Ansel 0.0
A darktable fork - bloat + design vision
Loading...
Searching...
No Matches
validate_json_schema.py
Go to the documentation of this file.
1#!/usr/bin/python3
2# This file is part of darktable,
3# Copyright (C) 2026 Ansel contributors.
4#
5# darktable is free software: you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation, either version 3 of the License, or
8# (at your option) any later version.
9#
10# darktable is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with darktable. If not, see <http://www.gnu.org/licenses/>.
17#
18# Validate a JSON instance file against a JSON schema file.
19#
20# Replaces the `jsonschema` command-line tool, which the jsonschema library
21# itself deprecated in favor of the separate `check-jsonschema` package
22# (not packaged for every distro we build on). Calling the validation API
23# directly avoids the CLI's deprecation warning and the extra dependency.
24
25import json
26import os
27import sys
28
29
30def _validated_path(path_str):
31 base_dir = os.path.realpath(os.getcwd())
32 path = os.path.realpath(os.path.join(base_dir, path_str))
33 try:
34 confined = os.path.commonpath([path, base_dir]) == base_dir
35 except ValueError:
36 # raised on Windows when the two paths are on different drives
37 confined = False
38 if not confined:
39 print(f"error: path escapes the working directory: {path_str}", file=sys.stderr)
40 sys.exit(2)
41 if not os.path.isfile(path):
42 print(f"error: not a file: {path_str}", file=sys.stderr)
43 sys.exit(2)
44 return path
45
46
47def main():
48 if len(sys.argv) != 3:
49 print(f"usage: {sys.argv[0]} <instance.json> <schema.json>", file=sys.stderr)
50 return 2
51
52 import jsonschema
53
54 instance_path = _validated_path(sys.argv[1])
55 schema_path = _validated_path(sys.argv[2])
56
57 with open(instance_path, encoding="utf-8") as f:
58 instance = json.load(f)
59 with open(schema_path, encoding="utf-8") as f:
60 schema = json.load(f)
61
62 validator_cls = jsonschema.validators.validator_for(schema)
63 validator_cls.check_schema(schema)
64 validator = validator_cls(schema)
65
66 errors = sorted(validator.iter_errors(instance), key=str)
67 for error in errors:
68 print(error, file=sys.stderr)
69
70 return 1 if errors else 0
71
72
73if __name__ == "__main__":
74 sys.exit(main())