#!/usr/bin/env python3 """Checks that the candidates in a folder follow the submission format in README.md: JSON shape, n, and words that are distinct strings of n binary digits. It does not check that no two words share a descendant. usage: python3 tools/check_format.py routes/ (or one .json file) """ import json import pathlib import sys def errors(candidate): n, words = candidate.get("n"), candidate.get("words") if type(n) is not int or n not in (16, 17, 18): return ['"n" must be one of the integers 16, 17, 18'] if not isinstance(words, list) or not words: return ['"words" must be a nonempty list'] bad = [w for w in words if not isinstance(w, str) or len(w) != n or not set(w) <= {"0", "1"}] if bad: return [f"{len(bad)} words are not strings of {n} binary digits, such as {str(bad[0])[:40]!r}"] return [] if len(set(words)) == len(words) else [f"{len(words) - len(set(words))} words are repeated"] 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 "words" not in candidate: print(f'{path}: not a candidate (no "words" key); ignored') continue found += 1 problems = errors(candidate) print(f"{path}: {'; '.join(problems)}" if problems else f"{path}: ok (n{candidate['n']}, {len(candidate['words'])} words)") bad += bool(problems) print(f"{found} candidates, {bad} files with format errors") sys.exit(1 if bad else 0)