initial commit
This commit is contained in:
commit
88c14b627e
224 files changed
+17204
No files matched your search
@@ -0,0 +1,324 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Merge split OpenAPI schema files without changing their schema semantics."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import unquote, urlsplit
|
||||
|
||||
import yaml
|
||||
|
||||
SCHEMA_FILE_PRIORITY = {"common_schemas.yml": 0}
|
||||
SCHEMA_PREFIXES = ("response.", "request.", "v1.", "jwt.", "entity.")
|
||||
|
||||
|
||||
class MergeError(Exception):
|
||||
"""Raised when a contract cannot be merged safely."""
|
||||
|
||||
|
||||
def normalize_schema_name(name: str) -> str:
|
||||
"""Remove one known namespace prefix from a schema name."""
|
||||
for prefix in SCHEMA_PREFIXES:
|
||||
if name.startswith(prefix):
|
||||
return name[len(prefix) :]
|
||||
return name
|
||||
|
||||
|
||||
def schema_files(contract_root: Path) -> list[Path]:
|
||||
"""Return split schema files in stable order."""
|
||||
schemas_dir = contract_root / "components" / "schemas"
|
||||
return sorted(
|
||||
schemas_dir.glob("*_schemas.yml"),
|
||||
key=lambda path: (SCHEMA_FILE_PRIORITY.get(path.name, 100), path.name),
|
||||
)
|
||||
|
||||
|
||||
def load_yaml(path: Path) -> Any:
|
||||
try:
|
||||
with path.open(encoding="utf-8") as stream:
|
||||
return yaml.safe_load(stream)
|
||||
except (OSError, yaml.YAMLError) as exc:
|
||||
raise MergeError(f"cannot read YAML file {path}: {exc}") from exc
|
||||
|
||||
|
||||
def pointer_parts(fragment: str) -> list[str]:
|
||||
"""Decode a JSON Pointer stored in a URI fragment."""
|
||||
if not fragment:
|
||||
return []
|
||||
pointer = unquote(fragment)
|
||||
if not pointer.startswith("/"):
|
||||
return []
|
||||
return [part.replace("~1", "/").replace("~0", "~") for part in pointer[1:].split("/")]
|
||||
|
||||
|
||||
def pointer_fragment(parts: list[str]) -> str:
|
||||
"""Encode path segments as a JSON Pointer fragment."""
|
||||
encoded = [part.replace("~", "~0").replace("/", "~1") for part in parts]
|
||||
return "#" + "".join(f"/{part}" for part in encoded)
|
||||
|
||||
|
||||
def reference_target(
|
||||
reference: str,
|
||||
source_path: Path,
|
||||
contract_root: Path,
|
||||
merged_path: Path,
|
||||
) -> tuple[Path | None, list[str]]:
|
||||
"""Resolve a local reference target and its pointer without opening it."""
|
||||
parsed = urlsplit(reference)
|
||||
parts = pointer_parts(parsed.fragment)
|
||||
if parsed.scheme or parsed.netloc:
|
||||
return None, parts
|
||||
if not parsed.path:
|
||||
return source_path.resolve(), parts
|
||||
|
||||
target = (source_path.parent / unquote(parsed.path)).resolve()
|
||||
if target == merged_path.resolve():
|
||||
return merged_path.resolve(), parts
|
||||
if not target.is_relative_to(contract_root.resolve()):
|
||||
return None, parts
|
||||
return target, parts
|
||||
|
||||
|
||||
def rewrite_schema_reference(
|
||||
reference: str,
|
||||
source_path: Path,
|
||||
contract_root: Path,
|
||||
merged_path: Path,
|
||||
name_mapping: dict[str, str],
|
||||
schema_paths: set[Path],
|
||||
) -> str:
|
||||
parsed = urlsplit(reference)
|
||||
parts = pointer_parts(parsed.fragment)
|
||||
if len(parts) < 2 or parts[0] != "schemas":
|
||||
return reference
|
||||
|
||||
target, _ = reference_target(reference, source_path, contract_root, merged_path)
|
||||
points_to_split_file = target in schema_paths
|
||||
points_to_merged_file = target == merged_path.resolve()
|
||||
if not points_to_split_file and not points_to_merged_file:
|
||||
return reference
|
||||
|
||||
old_name = parts[1]
|
||||
new_name = name_mapping.get(old_name)
|
||||
if new_name is None:
|
||||
raise MergeError(
|
||||
f"unresolved schema reference in {source_path}: {reference!r}"
|
||||
)
|
||||
return pointer_fragment([new_name, *parts[2:]])
|
||||
|
||||
|
||||
def rewrite_schema_references(
|
||||
value: Any,
|
||||
source_path: Path,
|
||||
contract_root: Path,
|
||||
merged_path: Path,
|
||||
name_mapping: dict[str, str],
|
||||
schema_paths: set[Path],
|
||||
) -> Any:
|
||||
"""Rewrite schema pointers recursively in dictionaries and lists."""
|
||||
if isinstance(value, dict):
|
||||
rewritten: dict[Any, Any] = {}
|
||||
for key, item in value.items():
|
||||
if key == "$ref" and isinstance(item, str):
|
||||
rewritten[key] = rewrite_schema_reference(
|
||||
item,
|
||||
source_path,
|
||||
contract_root,
|
||||
merged_path,
|
||||
name_mapping,
|
||||
schema_paths,
|
||||
)
|
||||
else:
|
||||
rewritten[key] = rewrite_schema_references(
|
||||
item,
|
||||
source_path,
|
||||
contract_root,
|
||||
merged_path,
|
||||
name_mapping,
|
||||
schema_paths,
|
||||
)
|
||||
return rewritten
|
||||
if isinstance(value, list):
|
||||
return [
|
||||
rewrite_schema_references(
|
||||
item,
|
||||
source_path,
|
||||
contract_root,
|
||||
merged_path,
|
||||
name_mapping,
|
||||
schema_paths,
|
||||
)
|
||||
for item in value
|
||||
]
|
||||
return value
|
||||
|
||||
|
||||
def collect_references(value: Any, location: str = "$") -> list[tuple[str, str]]:
|
||||
"""Return every nested $ref and its YAML location."""
|
||||
references: list[tuple[str, str]] = []
|
||||
if isinstance(value, dict):
|
||||
for key, item in value.items():
|
||||
child_location = f"{location}.{key}"
|
||||
if key == "$ref" and isinstance(item, str):
|
||||
references.append((item, child_location))
|
||||
else:
|
||||
references.extend(collect_references(item, child_location))
|
||||
elif isinstance(value, list):
|
||||
for index, item in enumerate(value):
|
||||
references.extend(collect_references(item, f"{location}[{index}]"))
|
||||
return references
|
||||
|
||||
|
||||
def find_stale_route_references(
|
||||
contract_root: Path,
|
||||
merged_path: Path,
|
||||
schema_paths: set[Path],
|
||||
name_mapping: dict[str, str],
|
||||
) -> list[str]:
|
||||
"""Find routes that still point through the removed schemas/ wrapper."""
|
||||
routes_dir = contract_root / "routes"
|
||||
if not routes_dir.exists():
|
||||
return []
|
||||
|
||||
stale: list[str] = []
|
||||
for route_path in sorted(routes_dir.glob("*.yml")):
|
||||
route_data = load_yaml(route_path)
|
||||
for reference, location in collect_references(route_data):
|
||||
target, parts = reference_target(
|
||||
reference, route_path, contract_root, merged_path
|
||||
)
|
||||
points_to_split_file = target in schema_paths
|
||||
points_to_wrapped_merged_schemas = (
|
||||
target == merged_path.resolve()
|
||||
and len(parts) >= 2
|
||||
and parts[0] == "schemas"
|
||||
)
|
||||
if points_to_split_file or points_to_wrapped_merged_schemas:
|
||||
schema_name = parts[1] if len(parts) >= 2 else "<missing>"
|
||||
normalized_name = name_mapping.get(
|
||||
schema_name, normalize_schema_name(schema_name)
|
||||
)
|
||||
suffix = parts[2:] if len(parts) >= 2 and parts[0] == "schemas" else []
|
||||
replacement_path = os.path.relpath(
|
||||
merged_path, route_path.parent
|
||||
).replace(os.sep, "/")
|
||||
replacement = f"{replacement_path}{pointer_fragment([normalized_name, *suffix])}"
|
||||
stale.append(
|
||||
f"{route_path}:{location}: {reference!r} should use {replacement!r}"
|
||||
)
|
||||
return stale
|
||||
|
||||
|
||||
def atomic_write(path: Path, contents: str) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary_path: Path | None = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(
|
||||
mode="w",
|
||||
encoding="utf-8",
|
||||
dir=path.parent,
|
||||
prefix=f".{path.name}.",
|
||||
suffix=".tmp",
|
||||
delete=False,
|
||||
) as stream:
|
||||
temporary_path = Path(stream.name)
|
||||
stream.write(contents)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
temporary_path.replace(path)
|
||||
finally:
|
||||
if temporary_path is not None and temporary_path.exists():
|
||||
temporary_path.unlink()
|
||||
|
||||
|
||||
def merge_contract(contract_root: Path) -> Path:
|
||||
contract_root = contract_root.resolve()
|
||||
if not contract_root.is_dir():
|
||||
raise MergeError(f"contract root is not a directory: {contract_root}")
|
||||
|
||||
merged_path = contract_root / "components" / "schemas.yml"
|
||||
files = schema_files(contract_root)
|
||||
schema_paths = {path.resolve() for path in files}
|
||||
schemas: dict[str, Any] = {}
|
||||
origins: dict[str, tuple[Path, str]] = {}
|
||||
name_mapping: dict[str, str] = {}
|
||||
|
||||
for path in files:
|
||||
document = load_yaml(path)
|
||||
if document is None:
|
||||
continue
|
||||
if not isinstance(document, dict) or not isinstance(document.get("schemas"), dict):
|
||||
raise MergeError(f"{path} must contain a mapping named 'schemas'")
|
||||
|
||||
for old_name, schema in document["schemas"].items():
|
||||
if not isinstance(old_name, str) or not old_name:
|
||||
raise MergeError(f"{path} contains a schema with an empty or non-string name")
|
||||
new_name = normalize_schema_name(old_name)
|
||||
if not new_name:
|
||||
raise MergeError(f"{path} schema {old_name!r} normalizes to an empty name")
|
||||
if new_name in schemas:
|
||||
previous_path, previous_name = origins[new_name]
|
||||
raise MergeError(
|
||||
f"duplicate normalized schema name {new_name!r}: "
|
||||
f"{previous_path} ({previous_name!r}) and {path} ({old_name!r})"
|
||||
)
|
||||
schemas[new_name] = schema
|
||||
origins[new_name] = (path, old_name)
|
||||
name_mapping[old_name] = new_name
|
||||
|
||||
merged_schemas: dict[str, Any] = {}
|
||||
for new_name, schema in schemas.items():
|
||||
source_path, _ = origins[new_name]
|
||||
merged_schemas[new_name] = rewrite_schema_references(
|
||||
schema,
|
||||
source_path,
|
||||
contract_root,
|
||||
merged_path,
|
||||
name_mapping,
|
||||
schema_paths,
|
||||
)
|
||||
|
||||
stale_references = find_stale_route_references(
|
||||
contract_root, merged_path, schema_paths, name_mapping
|
||||
)
|
||||
if stale_references:
|
||||
details = "\n".join(f" {reference}" for reference in stale_references)
|
||||
raise MergeError(f"stale schema references in handwritten routes:\n{details}")
|
||||
|
||||
output = yaml.safe_dump(
|
||||
merged_schemas,
|
||||
allow_unicode=True,
|
||||
default_flow_style=False,
|
||||
sort_keys=False,
|
||||
width=1000,
|
||||
)
|
||||
atomic_write(merged_path, output)
|
||||
return merged_path
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument(
|
||||
"contract_root",
|
||||
type=Path,
|
||||
help="directory containing components/schemas and routes (for example api/core or api/ml)",
|
||||
)
|
||||
arguments = parser.parse_args(argv)
|
||||
|
||||
try:
|
||||
output_path = merge_contract(arguments.contract_root)
|
||||
except MergeError as exc:
|
||||
print(f"merge-schemas: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
print(f"Merged schemas into {output_path}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user