File size: 3,662 Bytes
d76b924
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#!/usr/bin/env python3
import argparse
import json
import sys
import xml.etree.ElementTree as ET
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
MANIFEST = ROOT / "manifest" / "assets.jsonl"


def load_manifest():
    entries = {}
    if not MANIFEST.exists():
        return entries
    for line_no, line in enumerate(MANIFEST.read_text().splitlines(), start=1):
        line = line.strip()
        if not line:
            continue
        try:
            row = json.loads(line)
        except json.JSONDecodeError as exc:
            raise RuntimeError(f"{MANIFEST}:{line_no}: invalid JSON: {exc}") from exc
        entries[row.get("path")] = row
    return entries


def parse_simple_yaml(path):
    data = {}
    current_key = None
    list_mode = False
    for raw in path.read_text().splitlines():
        if not raw.strip() or raw.lstrip().startswith("#"):
            continue
        if raw.startswith("  - ") and current_key:
            data.setdefault(current_key, []).append(raw.strip()[2:].strip())
            continue
        if ":" in raw and not raw.startswith(" "):
            key, value = raw.split(":", 1)
            key = key.strip()
            value = value.strip()
            current_key = key
            if value == "":
                data[key] = []
                list_mode = True
            else:
                data[key] = value.strip('"').strip("'")
                list_mode = False
    return data


def validate_one(asset_dir, manifest):
    errors = []
    asset_dir = asset_dir.resolve()
    rel = asset_dir.relative_to(ROOT).as_posix()

    metadata_path = asset_dir / "metadata.yaml"
    if not metadata_path.exists():
        errors.append(f"missing metadata.yaml: {metadata_path}")
        metadata = {}
    else:
        metadata = parse_simple_yaml(metadata_path)

    entry_file = metadata.get("entry_file", "model.xml")
    entry_path = asset_dir / entry_file
    if not entry_path.exists():
        errors.append(f"missing entry_file: {entry_path}")

    if rel not in manifest:
        errors.append(f"missing manifest entry for path: {rel}")

    if entry_path.exists() and entry_path.is_file() and entry_path.suffix == ".xml":
        try:
            root = ET.parse(entry_path).getroot()
            for elem in root.iter():
                file_ref = elem.get("file")
                if file_ref:
                    ref_path = (entry_path.parent / file_ref).resolve()
                    if not ref_path.exists():
                        errors.append(f"missing XML file reference: {entry_path} -> {file_ref}")
        except ET.ParseError as exc:
            errors.append(f"invalid XML: {entry_path}: {exc}")

    return errors


def discover_assets():
    assets_root = ROOT / "assets"
    return sorted(p.parent for p in assets_root.rglob("metadata.yaml"))


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("asset_dir", nargs="?")
    parser.add_argument("--all", action="store_true")
    args = parser.parse_args()

    manifest = load_manifest()

    if args.all:
        asset_dirs = discover_assets()
    elif args.asset_dir:
        asset_dirs = [Path(args.asset_dir)]
    else:
        parser.error("provide asset_dir or --all")

    all_errors = []
    for asset_dir in asset_dirs:
        errors = validate_one(Path(asset_dir), manifest)
        if errors:
            all_errors.extend(errors)

    if all_errors:
        for error in all_errors:
            print(f"ERROR: {error}", file=sys.stderr)
        return 1

    print(f"validated_assets={len(asset_dirs)}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())