#!/usr/bin/env python3 """Краткий разбор OpenAPI-спецификации.""" from __future__ import annotations import argparse import json from pathlib import Path from urllib.request import urlopen import yaml METHODS = ("get", "post", "put", "patch", "delete", "head", "options", "trace") def load_spec(source: str) -> dict: if source.startswith("http://") or source.startswith("https://"): with urlopen(source, timeout=15) as response: text = response.read(5_000_000).decode("utf-8") if source.lower().endswith((".yaml", ".yml")): data = yaml.safe_load(text) else: data = json.loads(text) else: path = Path(source) if not path.is_file(): raise SystemExit(f"Файл не найден: {path}") text = path.read_text(encoding="utf-8") data = yaml.safe_load(text) if path.suffix.lower() in {".yaml", ".yml"} else json.loads(text) if not isinstance(data, dict): raise SystemExit("Спецификация должна быть объектом") return data def main() -> int: parser = argparse.ArgumentParser(description="Разобрать OpenAPI") parser.add_argument("--spec", required=True, help="Путь или URL к JSON/YAML") parser.add_argument("--json", type=Path, help="Сохранить отчёт") args = parser.parse_args() spec = load_spec(args.spec) version = spec.get("openapi") or spec.get("swagger") or "не указана" info = spec.get("info") or {} servers = spec.get("servers") or [] paths = spec.get("paths") or {} if not isinstance(paths, dict): raise SystemExit("Поле paths должно быть объектом") print(f"Версия: {version}") print(f"Название: {info.get('title', 'без названия')}") print(f"Версия API: {info.get('version', 'не указана')}") if servers: print("Серверы:") for server in servers: print(f" {server.get('url', '?')} {server.get('description', '')}".rstrip()) report = {"version": version, "title": info.get("title"), "servers": servers, "operations": [], "issues": []} for path, item in paths.items(): if not isinstance(item, dict): continue for method in METHODS: operation = item.get(method) if not isinstance(operation, dict): continue entry = { "method": method.upper(), "path": path, "operationId": operation.get("operationId"), "summary": operation.get("summary"), "deprecated": bool(operation.get("deprecated")), "tags": operation.get("tags") or [], } report["operations"].append(entry) missing = [name for name in ("operationId", "summary") if not operation.get(name)] if missing: report["issues"].append({"method": method.upper(), "path": path, "missing": missing}) print(f"{method.upper():<7} {path} {operation.get('summary', '')}".rstrip()) components = spec.get("components") or {} security = components.get("securitySchemes") or {} if security: print("Схемы безопасности:") for name, scheme in security.items(): print(f" {name}: {scheme.get('type', '?')} {scheme.get('scheme', '')}".rstrip()) print(f"Операций: {len(report['operations'])}, замечаний: {len(report['issues'])}") if args.json: args.json.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"Отчёт: {args.json}") return 0 if not report["issues"] else 1 if __name__ == "__main__": raise SystemExit(main())