"""Check a SaaCIP 0.2 document or message against its JSON Schema. python validate.py python validate.py terms my-terms.json python validate.py capability-manifest saacip-manifest.yaml python validate.py receipt receipts.jsonl (every line is checked) is the file name without ".schema.json": terms, receipt, statement, capability-manifest, declared-actions, enrol-request, and so on. Run with no arguments to see the full list. The file may be JSON, YAML (for the two documents people write: the capability manifest and the declared actions file; it is converted to JSON first, as the specification requires) or JSON Lines (one document per line). Exit code 0: valid. 1: problems found, listed one per line. 2: wrong usage. Needs the "jsonschema" and "referencing" packages (pip install jsonschema referencing), and "pyyaml" for YAML files. Keep this file next to the "schemas" folder. SaaCIP 0.2, https://thesoftwarelens.com/saacip/ . Licensed under the Apache License 2.0. """ import json import os import sys HERE = os.path.dirname(os.path.abspath(__file__)) SCHEMAS = os.path.join(HERE, "schemas") BASE = "https://thesoftwarelens.com/saacip/0.2/schemas/" def schema_names(): """The schema names this folder holds, for example ["ack", "approval", ...].""" return sorted(f[:-len(".schema.json")] for f in os.listdir(SCHEMAS) if f.endswith(".schema.json")) _REGISTRY = None def _registry(): """All schemas, registered under their published $id so that $ref works offline.""" global _REGISTRY if _REGISTRY is None: from referencing import Registry, Resource resources = [] for name in schema_names(): with open(os.path.join(SCHEMAS, name + ".schema.json"), encoding="utf-8") as fh: resources.append((BASE + name + ".schema.json", Resource.from_contents(json.load(fh)))) _REGISTRY = Registry().with_resources(resources) return _REGISTRY def errors(kind, data): """Every way `data` fails the schema `kind`, as messages; an empty list means valid.""" from jsonschema import Draft202012Validator if kind not in schema_names(): raise KeyError(kind) schema = _registry().get_or_retrieve(BASE + kind + ".schema.json").value.contents validator = Draft202012Validator(schema, registry=_registry()) found = sorted(validator.iter_errors(data), key=lambda e: list(e.absolute_path)) return [f"{'/'.join(str(p) for p in e.absolute_path) or '(root)'}: {e.message}" for e in found] def load(path): """Read a JSON, YAML or JSON Lines file. JSON Lines gives a list, one item per line.""" with open(path, encoding="utf-8") as fh: text = fh.read() if path.endswith((".yaml", ".yml")): import yaml return yaml.safe_load(text) if path.endswith(".jsonl"): return [json.loads(line) for line in text.splitlines() if line.strip()] return json.loads(text) def main(argv): if len(argv) != 3: print(__doc__) print("Schemas in this folder:", ", ".join(schema_names())) return 2 kind, path = argv[1], argv[2] if kind not in schema_names(): print(f"No schema called {kind!r}. Choose one of: {', '.join(schema_names())}") return 2 if not os.path.isfile(path): print(f"No such file: {path}") return 2 try: import jsonschema, referencing # noqa: F401 except ImportError: print("This script needs the jsonschema and referencing packages: pip install jsonschema referencing") return 2 try: data = load(path) except ImportError: print("Reading YAML needs the pyyaml package: pip install pyyaml") return 2 except ValueError as exc: print(f"{path}: not valid JSON or YAML: {exc}") return 1 items = data if isinstance(data, list) else [data] bad = 0 for i, item in enumerate(items, 1): where = f"{path} line {i}" if len(items) > 1 else path for message in errors(kind, item): bad += 1 print(f"{where}: {message}") print("valid" if not bad else f"{bad} problem(s)") return 0 if not bad else 1 if __name__ == "__main__": sys.exit(main(sys.argv))