Files
structured-media-builder-OPEN/scripts/check_repository.py
T

71 lines
3.4 KiB
Python
Raw Normal View History

2026-10-17 14:59:30 -06:00
"""Check repository JSON, document links, manifest paths, and local schema references."""
import ast
import json
import re
from pathlib import Path
from urllib.parse import unquote
from jsonschema import Draft202012Validator
ROOT = Path(__file__).resolve().parents[1]
SKIP = {'build', '.git', '__pycache__', '.test-work', '.venv'}
def check():
files = [p for p in ROOT.rglob('*') if p.is_file() and not (set(p.relative_to(ROOT).parts) & SKIP)]
count = {'json': 0, 'markdown_links': 0, 'schema_refs': 0, 'python': 0}
errors = []
def local_ref(base, ref):
filename, _, pointer = ref.partition('#')
path = (base.parent / filename).resolve() if filename else base
assert path.is_relative_to(ROOT) and path.is_file(), f'Missing/outside reference {ref}'
doc = json.loads(path.read_text(encoding='utf-8-sig'))
for key in pointer.lstrip('/').split('/') if pointer else []:
key = unquote(key).replace('~1', '/').replace('~0', '~')
doc = doc[int(key)] if isinstance(doc, list) else doc[key]
def walk_refs(value, base):
if isinstance(value, dict):
for key, item in value.items():
if key == '$ref' and not item.startswith(('https:', 'http:')):
local_ref(base, item)
count['schema_refs'] += 1
else:
walk_refs(item, base)
elif isinstance(value, list):
for item in value:
walk_refs(item, base)
for path in files:
try:
if path.suffix in {'.md', '.py', '.json', '.txt', '.vtt'} or path.name in {'.gitignore', '.gitattributes', 'VERSION'}:
text = path.read_text(encoding='utf-8-sig')
assert all(line == line.rstrip(' \t') for line in text.splitlines()), 'Trailing whitespace'
assert not re.search(r'-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{30,}', text), 'Potential credential pattern'
if path.suffix == '.json':
value = json.loads(path.read_text(encoding='utf-8-sig'))
count['json'] += 1
walk_refs(value, path)
if path.name.endswith('.schema.json'):
Draft202012Validator.check_schema(value)
elif path.suffix == '.py':
ast.parse(path.read_text(encoding='utf-8'), filename=str(path))
count['python'] += 1
elif path.suffix == '.md':
for target in re.findall(r'\[[^\]]*\]\(([^)]+)\)', path.read_text(encoding='utf-8')):
if target.startswith(('http:', 'https:', '#', 'mailto:')):
continue
linked = (path.parent / unquote(target.split('#')[0])).resolve()
assert linked.is_relative_to(ROOT) and linked.exists(), f'Missing local link {target}'
count['markdown_links'] += 1
except Exception as error:
errors.append(f'{path.relative_to(ROOT)}: {error}')
manifest = json.loads((ROOT/'repository.json').read_text(encoding='utf-8'))
for name in list(manifest['entrypoints'].values()) + [v['path'] for v in manifest['contents']]:
if not (ROOT/name).exists():
errors.append('Missing manifest path: ' + name)
if errors:
raise ValueError('\n'.join(errors))
print(json.dumps({'valid': True, **count}, indent=2))
if __name__ == '__main__':
check()