initial commit
This commit is contained in:
commit
88c14b627e
224 files changed
+17204
No files matched your search
@@ -0,0 +1,2 @@
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
|
||||
api_base_ref="${API_BASE_REF:-}"
|
||||
redocly="${REDOCLY:-}"
|
||||
codegen_python="${CODEGEN_PYTHON:-python3}"
|
||||
|
||||
if [[ -z "$api_base_ref" ]]; then
|
||||
echo "check-api-compat: set API_BASE_REF to a Git ref containing the previous API sources" >&2
|
||||
exit 2
|
||||
fi
|
||||
if [[ -z "$redocly" || ! -x "$redocly" ]]; then
|
||||
echo "check-api-compat: install the API tools with make -C api install first" >&2
|
||||
exit 2
|
||||
fi
|
||||
if ! git -C "$repo_root" rev-parse --verify "${api_base_ref}^{commit}" >/dev/null 2>&1; then
|
||||
echo "check-api-compat: API_BASE_REF does not resolve to a Git commit" >&2
|
||||
exit 2
|
||||
fi
|
||||
if ! git -C "$repo_root" ls-tree -r --name-only "$api_base_ref" -- api | grep -Eq '^api/(core/)?openapi\.yml$'; then
|
||||
echo "check-api-compat: API_BASE_REF has no prior public contract; compatibility comparison skipped"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
temporary_dir="$(mktemp -d "${TMPDIR:-/tmp}/lincodex-api-compat.XXXXXX")"
|
||||
trap 'rm -rf "$temporary_dir"' EXIT
|
||||
|
||||
git -C "$repo_root" archive --format=tar "$api_base_ref" api | tar -xf - -C "$temporary_dir"
|
||||
if [[ -f "$temporary_dir/api/core/openapi.yml" ]]; then
|
||||
previous_contract="$temporary_dir/api/core"
|
||||
else
|
||||
previous_contract="$temporary_dir/api"
|
||||
fi
|
||||
"$codegen_python" "$repo_root/scripts/merge-schemas.py" "$previous_contract"
|
||||
"$redocly" bundle "$previous_contract/openapi.yml" --output "$previous_contract/openapi.bundle.yml"
|
||||
"$redocly" lint --config "$repo_root/api/redocly.yaml" "$previous_contract/openapi.bundle.yml"
|
||||
go -C "$repo_root/backend" tool oasdiff breaking \
|
||||
"$previous_contract/openapi.bundle.yml" \
|
||||
"$repo_root/api/core/openapi.bundle.yml" \
|
||||
--fail-on ERR
|
||||
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Report changed or untracked generated outputs in the current checkout."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
GENERATED_PREFIXES = (
|
||||
"backend/internal/adapter/primary/http/api/",
|
||||
"backend/internal/adapter/secondary/ml/api/",
|
||||
"backend/internal/adapter/secondary/postgres/sqlc/",
|
||||
"frontend/src/shared/api/endpoints/",
|
||||
"frontend/src/shared/api/schemas/",
|
||||
)
|
||||
GENERATED_BASENAMES = {"wire_gen.go"}
|
||||
GENERATED_FILES = {
|
||||
"api/core/openapi.bundle.yml",
|
||||
"api/core/components/schemas.yml",
|
||||
"api/ml/openapi.bundle.yml",
|
||||
"api/ml/components/schemas.yml",
|
||||
"ml/src/lincodex_ml/api/models.py",
|
||||
}
|
||||
SOURCE_SUFFIXES = {".go", ".ts", ".tsx", ".js", ".sql", ".json", ".py"}
|
||||
GENERATED_HEADER = re.compile(
|
||||
rb"(?im)^\s*(?://|#|/\*|\*|<!--|--|;)\s*"
|
||||
rb"(?:code generated|generated by|this file was generated|@generated)\b"
|
||||
)
|
||||
|
||||
|
||||
def git_output(root: Path, *args: str) -> bytes:
|
||||
result = subprocess.run(
|
||||
["git", *args], cwd=root, stdout=subprocess.PIPE, stderr=subprocess.PIPE
|
||||
)
|
||||
if result.returncode != 0:
|
||||
detail = result.stderr.decode("utf-8", errors="replace").strip()
|
||||
raise RuntimeError(detail or f"git {' '.join(args)} failed")
|
||||
return result.stdout
|
||||
|
||||
|
||||
def is_generated(root: Path, relative_path: str) -> bool:
|
||||
normalized = relative_path.replace(os.sep, "/")
|
||||
if normalized.startswith("codegen/") or "/codegen/" in normalized:
|
||||
return False
|
||||
|
||||
if normalized in GENERATED_FILES or normalized.startswith(GENERATED_PREFIXES):
|
||||
return True
|
||||
if Path(normalized).name in GENERATED_BASENAMES:
|
||||
return True
|
||||
if Path(normalized).suffix.lower() not in SOURCE_SUFFIXES:
|
||||
return False
|
||||
|
||||
path = root / relative_path
|
||||
if not path.is_file():
|
||||
return False
|
||||
try:
|
||||
prefix = path.read_bytes()[:4096]
|
||||
except OSError:
|
||||
return False
|
||||
return GENERATED_HEADER.search(prefix) is not None
|
||||
|
||||
|
||||
def main() -> int:
|
||||
try:
|
||||
top = subprocess.run(
|
||||
["git", "rev-parse", "--show-toplevel"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
if top.returncode != 0:
|
||||
print(
|
||||
"check-generated: run this command from a Git working tree.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 2
|
||||
root = Path(os.fsdecode(top.stdout.rstrip(b"\n"))).resolve()
|
||||
git_output(root, "rev-parse", "--verify", "HEAD^{commit}")
|
||||
changed = git_output(
|
||||
root, "diff", "--name-only", "--diff-filter=ACMRTD", "-z", "HEAD", "--"
|
||||
)
|
||||
untracked = git_output(root, "ls-files", "--others", "--exclude-standard", "-z")
|
||||
except RuntimeError as error:
|
||||
print(f"check-generated: cannot inspect Git state: {error}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
drift: list[tuple[str, str]] = []
|
||||
for path in (os.fsdecode(part) for part in changed.split(b"\0") if part):
|
||||
if is_generated(root, path):
|
||||
drift.append(("changed", path))
|
||||
for path in (os.fsdecode(part) for part in untracked.split(b"\0") if part):
|
||||
if is_generated(root, path):
|
||||
drift.append(("untracked", path))
|
||||
|
||||
if drift:
|
||||
for state, path in sorted(set(drift)):
|
||||
if state == "changed":
|
||||
print(f"generated output differs from committed state: {path}", file=sys.stderr)
|
||||
else:
|
||||
print(f"untracked generated output is present: {path}", file=sys.stderr)
|
||||
print(
|
||||
"check-generated: regenerate outputs and commit the matching generator inputs and outputs.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
|
||||
print("check-generated: generated outputs match the committed state.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,293 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check project-owned Markdown links, language docs, routes, and imports."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from urllib.parse import unquote, urlsplit
|
||||
|
||||
|
||||
IGNORED_DIRS = {
|
||||
".git",
|
||||
".next",
|
||||
".pnpm-store",
|
||||
".pytest_cache",
|
||||
".ruff_cache",
|
||||
".mypy_cache",
|
||||
"__pycache__",
|
||||
"bin",
|
||||
"build",
|
||||
"coverage",
|
||||
"dist",
|
||||
"node_modules",
|
||||
"site-packages",
|
||||
"target",
|
||||
"vendor",
|
||||
"venv",
|
||||
}
|
||||
LANGUAGE_DOCS = {"ARCHITECTURE.md", "DEPLOY.md", "DEVELOPMENT.md", "TESTING.md"}
|
||||
INLINE_LINK = re.compile(
|
||||
r"!?\[[^\]]*\]\(\s*(<[^>]+>|(?:\\.|[^\s)])+)(?:\s+[^)]*)?\)"
|
||||
)
|
||||
REFERENCE_LINK = re.compile(r"^\s{0,3}\[[^\]]+\]:\s*(<[^>]+>|\S+)")
|
||||
IMPORT = re.compile(r"^\s*@([^\s]+\.md)\s*$")
|
||||
ROUTE_TARGET = re.compile(r"\.agents/[A-Za-z0-9_./-]+\.md")
|
||||
FENCE = re.compile(r"^\s{0,3}(`{3,}|~{3,})")
|
||||
HEADING = re.compile(r"^\s{0,3}#{1,6}\s+(.+?)\s*#*\s*$")
|
||||
HTML_ID = re.compile(r"\bid\s*=\s*['\"]([^'\"]+)['\"]", re.IGNORECASE)
|
||||
|
||||
|
||||
def markdown_files(root: Path) -> list[Path]:
|
||||
found: list[Path] = []
|
||||
for current, directories, filenames in os.walk(root):
|
||||
directories[:] = sorted(
|
||||
name
|
||||
for name in directories
|
||||
if name not in IGNORED_DIRS and not name.startswith(".venv") and not (Path(current) / name).is_symlink()
|
||||
)
|
||||
for filename in filenames:
|
||||
path = Path(current) / filename
|
||||
if path.suffix.lower() == ".md" and not path.is_symlink():
|
||||
found.append(path.resolve())
|
||||
return sorted(found)
|
||||
|
||||
|
||||
def visible_lines(markdown: str) -> list[tuple[int, str]]:
|
||||
"""Return source lines outside fenced code blocks, preserving line numbers."""
|
||||
result: list[tuple[int, str]] = []
|
||||
fence_char: str | None = None
|
||||
fence_size = 0
|
||||
for number, line in enumerate(markdown.splitlines(), start=1):
|
||||
match = FENCE.match(line)
|
||||
if match:
|
||||
marker = match.group(1)
|
||||
if fence_char is None:
|
||||
fence_char, fence_size = marker[0], len(marker)
|
||||
elif marker[0] == fence_char and len(marker) >= fence_size:
|
||||
fence_char, fence_size = None, 0
|
||||
continue
|
||||
if fence_char is None:
|
||||
result.append((number, line))
|
||||
return result
|
||||
|
||||
|
||||
def destination_value(raw: str) -> str:
|
||||
value = raw.strip()
|
||||
if value.startswith("<") and value.endswith(">"):
|
||||
value = value[1:-1]
|
||||
return value.replace("\\ ", " ")
|
||||
|
||||
|
||||
def without_code_spans(line: str) -> str:
|
||||
output: list[str] = []
|
||||
index = 0
|
||||
while index < len(line):
|
||||
if line[index] != "`":
|
||||
output.append(line[index])
|
||||
index += 1
|
||||
continue
|
||||
end_run = index
|
||||
while end_run < len(line) and line[end_run] == "`":
|
||||
end_run += 1
|
||||
delimiter = line[index:end_run]
|
||||
close = line.find(delimiter, end_run)
|
||||
if close < 0:
|
||||
output.append(delimiter)
|
||||
index = end_run
|
||||
continue
|
||||
output.append(" ")
|
||||
index = close + len(delimiter)
|
||||
return "".join(output)
|
||||
|
||||
|
||||
def heading_anchors(markdown: str) -> set[str]:
|
||||
anchors: set[str] = set()
|
||||
occurrences: dict[str, int] = {}
|
||||
for _, line in visible_lines(markdown):
|
||||
for explicit in HTML_ID.findall(line):
|
||||
anchors.add(explicit)
|
||||
match = HEADING.match(line)
|
||||
if not match:
|
||||
continue
|
||||
title = re.sub(r"`([^`]*)`", r"\1", match.group(1))
|
||||
title = re.sub(r"!?\[([^\]]*)\]\([^)]*\)", r"\1", title)
|
||||
slug = re.sub(r"[^\w -]", "", title.lower(), flags=re.UNICODE)
|
||||
slug = re.sub(r"\s+", "-", slug.strip())
|
||||
occurrence = occurrences.get(slug, 0)
|
||||
occurrences[slug] = occurrence + 1
|
||||
anchors.add(slug if occurrence == 0 else f"{slug}-{occurrence}")
|
||||
return anchors
|
||||
|
||||
|
||||
def is_external(destination: str) -> bool:
|
||||
parsed = urlsplit(destination)
|
||||
return bool(parsed.scheme or parsed.netloc)
|
||||
|
||||
|
||||
def check_link(
|
||||
source: Path,
|
||||
line_number: int,
|
||||
destination: str,
|
||||
root: Path,
|
||||
errors: list[str],
|
||||
) -> None:
|
||||
destination = destination_value(destination)
|
||||
if not destination or is_external(destination):
|
||||
return
|
||||
|
||||
parsed = urlsplit(destination)
|
||||
relative = unquote(parsed.path)
|
||||
target = (source.parent / relative).resolve() if relative else source.resolve()
|
||||
try:
|
||||
target.relative_to(root.resolve())
|
||||
except ValueError:
|
||||
errors.append(f"{source.relative_to(root)}:{line_number}: local link escapes the repository: {destination}")
|
||||
return
|
||||
|
||||
if not target.exists():
|
||||
errors.append(f"{source.relative_to(root)}:{line_number}: broken local link: {destination}")
|
||||
return
|
||||
|
||||
if parsed.fragment and target.is_file() and target.suffix.lower() == ".md":
|
||||
fragment = unquote(parsed.fragment)
|
||||
if fragment not in heading_anchors(target.read_text(encoding="utf-8")):
|
||||
errors.append(
|
||||
f"{source.relative_to(root)}:{line_number}: missing Markdown anchor #{fragment} in "
|
||||
f"{target.relative_to(root)}"
|
||||
)
|
||||
|
||||
|
||||
def check_language_docs(root: Path, errors: list[str]) -> None:
|
||||
names: dict[str, set[str]] = {}
|
||||
for language in ("ru", "en"):
|
||||
directory = root / "docs" / language
|
||||
if not directory.is_dir():
|
||||
errors.append(f"missing documentation directory: docs/{language}")
|
||||
continue
|
||||
actual = {path.name for path in directory.glob("*.md") if path.is_file()}
|
||||
names[language] = actual
|
||||
missing = sorted(LANGUAGE_DOCS - actual)
|
||||
if missing:
|
||||
errors.append(f"docs/{language} is missing required files: {', '.join(missing)}")
|
||||
if "ru" in names and "en" in names and names["ru"] != names["en"]:
|
||||
missing_en = sorted(names["ru"] - names["en"])
|
||||
missing_ru = sorted(names["en"] - names["ru"])
|
||||
details = []
|
||||
if missing_en:
|
||||
details.append("missing in docs/en: " + ", ".join(missing_en))
|
||||
if missing_ru:
|
||||
details.append("missing in docs/ru: " + ", ".join(missing_ru))
|
||||
errors.append("docs/ru and docs/en filenames do not match: " + "; ".join(details))
|
||||
|
||||
|
||||
def check_root_readme(files: list[Path], root: Path, errors: list[str]) -> None:
|
||||
expected = (root / "README.md").resolve()
|
||||
if not expected.is_file():
|
||||
errors.append("missing root README.md")
|
||||
nested = [path for path in files if path.name.lower() == "readme.md" and path != expected]
|
||||
for path in nested:
|
||||
errors.append(f"nested README is not allowed: {path.relative_to(root)}")
|
||||
for name in ("AGENTS.md", "CLAUDE.md", "AGENTS_ROUTING.md"):
|
||||
if not (root / name).is_file():
|
||||
errors.append(f"missing root {name}")
|
||||
old_architecture = root / "architecture.md"
|
||||
if old_architecture.exists():
|
||||
errors.append("obsolete root architecture.md remains; keep architecture in docs/ru/ARCHITECTURE.md")
|
||||
|
||||
|
||||
def check_routes(root: Path, source: Path, markdown: str, errors: list[str]) -> None:
|
||||
for line_number, line in visible_lines(markdown):
|
||||
for target in ROUTE_TARGET.findall(line):
|
||||
if not (root / target).is_file():
|
||||
errors.append(f"{source.relative_to(root)}:{line_number}: missing route target: {target}")
|
||||
|
||||
|
||||
def check_imports(root: Path, files: list[Path], errors: list[str]) -> None:
|
||||
graph: dict[Path, list[Path]] = {path: [] for path in files}
|
||||
for source in files:
|
||||
text = source.read_text(encoding="utf-8")
|
||||
for line_number, line in visible_lines(text):
|
||||
match = IMPORT.match(line)
|
||||
if not match:
|
||||
continue
|
||||
imported = (source.parent / match.group(1)).resolve()
|
||||
try:
|
||||
imported.relative_to(root.resolve())
|
||||
except ValueError:
|
||||
errors.append(f"{source.relative_to(root)}:{line_number}: instruction import escapes repository")
|
||||
continue
|
||||
if not imported.is_file():
|
||||
errors.append(
|
||||
f"{source.relative_to(root)}:{line_number}: missing instruction import: {match.group(1)}"
|
||||
)
|
||||
continue
|
||||
graph[source].append(imported)
|
||||
|
||||
state: dict[Path, int] = {}
|
||||
stack: list[Path] = []
|
||||
|
||||
def visit(node: Path) -> None:
|
||||
state[node] = 1
|
||||
stack.append(node)
|
||||
for child in graph.get(node, []):
|
||||
if state.get(child) == 1:
|
||||
cycle = stack[stack.index(child) :] + [child]
|
||||
display = " -> ".join(path.relative_to(root).as_posix() for path in cycle)
|
||||
errors.append(f"instruction import cycle: {display}")
|
||||
elif state.get(child, 0) == 0:
|
||||
visit(child)
|
||||
stack.pop()
|
||||
state[node] = 2
|
||||
|
||||
for node in graph:
|
||||
if state.get(node, 0) == 0:
|
||||
visit(node)
|
||||
|
||||
|
||||
def validate_repository(root: Path) -> list[str]:
|
||||
root = root.resolve()
|
||||
errors: list[str] = []
|
||||
files = markdown_files(root)
|
||||
check_root_readme(files, root, errors)
|
||||
check_language_docs(root, errors)
|
||||
|
||||
routing = root / "AGENTS_ROUTING.md"
|
||||
if not routing.is_file():
|
||||
errors.append("missing root AGENTS_ROUTING.md")
|
||||
else:
|
||||
check_routes(root, routing, routing.read_text(encoding="utf-8"), errors)
|
||||
|
||||
for source in files:
|
||||
text = source.read_text(encoding="utf-8")
|
||||
for line_number, line in visible_lines(text):
|
||||
line_without_code = without_code_spans(line)
|
||||
for match in INLINE_LINK.finditer(line_without_code):
|
||||
check_link(source, line_number, match.group(1), root, errors)
|
||||
match = REFERENCE_LINK.match(line_without_code)
|
||||
if match:
|
||||
check_link(source, line_number, match.group(1), root, errors)
|
||||
|
||||
check_imports(root, files, errors)
|
||||
return errors
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1])
|
||||
args = parser.parse_args()
|
||||
errors = validate_repository(args.root)
|
||||
if errors:
|
||||
for error in errors:
|
||||
print(f"ERROR: {error}", file=sys.stderr)
|
||||
print(f"Documentation check failed with {len(errors)} error(s).", file=sys.stderr)
|
||||
return 1
|
||||
print("Documentation check passed.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -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())
|
||||
@@ -0,0 +1,74 @@
|
||||
pyyaml==6.0.3 \
|
||||
--hash=sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c \
|
||||
--hash=sha256:0150219816b6a1fa26fb4699fb7daa9caf09eb1999f3b70fb6e786805e80375a \
|
||||
--hash=sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3 \
|
||||
--hash=sha256:02ea2dfa234451bbb8772601d7b8e426c2bfa197136796224e50e35a78777956 \
|
||||
--hash=sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6 \
|
||||
--hash=sha256:10892704fc220243f5305762e276552a0395f7beb4dbf9b14ec8fd43b57f126c \
|
||||
--hash=sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65 \
|
||||
--hash=sha256:1d37d57ad971609cf3c53ba6a7e365e40660e3be0e5175fa9f2365a379d6095a \
|
||||
--hash=sha256:1ebe39cb5fc479422b83de611d14e2c0d3bb2a18bbcb01f229ab3cfbd8fee7a0 \
|
||||
--hash=sha256:214ed4befebe12df36bcc8bc2b64b396ca31be9304b8f59e25c11cf94a4c033b \
|
||||
--hash=sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1 \
|
||||
--hash=sha256:22ba7cfcad58ef3ecddc7ed1db3409af68d023b7f940da23c6c2a1890976eda6 \
|
||||
--hash=sha256:27c0abcb4a5dac13684a37f76e701e054692a9b2d3064b70f5e4eb54810553d7 \
|
||||
--hash=sha256:28c8d926f98f432f88adc23edf2e6d4921ac26fb084b028c733d01868d19007e \
|
||||
--hash=sha256:2e71d11abed7344e42a8849600193d15b6def118602c4c176f748e4583246007 \
|
||||
--hash=sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310 \
|
||||
--hash=sha256:37503bfbfc9d2c40b344d06b2199cf0e96e97957ab1c1b546fd4f87e53e5d3e4 \
|
||||
--hash=sha256:3c5677e12444c15717b902a5798264fa7909e41153cdf9ef7ad571b704a63dd9 \
|
||||
--hash=sha256:3ff07ec89bae51176c0549bc4c63aa6202991da2d9a6129d7aef7f1407d3f295 \
|
||||
--hash=sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea \
|
||||
--hash=sha256:418cf3f2111bc80e0933b2cd8cd04f286338bb88bdc7bc8e6dd775ebde60b5e0 \
|
||||
--hash=sha256:44edc647873928551a01e7a563d7452ccdebee747728c1080d881d68af7b997e \
|
||||
--hash=sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac \
|
||||
--hash=sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9 \
|
||||
--hash=sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7 \
|
||||
--hash=sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35 \
|
||||
--hash=sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb \
|
||||
--hash=sha256:5cf4e27da7e3fbed4d6c3d8e797387aaad68102272f8f9752883bc32d61cb87b \
|
||||
--hash=sha256:5e0b74767e5f8c593e8c9b5912019159ed0533c70051e9cce3e8b6aa699fcd69 \
|
||||
--hash=sha256:5ed875a24292240029e4483f9d4a4b8a1ae08843b9c54f43fcc11e404532a8a5 \
|
||||
--hash=sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b \
|
||||
--hash=sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c \
|
||||
--hash=sha256:6344df0d5755a2c9a276d4473ae6b90647e216ab4757f8426893b5dd2ac3f369 \
|
||||
--hash=sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd \
|
||||
--hash=sha256:652cb6edd41e718550aad172851962662ff2681490a8a711af6a4d288dd96824 \
|
||||
--hash=sha256:66291b10affd76d76f54fad28e22e51719ef9ba22b29e1d7d03d6777a9174198 \
|
||||
--hash=sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065 \
|
||||
--hash=sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c \
|
||||
--hash=sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c \
|
||||
--hash=sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764 \
|
||||
--hash=sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196 \
|
||||
--hash=sha256:8098f252adfa6c80ab48096053f512f2321f0b998f98150cea9bd23d83e1467b \
|
||||
--hash=sha256:850774a7879607d3a6f50d36d04f00ee69e7fc816450e5f7e58d7f17f1ae5c00 \
|
||||
--hash=sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac \
|
||||
--hash=sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8 \
|
||||
--hash=sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e \
|
||||
--hash=sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28 \
|
||||
--hash=sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3 \
|
||||
--hash=sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5 \
|
||||
--hash=sha256:9c57bb8c96f6d1808c030b1687b9b5fb476abaa47f0db9c0101f5e9f394e97f4 \
|
||||
--hash=sha256:9c7708761fccb9397fe64bbc0395abcae8c4bf7b0eac081e12b809bf47700d0b \
|
||||
--hash=sha256:9f3bfb4965eb874431221a3ff3fdcddc7e74e3b07799e0e84ca4a0f867d449bf \
|
||||
--hash=sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5 \
|
||||
--hash=sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702 \
|
||||
--hash=sha256:b30236e45cf30d2b8e7b3e85881719e98507abed1011bf463a8fa23e9c3e98a8 \
|
||||
--hash=sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788 \
|
||||
--hash=sha256:b865addae83924361678b652338317d1bd7e79b1f4596f96b96c77a5a34b34da \
|
||||
--hash=sha256:b8bb0864c5a28024fac8a632c443c87c5aa6f215c0b126c449ae1a150412f31d \
|
||||
--hash=sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc \
|
||||
--hash=sha256:bdb2c67c6c1390b63c6ff89f210c8fd09d9a1217a465701eac7316313c915e4c \
|
||||
--hash=sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba \
|
||||
--hash=sha256:c2514fceb77bc5e7a2f7adfaa1feb2fb311607c9cb518dbc378688ec73d8292f \
|
||||
--hash=sha256:c3355370a2c156cffb25e876646f149d5d68f5e0a3ce86a5084dd0b64a994917 \
|
||||
--hash=sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5 \
|
||||
--hash=sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26 \
|
||||
--hash=sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f \
|
||||
--hash=sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b \
|
||||
--hash=sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be \
|
||||
--hash=sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c \
|
||||
--hash=sha256:efd7b85f94a6f21e4932043973a7ba2613b059c4a000551892ac9f1d11f5baf3 \
|
||||
--hash=sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6 \
|
||||
--hash=sha256:fa160448684b4e94d80416c0fa4aac48967a969efe22931448d853ada8baf926 \
|
||||
--hash=sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0
|
||||
@@ -0,0 +1,74 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
MODULE_PATH = Path(__file__).with_name("docs-check.py")
|
||||
SPEC = importlib.util.spec_from_file_location("docs_check", MODULE_PATH)
|
||||
assert SPEC is not None and SPEC.loader is not None
|
||||
DOCS_CHECK = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(DOCS_CHECK)
|
||||
|
||||
|
||||
class DocsCheckTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.temporary = tempfile.TemporaryDirectory()
|
||||
self.root = Path(self.temporary.name)
|
||||
self.write("README.md", "# Root\n\n[Guide](docs/en/DEVELOPMENT.md)\n")
|
||||
self.write("AGENTS.md", "Project rules.\n")
|
||||
self.write("CLAUDE.md", "@AGENTS.md\n")
|
||||
self.write(
|
||||
"AGENTS_ROUTING.md",
|
||||
"Read `.agents/workflows/development.md` and `.agents/workflows/validation.md`.\n",
|
||||
)
|
||||
self.write(".agents/workflows/development.md", "Development.\n")
|
||||
self.write(".agents/workflows/validation.md", "Validation.\n")
|
||||
for language in ("ru", "en"):
|
||||
for name in ("ARCHITECTURE", "DEPLOY", "DEVELOPMENT", "TESTING"):
|
||||
self.write(f"docs/{language}/{name}.md", f"# {name}\n")
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self.temporary.cleanup()
|
||||
|
||||
def write(self, relative: str, content: str) -> Path:
|
||||
path = self.root / relative
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(content, encoding="utf-8")
|
||||
return path
|
||||
|
||||
def test_accepts_angle_bracket_path_with_spaces(self) -> None:
|
||||
self.write("README.md", "# Root\n\n[Guide](<guides/guide with spaces.md>)\n")
|
||||
self.write("guides/guide with spaces.md", "# Guide\n")
|
||||
self.assertEqual([], DOCS_CHECK.validate_repository(self.root))
|
||||
|
||||
def test_accepts_additional_paired_translation_files(self) -> None:
|
||||
self.write("docs/ru/FAQ.md", "# Вопросы\n")
|
||||
self.write("docs/en/FAQ.md", "# FAQ\n")
|
||||
self.assertEqual([], DOCS_CHECK.validate_repository(self.root))
|
||||
|
||||
def test_ignores_link_syntax_inside_inline_code(self) -> None:
|
||||
self.write("README.md", "Use `[missing](not-a-real-link.md)` as an example.\n")
|
||||
self.assertEqual([], DOCS_CHECK.validate_repository(self.root))
|
||||
|
||||
def test_reports_broken_local_markdown_link(self) -> None:
|
||||
self.write("README.md", "[Missing](docs/en/missing.md)\n")
|
||||
errors = DOCS_CHECK.validate_repository(self.root)
|
||||
self.assertTrue(any("broken local link" in error for error in errors), errors)
|
||||
|
||||
def test_reports_typo_in_agent_route_target(self) -> None:
|
||||
self.write("AGENTS_ROUTING.md", "Read `.agents/workflows/developmnt.md`.\n")
|
||||
errors = DOCS_CHECK.validate_repository(self.root)
|
||||
self.assertTrue(any("missing route target" in error for error in errors), errors)
|
||||
|
||||
def test_reports_instruction_import_cycle(self) -> None:
|
||||
self.write("AGENTS.md", "@CLAUDE.md\n")
|
||||
self.write("CLAUDE.md", "@AGENTS.md\n")
|
||||
errors = DOCS_CHECK.validate_repository(self.root)
|
||||
self.assertTrue(any("instruction import cycle" in error for error in errors), errors)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,196 @@
|
||||
"""Focused tests for schema normalization and reference handling."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
|
||||
SCRIPT_PATH = Path(__file__).with_name("merge-schemas.py")
|
||||
SPEC = importlib.util.spec_from_file_location("merge_schemas", SCRIPT_PATH)
|
||||
if SPEC is None or SPEC.loader is None:
|
||||
raise RuntimeError(f"cannot load schema merge script at {SCRIPT_PATH}")
|
||||
MERGE = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(MERGE)
|
||||
|
||||
|
||||
class MergeSchemasTest(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.temporary = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.contract_root = Path(self.temporary.name) / "api"
|
||||
(self.contract_root / "components" / "schemas").mkdir(parents=True)
|
||||
(self.contract_root / "routes").mkdir()
|
||||
|
||||
def write_yaml(self, relative_path: str, value: Any) -> Path:
|
||||
path = self.contract_root / relative_path
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
contents = yaml.safe_dump(value, sort_keys=False, allow_unicode=True)
|
||||
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
|
||||
stream.write(contents)
|
||||
return path
|
||||
|
||||
def read_yaml(self, relative_path: str) -> Any:
|
||||
with (self.contract_root / relative_path).open(encoding="utf-8") as stream:
|
||||
return yaml.safe_load(stream)
|
||||
|
||||
def test_rewrites_nested_refs_and_preserves_nullable_type_arrays(self) -> None:
|
||||
self.write_yaml(
|
||||
"components/schemas/common_schemas.yml",
|
||||
{
|
||||
"schemas": {
|
||||
"entity.Status": {"type": "string"},
|
||||
"response.Health": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": {"$ref": "#/schemas/entity.Status"},
|
||||
"metadata": {
|
||||
"anyOf": [
|
||||
{"$ref": "#/schemas/entity.Status"},
|
||||
{"type": ["string", "null"]},
|
||||
]
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
output = MERGE.merge_contract(self.contract_root)
|
||||
self.assertEqual(output, self.contract_root / "components" / "schemas.yml")
|
||||
document = self.read_yaml("components/schemas.yml")
|
||||
self.assertEqual(list(document), ["Status", "Health"])
|
||||
self.assertEqual(document["Health"]["properties"]["status"]["$ref"], "#/Status")
|
||||
self.assertEqual(
|
||||
document["Health"]["properties"]["metadata"]["anyOf"][0]["$ref"],
|
||||
"#/Status",
|
||||
)
|
||||
self.assertEqual(
|
||||
document["Health"]["properties"]["metadata"]["anyOf"][1]["type"],
|
||||
["string", "null"],
|
||||
)
|
||||
|
||||
def test_rebases_cross_file_refs_and_keeps_nested_pointers(self) -> None:
|
||||
self.write_yaml(
|
||||
"components/schemas/common_schemas.yml",
|
||||
{
|
||||
"schemas": {
|
||||
"entity.Contact": {
|
||||
"type": "object",
|
||||
"properties": {"email": {"type": "string"}},
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
self.write_yaml(
|
||||
"components/schemas/profile_schemas.yml",
|
||||
{
|
||||
"schemas": {
|
||||
"response.Profile": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"contact": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "./common_schemas.yml#/schemas/entity.Contact/properties/email"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
MERGE.merge_contract(self.contract_root)
|
||||
document = self.read_yaml("components/schemas.yml")
|
||||
|
||||
self.assertEqual(
|
||||
document["Profile"]["properties"]["contact"]["anyOf"][0]["$ref"],
|
||||
"#/Contact/properties/email",
|
||||
)
|
||||
|
||||
def test_duplicate_normalized_names_fail_without_overwriting_output(self) -> None:
|
||||
self.write_yaml(
|
||||
"components/schemas/auth_schemas.yml",
|
||||
{"schemas": {"response.Health": {"type": "string"}}},
|
||||
)
|
||||
self.write_yaml(
|
||||
"components/schemas/common_schemas.yml",
|
||||
{"schemas": {"Health": {"type": "integer"}}},
|
||||
)
|
||||
output = self.contract_root / "components" / "schemas.yml"
|
||||
output.write_text("previous output\n", encoding="utf-8")
|
||||
|
||||
with self.assertRaisesRegex(MERGE.MergeError, "duplicate normalized schema name") as error:
|
||||
MERGE.merge_contract(self.contract_root)
|
||||
|
||||
self.assertIn("auth_schemas.yml", str(error.exception))
|
||||
self.assertIn("common_schemas.yml", str(error.exception))
|
||||
self.assertEqual(output.read_text(encoding="utf-8"), "previous output\n")
|
||||
|
||||
def test_stale_nested_route_refs_fail_without_writing_output(self) -> None:
|
||||
self.write_yaml(
|
||||
"components/schemas/health_schemas.yml",
|
||||
{"schemas": {"Health": {"type": "object"}}},
|
||||
)
|
||||
route_path = self.contract_root / "routes" / "health.yml"
|
||||
route_path.write_text(
|
||||
"get:\n"
|
||||
" responses:\n"
|
||||
" '200':\n"
|
||||
" content:\n"
|
||||
" application/json:\n"
|
||||
" schema:\n"
|
||||
" anyOf:\n"
|
||||
' - $ref: "../components/schemas.yml#/schemas/response.Health"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
with self.assertRaisesRegex(MERGE.MergeError, "stale schema references"):
|
||||
MERGE.merge_contract(self.contract_root)
|
||||
|
||||
self.assertFalse((self.contract_root / "components" / "schemas.yml").exists())
|
||||
|
||||
def test_route_refs_to_split_schema_files_are_rejected(self) -> None:
|
||||
self.write_yaml(
|
||||
"components/schemas/health_schemas.yml",
|
||||
{"schemas": {"Health": {"type": "object"}}},
|
||||
)
|
||||
self.write_yaml(
|
||||
"routes/health.yml",
|
||||
{"get": {"responses": {"200": {"$ref": "../components/schemas/health_schemas.yml#/schemas/Health"}}}},
|
||||
)
|
||||
|
||||
with self.assertRaisesRegex(MERGE.MergeError, "stale schema references"):
|
||||
MERGE.merge_contract(self.contract_root)
|
||||
|
||||
self.assertFalse((self.contract_root / "components" / "schemas.yml").exists())
|
||||
|
||||
def test_contract_roots_are_independent(self) -> None:
|
||||
self.write_yaml(
|
||||
"components/schemas/health_schemas.yml",
|
||||
{"schemas": {"Health": {"type": "object"}}},
|
||||
)
|
||||
ml_root = self.contract_root / "ml"
|
||||
(ml_root / "components" / "schemas").mkdir(parents=True)
|
||||
self.write_yaml(
|
||||
"ml/components/schemas/health_schemas.yml",
|
||||
{"schemas": {"Health": {"type": "string"}}},
|
||||
)
|
||||
|
||||
MERGE.merge_contract(self.contract_root)
|
||||
MERGE.merge_contract(ml_root)
|
||||
|
||||
self.assertEqual(self.read_yaml("components/schemas.yml")["Health"]["type"], "object")
|
||||
self.assertEqual(self.read_yaml("ml/components/schemas.yml")["Health"]["type"], "string")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user