#!/usr/bin/env python3 """Checks that the candidates in a folder follow the submission format in README.md: JSON shape, d, and steps that are coordinates from 0 to d - 1. It does not follow the path, so it does not check that it is a snake. usage: python3 tools/check_format.py routes/ (or one .json file) """ import json import pathlib import sys def errors(candidate): d, t = candidate.get("d"), candidate.get("transitions") if type(d) is not int or d not in (13, 14, 15, 16): return ['"d" must be one of the integers 13, 14, 15, 16'] if isinstance(t, str): t = ["0123456789abcdefghijklmnopqrstuvwxyz".find(c) for c in t.lower() if not c.isspace()] if not isinstance(t, list) or not t or len(t) >= 2 ** d: return [f'"transitions" must be a nonempty string or list of fewer than {2 ** d} steps'] bad = [s for s in t if type(s) is not int or not 0 <= s < d] return [f"{len(bad)} steps are not coordinates from 0 to {d - 1}"] if bad else [] if len(sys.argv) != 2: sys.exit(__doc__) target = pathlib.Path(sys.argv[1]) if target.is_file() and target.suffix != ".json": sys.exit(f"{target}: candidates are .json files") files = [target] if target.is_file() else sorted(target.rglob("*.json")) found = bad = 0 for path in files: if path.stat().st_size > 1_000_000: print(f"{path}: over 1 MB") bad += 1 continue try: candidate = json.loads(path.read_text()) except Exception as exc: print(f"{path}: not valid JSON ({exc})") bad += 1 continue if not isinstance(candidate, dict) or "transitions" not in candidate: print(f'{path}: not a candidate (no "transitions" key); ignored') continue found += 1 problems = errors(candidate) print(f"{path}: {'; '.join(problems)}" if problems else f"{path}: ok (d{candidate['d']})") bad += bool(problems) print(f"{found} candidates, {bad} files with format errors") sys.exit(1 if bad else 0)