my-homelab-configs/scripts/render-website-tree.py

65 lines
3.1 KiB
Python

#!/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')
parser.add_argument('--output', type=Path, help='write generated data to this path')
args = parser.parse_args()
output = args.output or TREE_DATA
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 output.exists() or output.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:
output.write_text(source, encoding='utf-8')
print(f'Wrote {output}')
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())