#!/usr/bin/env python3 """Validate and generate the public Christmas tree ornament data.""" import argparse import importlib.util import json import re import sys from pathlib import Path ROOT = Path(__file__).resolve().parent.parent TREE_MODEL = ROOT / 'apps/website/architecture/tree-model.json' TREE_DATA = ROOT / 'apps/website/architecture/tree-data.json' ARCH_MODEL = ROOT / 'apps/website/architecture/model.json' ARCH_SCRIPT = ROOT / 'scripts/render-website-architecture.py' def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--check', action='store_true', help='check the generated data without writing') args = parser.parse_args() try: spec = importlib.util.spec_from_file_location('architecture_renderer', ARCH_SCRIPT) architecture = importlib.util.module_from_spec(spec) spec.loader.exec_module(architecture) data = architecture.inventory() architecture.render(json.loads(ARCH_MODEL.read_text(encoding='utf-8')), data) source = TREE_MODEL.read_text(encoding='utf-8') ornaments = json.loads(source)['ornaments'] if not isinstance(ornaments, list) or len(ornaments) != 12: raise ValueError('The tree has twelve positions; provide exactly twelve ornaments') names = set() for ornament in ornaments: if not isinstance(ornament, dict): raise ValueError('Every ornament must be an object') for key, limit in [('name', 12), ('detail', 18), ('category', 20), ('description', 180)]: value = ornament.get(key) if not isinstance(value, str) or not value.strip() or len(value) > limit: raise ValueError(f'Invalid {key} for ornament {ornament.get("name", "?")}') if ornament['name'] in names: raise ValueError(f'Duplicate ornament: {ornament["name"]}') names.add(ornament['name']) if ornament.get('color') not in {'blue', 'gold', 'red', 'purple', 'teal', 'green'}: raise ValueError(f'Invalid color for {ornament["name"]}') if not re.fullmatch(r'case-[a-z0-9-]+', ornament.get('link', '')): raise ValueError(f'Invalid local case-study link for {ornament["name"]}') if ornament.get('inventory'): architecture.lookup(data, ornament['inventory']) if args.check: if not TREE_DATA.exists() or TREE_DATA.read_text(encoding='utf-8') != source: raise ValueError('Tree data is stale; run python3 scripts/render-website-tree.py') print('Website Christmas tree is current.') else: TREE_DATA.write_text(source, encoding='utf-8') print(f'Wrote {TREE_DATA.relative_to(ROOT)}') except (OSError, ValueError, KeyError, TypeError, AttributeError, json.JSONDecodeError) as exc: print(f'Website Christmas tree: {exc}', file=sys.stderr) return 1 return 0 if __name__ == '__main__': sys.exit(main())