Repository navigation
Expand file tree
/
Copy pathcommon.py
More file actions
74 lines (59 loc) · 2.83 KB
/
Copy pathcommon.py
File metadata and controls
74 lines (59 loc) · 2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"""Small helpers shared by the four pipeline scripts."""
from __future__ import annotations
import json
import re
from collections.abc import Iterator
from pathlib import Path
from typing import Any
HTTP_METHODS = ("get", "put", "post", "delete", "options", "head", "patch", "trace")
PATH_TEMPLATE_PARAM = re.compile(r"\{([^}/]+)\}")
# OpenAPI 3 requires component keys to match this pattern.
VALID_COMPONENT_NAME = re.compile(r"^[A-Za-z0-9._-]+$")
def load_json(path: str | Path) -> dict[str, Any]:
"""Read a JSON document, failing with a readable message."""
path = Path(path)
if not path.exists():
raise SystemExit(f"error: file not found: {path}")
try:
with path.open(encoding="utf-8") as handle:
return json.load(handle)
except json.JSONDecodeError as exc:
raise SystemExit(f"error: {path} is not valid JSON ({exc.msg}, line {exc.lineno})") from exc
def save_json(path: str | Path, document: dict[str, Any]) -> None:
"""Write a JSON document with stable formatting (UTF-8, 2-space indent)."""
with Path(path).open("w", encoding="utf-8") as handle:
json.dump(document, handle, indent=2, ensure_ascii=False)
handle.write("\n")
def iter_operations(document: dict[str, Any]) -> Iterator[tuple[str, str, dict[str, Any]]]:
"""Yield (path, method, operation) for every operation in the document."""
for path, path_item in document.get("paths", {}).items():
if not isinstance(path_item, dict):
continue
for method, operation in path_item.items():
if method.lower() in HTTP_METHODS and isinstance(operation, dict):
yield path, method.lower(), operation
def template_params(path: str) -> list[str]:
"""Return the parameter names used in a path template, e.g. /a/{id} -> ['id']."""
return PATH_TEMPLATE_PARAM.findall(path)
def resolve_ref(document: dict[str, Any], node: Any) -> Any:
"""Resolve a local '#/...' $ref (one level at a time, until a non-ref node)."""
seen: set[str] = set()
while isinstance(node, dict) and isinstance(node.get("$ref"), str):
ref = node["$ref"]
if not ref.startswith("#/") or ref in seen:
return node
seen.add(ref)
target: Any = document
for part in ref[2:].split("/"):
part = part.replace("~1", "/").replace("~0", "~")
if not isinstance(target, dict) or part not in target:
return node
target = target[part]
node = target
return node
def declared_params(
document: dict[str, Any], path_item: dict[str, Any], operation: dict[str, Any]
) -> list[dict[str, Any]]:
"""Return the resolved path-level and operation-level parameters."""
raw = [*path_item.get("parameters", []), *operation.get("parameters", [])]
return [resolve_ref(document, param) for param in raw]