|
| 1 | +"""`otdf-sdk-mgr schema` subcommands. |
| 2 | +
|
| 3 | +Emit canonical JSON Schemas for the Pydantic models in `otdf_sdk_mgr.schema` |
| 4 | +so agents (and humans) can introspect the on-disk YAML formats without |
| 5 | +running `python -c` against the package. The generated files live under |
| 6 | +`xtest/schema/` and are kept in sync via `tests/test_schema_sync.py`. |
| 7 | +""" |
| 8 | + |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +import json |
| 12 | +from pathlib import Path |
| 13 | +from typing import Annotated |
| 14 | + |
| 15 | +import typer |
| 16 | +from otdf_sdk_mgr.schema import Instance, Scenario |
| 17 | + |
| 18 | +schema_app = typer.Typer(help="Emit JSON Schemas for the scenario/instance models.") |
| 19 | + |
| 20 | +# (model_class, output_filename). Add new models here and `schema dump` |
| 21 | +# will pick them up automatically. |
| 22 | +SCHEMAS: tuple[tuple[type, str], ...] = ( |
| 23 | + (Scenario, "scenario.schema.json"), |
| 24 | + (Instance, "instance.schema.json"), |
| 25 | +) |
| 26 | + |
| 27 | + |
| 28 | +def render(model: type) -> str: |
| 29 | + """Render `model.model_json_schema()` as a deterministic JSON string. |
| 30 | +
|
| 31 | + Sorted keys and a trailing newline so byte-equality comparisons in the |
| 32 | + sync test are stable. |
| 33 | + """ |
| 34 | + return json.dumps(model.model_json_schema(), indent=2, sort_keys=True) + "\n" |
| 35 | + |
| 36 | + |
| 37 | +@schema_app.command("dump") |
| 38 | +def dump( |
| 39 | + out_dir: Annotated[ |
| 40 | + Path, |
| 41 | + typer.Option( |
| 42 | + "--out-dir", |
| 43 | + help="Directory to write *.schema.json files into.", |
| 44 | + ), |
| 45 | + ] = Path("xtest/schema"), |
| 46 | +) -> None: |
| 47 | + """Write JSON Schemas for every canonical scenario/instance model. |
| 48 | +
|
| 49 | + Overwrites existing files. Re-run whenever a Pydantic model changes; |
| 50 | + the committed schemas in xtest/schema/ are otherwise the source of |
| 51 | + truth that the scenario-authoring skills read. |
| 52 | + """ |
| 53 | + out_dir.mkdir(parents=True, exist_ok=True) |
| 54 | + for model, filename in SCHEMAS: |
| 55 | + path = out_dir / filename |
| 56 | + path.write_text(render(model), encoding="utf-8") |
| 57 | + typer.echo(f" wrote {path}") |
0 commit comments