#!/usr/bin/env python3 """Validate native recipe JSON or a documented recipes[] transport wrapper. Requires an already installed jsonschema. Downloads only the authoritative schema, never input-supplied URLs or references. Validation is not publication approval. """ import argparse from collections import Counter import re import json from pathlib import Path import sys from urllib.request import urlopen import jsonschema SCHEMA_URL = 'https://francespopsicle.com/data/recipe.schema.json' def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('input', type=Path, help='UTF-8 JSON file, regardless of extension') parser.add_argument('--schema', type=Path, help='Local authoritative schema for offline use') args = parser.parse_args() try: data = json.loads(args.input.read_text(encoding='utf-8')) if args.schema: schema = json.loads(args.schema.read_text(encoding='utf-8')) else: with urlopen(SCHEMA_URL, timeout=20) as response: schema = json.loads(response.read().decode('utf-8')) validator_type = jsonschema.validators.validator_for(schema) validator_type.check_schema(schema) validator = validator_type(schema, format_checker=jsonschema.FormatChecker()) errors = [] wrapped = isinstance(data, dict) and 'recipes' in data if wrapped: # batchVersion is preferred. Existing exported envelopes used schemaVersion. versions = [data[key] for key in ('batchVersion', 'schemaVersion') if key in data] if not versions or any(value != '1.0' for value in versions): errors.append('transport: batchVersion (or legacy envelope schemaVersion) must be "1.0"') records = data['recipes'] if not isinstance(records, list) or not records: errors.append('transport: recipes must be a nonempty array') records = [] else: records = [data] seen = set() for index, record in enumerate(records, 1): schema_errors = list(validator.iter_errors(record)) errors.extend(f'recipe {index} schema: {e.message}' for e in schema_errors) if schema_errors: continue prefix = f'recipe {index} semantic: ' slug = record['slug'] if not re.fullmatch(r'[a-z0-9]+(?:-[a-z0-9]+)*', slug): errors.append(prefix + 'slug must use lowercase ASCII words separated by single hyphens') if slug in seen: errors.append(prefix + f'duplicate slug {slug!r}') seen.add(slug) if record['schemaVersion'] != '1.2': errors.append(prefix + 'current native schemaVersion must be "1.2"') if record['url'] != f'https://francespopsicle.com/recipes/{slug}/': errors.append(prefix + 'url must equal the canonical recipe URL for its slug') if record['dataUrl'] != f'https://francespopsicle.com/recipes/data/{slug}.json': errors.append(prefix + 'dataUrl must equal the canonical JSON URL for its slug') if 'ingredientGroups' in record: flattened = [] for group in record['ingredientGroups']: if (not isinstance(group.get('title'), str) or not isinstance(group.get('items'), list) or not all(isinstance(item, str) for item in group['items'])): errors.append(prefix + 'each ingredient group needs a string title and string-array items') break flattened.extend(group['items']) else: if Counter(flattened) != Counter(record['ingredients']): errors.append(prefix + 'ingredientGroups must flatten to the ingredients multiset, including duplicates') if 'ingredientDetails' in record: if [detail['text'] for detail in record['ingredientDetails']] != record['ingredients']: errors.append(prefix + 'ingredientDetails must match ingredients one-to-one in display order') holds = data.get('publicationHolds', []) if wrapped else [] hold_slugs = set() if not isinstance(holds, list): errors.append('transport: publicationHolds must be an array') holds = [] for hold in holds: if not isinstance(hold, dict): errors.append('transport: each publication hold needs slug and reason strings') continue slug, reason = hold.get('slug'), hold.get('reason') if not isinstance(slug, str) or not isinstance(reason, str) or not reason.strip(): errors.append('transport: each publication hold needs slug and nonempty reason strings') continue if slug not in seen: errors.append('transport: publication hold refers to a missing or invalid recipe') if slug in hold_slugs: errors.append('transport: duplicate publication hold') hold_slugs.add(slug) if errors: print('\n'.join(errors), file=sys.stderr) return 1 print(f'OK: {len(records)} native recipe(s); schema and semantic checks passed.') if holds: print(f'NOTICE: {len(holds)} publication hold(s) remain in effect. Validation does not clear them.') return 0 except (OSError, ValueError, jsonschema.exceptions.SchemaError) as exc: print(f'ERROR: {exc}', file=sys.stderr) return 2 if __name__ == '__main__': raise SystemExit(main())