|
| 1 | +""" |
| 2 | +This Python module: |
| 3 | + - Searches for JSON Schema templates with the name values.schema.tmpl.json |
| 4 | + - Dereferences any $refs contained in those files |
| 5 | + - Outputs the new Schema to a values.schema.json file in the same directory |
| 6 | +""" |
| 7 | + |
| 8 | +import sys |
| 9 | +import json |
| 10 | +from typing import List, Dict, Any |
| 11 | +from pathlib import Path |
| 12 | + |
| 13 | +# External library dependency |
| 14 | +# Install with 'pip install jsonref' |
| 15 | +import jsonref |
| 16 | + |
| 17 | +# File to write the dereferenced JSON Schema to |
| 18 | +JSONSCHEMA_NAME = "values.schema.json" |
| 19 | +# File that contains the JSON Schema that needs dereferencing |
| 20 | +JSONSCHEMA_TEMPLATE_NAME = "values.schema.tmpl.json" |
| 21 | + |
| 22 | +def load_template_schema(schema_dir: Path) -> Dict[str, Any]: |
| 23 | + """Load the schema template values.schema.tmpl.json""" |
| 24 | + with open(schema_dir / JSONSCHEMA_TEMPLATE_NAME, "r", encoding="utf-8") as f: |
| 25 | + return json.loads(f.read()) |
| 26 | + |
| 27 | +def save(schema_dir: Path, schema_data: Any): |
| 28 | + """Save the dereferenced schema to values.schema.json""" |
| 29 | + with open(schema_dir / JSONSCHEMA_NAME, "w", encoding="utf-8") as f: |
| 30 | + json.dump(schema_data, f, indent=4, sort_keys=True) |
| 31 | + |
| 32 | +if __name__ == '__main__': |
| 33 | + # Search for all values.schema.tmpl.json files |
| 34 | + schema_templates = [p.parent for p in Path(".").rglob(JSONSCHEMA_TEMPLATE_NAME)] |
| 35 | + |
| 36 | + # Create a list to hold any exceptions |
| 37 | + errors: List[BaseException] = [] |
| 38 | + # Iterate over the List of found schema templates |
| 39 | + for schema_template in schema_templates: |
| 40 | + try: |
| 41 | + # Load the schema into a variable as JSON |
| 42 | + st = load_template_schema(schema_template) |
| 43 | + # Dereference all of the $refs |
| 44 | + s = jsonref.replace_refs(st) |
| 45 | + # Save the dereferenced JSON |
| 46 | + save(schema_template, s) |
| 47 | + except BaseException as e: |
| 48 | + # Print any errors to the screen |
| 49 | + print(f"Could not process schema for '{schema_template}': {e}") |
| 50 | + # Append any exceptions to the errors List |
| 51 | + errors.append(e) |
| 52 | + if errors: |
| 53 | + # Exit with status 1 if any exceptions were thrown |
| 54 | + sys.exit(1) |
0 commit comments