from __future__ import annotations
import sys
import yaml
def strip_ref_siblings(node: object) -> int:
removed = 0
if isinstance(node, dict):
if "$ref" in node and len(node) > 1:
for key in [k for k in node if k != "$ref"]:
del node[key]
removed += 1
for value in list(node.values()):
removed += strip_ref_siblings(value)
elif isinstance(node, list):
for item in node:
removed += strip_ref_siblings(item)
return removed
def main() -> int:
if len(sys.argv) != 2:
print("usage: normalize-openapi.py <spec.yaml>", file=sys.stderr)
return 2
path = sys.argv[1]
with open(path, encoding="utf-8") as handle:
spec = yaml.safe_load(handle)
removed = strip_ref_siblings(spec)
with open(path, "w", encoding="utf-8") as handle:
yaml.safe_dump(spec, handle, sort_keys=False, allow_unicode=True)
print(f"normalize-openapi: stripped {removed} sibling key(s) from $ref nodes in {path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())