apimpact 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- apimpact/__init__.py +10 -0
- apimpact/__main__.py +4 -0
- apimpact/cli.py +263 -0
- apimpact/config.py +57 -0
- apimpact/explain.py +512 -0
- apimpact/formats/__init__.py +75 -0
- apimpact/formats/graphql.py +430 -0
- apimpact/formats/jsonschema.py +40 -0
- apimpact/formats/openapi.py +334 -0
- apimpact/formats/protobuf.py +334 -0
- apimpact/formats/schema.py +269 -0
- apimpact/gitutil.py +76 -0
- apimpact/impact.py +112 -0
- apimpact/model.py +51 -0
- apimpact/py.typed +0 -0
- apimpact/report.py +164 -0
- apimpact-1.0.0.dist-info/METADATA +334 -0
- apimpact-1.0.0.dist-info/RECORD +22 -0
- apimpact-1.0.0.dist-info/WHEEL +5 -0
- apimpact-1.0.0.dist-info/entry_points.txt +2 -0
- apimpact-1.0.0.dist-info/licenses/LICENSE +21 -0
- apimpact-1.0.0.dist-info/top_level.txt +1 -0
apimpact/__init__.py
ADDED
apimpact/__main__.py
ADDED
apimpact/cli.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
"""Command-line interface for APImpact."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
from typing import Any, Dict, List, Optional
|
|
8
|
+
|
|
9
|
+
from . import __version__
|
|
10
|
+
from .config import load_config
|
|
11
|
+
from .explain import explain_code
|
|
12
|
+
from .formats import FORMATS, diff_text, format_info
|
|
13
|
+
from .gitutil import read_pair
|
|
14
|
+
from .impact import api_token, api_url, project_id, query_impact
|
|
15
|
+
from .model import Change
|
|
16
|
+
from .report import filter_changes, json_report, sarif_report, text_report
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _add_pair(parser: argparse.ArgumentParser) -> None:
|
|
20
|
+
parser.add_argument("--baseline", default=None,
|
|
21
|
+
help="Git ref or file path for the baseline contract.")
|
|
22
|
+
parser.add_argument("--path", default=None,
|
|
23
|
+
help="Current contract file.")
|
|
24
|
+
parser.add_argument("--old", default=None,
|
|
25
|
+
help="Old contract file (alternative to --baseline).")
|
|
26
|
+
parser.add_argument("--new", default=None,
|
|
27
|
+
help="New contract file (alternative to --path).")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _add_output(parser: argparse.ArgumentParser) -> None:
|
|
31
|
+
parser.add_argument("--format", choices=["text", "json", "sarif"], default=None,
|
|
32
|
+
help="Output format.")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _add_input(parser: argparse.ArgumentParser) -> None:
|
|
36
|
+
parser.add_argument("--contract-format",
|
|
37
|
+
choices=["openapi", "graphql", "protobuf", "jsonschema"],
|
|
38
|
+
default=None,
|
|
39
|
+
help="Contract format; detected from the file when omitted.")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _add_ignore(parser: argparse.ArgumentParser) -> None:
|
|
43
|
+
parser.add_argument("--ignore", action="append", default=None,
|
|
44
|
+
help="Ignore a change code or path glob (repeatable).")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
48
|
+
parser = argparse.ArgumentParser(
|
|
49
|
+
prog="apimpact",
|
|
50
|
+
description="Analyze API schema changes and their blast radius.",
|
|
51
|
+
)
|
|
52
|
+
parser.add_argument("--version", action="version",
|
|
53
|
+
version="apimpact %s" % __version__)
|
|
54
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
55
|
+
|
|
56
|
+
diff = sub.add_parser("diff", help="Compare two API contracts.")
|
|
57
|
+
diff.add_argument("old")
|
|
58
|
+
diff.add_argument("new")
|
|
59
|
+
_add_output(diff)
|
|
60
|
+
_add_input(diff)
|
|
61
|
+
_add_ignore(diff)
|
|
62
|
+
|
|
63
|
+
gate = sub.add_parser("gate", help="Fail CI on breaking changes.")
|
|
64
|
+
_add_pair(gate)
|
|
65
|
+
_add_output(gate)
|
|
66
|
+
_add_input(gate)
|
|
67
|
+
gate.add_argument("--fail-on", choices=["breaking", "warning", "none"],
|
|
68
|
+
default=None, help="Failure threshold.")
|
|
69
|
+
_add_ignore(gate)
|
|
70
|
+
|
|
71
|
+
impact = sub.add_parser("impact", help="Diff and query the consumer graph.")
|
|
72
|
+
_add_pair(impact)
|
|
73
|
+
_add_output(impact)
|
|
74
|
+
_add_input(impact)
|
|
75
|
+
impact.add_argument("--fail-on", choices=["breaking", "warning", "none"],
|
|
76
|
+
default=None, help="Failure threshold.")
|
|
77
|
+
impact.add_argument("--api-url", default=None,
|
|
78
|
+
help="Consumer graph base URL.")
|
|
79
|
+
impact.add_argument("--api-token", default=None,
|
|
80
|
+
help="Optional consumer graph token.")
|
|
81
|
+
impact.add_argument("--project", default=None,
|
|
82
|
+
help="Project identifier for the consumer graph.")
|
|
83
|
+
impact.add_argument("--timeout", type=float, default=None,
|
|
84
|
+
help="Consumer graph timeout in seconds.")
|
|
85
|
+
impact.add_argument("--insecure", action="store_true",
|
|
86
|
+
help="Skip TLS verification for the consumer graph.")
|
|
87
|
+
impact.add_argument("--no-network", action="store_true",
|
|
88
|
+
help="Skip the consumer graph lookup.")
|
|
89
|
+
_add_ignore(impact)
|
|
90
|
+
|
|
91
|
+
explain = sub.add_parser("explain", help="Explain a change code.")
|
|
92
|
+
explain.add_argument("code")
|
|
93
|
+
|
|
94
|
+
sub.add_parser("formats", help="List supported contract formats.")
|
|
95
|
+
return parser
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _start_services() -> None:
|
|
99
|
+
"""Start optional APImpact service plugins (for example apimpact-sync)."""
|
|
100
|
+
try:
|
|
101
|
+
from importlib.metadata import entry_points
|
|
102
|
+
except Exception:
|
|
103
|
+
return
|
|
104
|
+
try:
|
|
105
|
+
try:
|
|
106
|
+
eps = entry_points(group="apimpact.services")
|
|
107
|
+
except TypeError: # Python 3.9
|
|
108
|
+
eps = entry_points().get("apimpact.services", [])
|
|
109
|
+
for ep in eps:
|
|
110
|
+
try:
|
|
111
|
+
ep.load()()
|
|
112
|
+
except Exception:
|
|
113
|
+
pass
|
|
114
|
+
except Exception:
|
|
115
|
+
pass
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _safe_label(label: str) -> str:
|
|
119
|
+
"""Keep the network payload free of absolute local paths."""
|
|
120
|
+
if os.path.isabs(label):
|
|
121
|
+
return os.path.basename(label)
|
|
122
|
+
return label
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _config_value(config: Dict[str, Any], key: str, default: Any = None) -> Any:
|
|
126
|
+
value = config.get(key)
|
|
127
|
+
return value if value is not None else default
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _ignore_list(args: argparse.Namespace, config: Dict[str, Any]) -> List[str]:
|
|
131
|
+
configured = config.get("ignore") or []
|
|
132
|
+
if isinstance(configured, str):
|
|
133
|
+
configured = [configured]
|
|
134
|
+
return list(configured) + list(args.ignore or [])
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _read_pair(args: argparse.Namespace):
|
|
138
|
+
return read_pair(
|
|
139
|
+
getattr(args, "old", None),
|
|
140
|
+
getattr(args, "new", None),
|
|
141
|
+
getattr(args, "baseline", None),
|
|
142
|
+
getattr(args, "path", None),
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _should_fail(changes: List[Change], fail_on: str) -> bool:
|
|
147
|
+
if fail_on == "none":
|
|
148
|
+
return False
|
|
149
|
+
if fail_on == "warning":
|
|
150
|
+
return any(c.severity in ("breaking", "warning") for c in changes)
|
|
151
|
+
return any(c.severity == "breaking" for c in changes)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _render(changes: List[Change], impact: Optional[Dict[str, Any]],
|
|
155
|
+
baseline: str, current: str, fmt: str) -> str:
|
|
156
|
+
if fmt == "json":
|
|
157
|
+
return json.dumps(json_report(changes, impact, baseline, current),
|
|
158
|
+
indent=2, default=str)
|
|
159
|
+
if fmt == "sarif":
|
|
160
|
+
return json.dumps(sarif_report(changes, baseline, current),
|
|
161
|
+
indent=2, default=str)
|
|
162
|
+
return text_report(changes, impact, baseline, current)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _cmd_diff(args: argparse.Namespace, config: Dict[str, Any]) -> int:
|
|
166
|
+
old_text, new_text, old_label, new_label = _read_pair(args)
|
|
167
|
+
contract_format = args.contract_format or _config_value(config, "contract_format")
|
|
168
|
+
changes = diff_text(old_text, new_text, contract_format, old_label, new_label)
|
|
169
|
+
changes = filter_changes(changes, _ignore_list(args, config))
|
|
170
|
+
fmt = args.format or _config_value(config, "format", "text")
|
|
171
|
+
print(_render(changes, None, old_label, new_label, fmt))
|
|
172
|
+
return 0
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _cmd_gate(args: argparse.Namespace, config: Dict[str, Any]) -> int:
|
|
176
|
+
old_text, new_text, old_label, new_label = _read_pair(args)
|
|
177
|
+
contract_format = args.contract_format or _config_value(config, "contract_format")
|
|
178
|
+
changes = diff_text(old_text, new_text, contract_format, old_label, new_label)
|
|
179
|
+
changes = filter_changes(changes, _ignore_list(args, config))
|
|
180
|
+
fmt = args.format or _config_value(config, "format", "text")
|
|
181
|
+
print(_render(changes, None, old_label, new_label, fmt))
|
|
182
|
+
fail_on = args.fail_on or _config_value(config, "fail_on", "breaking")
|
|
183
|
+
return 1 if _should_fail(changes, fail_on) else 0
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _cmd_impact(args: argparse.Namespace, config: Dict[str, Any]) -> int:
|
|
187
|
+
old_text, new_text, old_label, new_label = _read_pair(args)
|
|
188
|
+
contract_format = args.contract_format or _config_value(config, "contract_format")
|
|
189
|
+
changes = diff_text(old_text, new_text, contract_format, old_label, new_label)
|
|
190
|
+
changes = filter_changes(changes, _ignore_list(args, config))
|
|
191
|
+
fmt = args.format or _config_value(config, "format", "text")
|
|
192
|
+
|
|
193
|
+
impact: Optional[Dict[str, Any]]
|
|
194
|
+
if args.no_network:
|
|
195
|
+
impact = {"configured": False, "consumers": [], "summary": {}, "error": None}
|
|
196
|
+
else:
|
|
197
|
+
url = api_url(args.api_url, _config_value(config, "api_url"))
|
|
198
|
+
if url:
|
|
199
|
+
token = api_token(args.api_token)
|
|
200
|
+
project = project_id(args.project, _config_value(config, "project"))
|
|
201
|
+
timeout = args.timeout or _config_value(config, "timeout", 10)
|
|
202
|
+
insecure = args.insecure or bool(_config_value(config, "insecure", False))
|
|
203
|
+
impact = query_impact(changes, project, _safe_label(old_label), url,
|
|
204
|
+
token, timeout=timeout, insecure=insecure)
|
|
205
|
+
else:
|
|
206
|
+
impact = {"configured": False, "consumers": [], "summary": {}, "error": None}
|
|
207
|
+
|
|
208
|
+
print(_render(changes, impact, old_label, new_label, fmt))
|
|
209
|
+
fail_on = args.fail_on or _config_value(config, "fail_on", "breaking")
|
|
210
|
+
return 1 if _should_fail(changes, fail_on) else 0
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _cmd_explain(args: argparse.Namespace) -> int:
|
|
214
|
+
info = explain_code(args.code)
|
|
215
|
+
if not info:
|
|
216
|
+
print("Unknown change code: %s" % args.code, file=sys.stderr)
|
|
217
|
+
print("Run `apimpact formats` or see the README for supported codes.",
|
|
218
|
+
file=sys.stderr)
|
|
219
|
+
return 2
|
|
220
|
+
print("%s - %s" % (args.code, info["severity"]))
|
|
221
|
+
print(info["summary"])
|
|
222
|
+
print("")
|
|
223
|
+
print("Suggestions:")
|
|
224
|
+
for suggestion in info["suggestions"]:
|
|
225
|
+
print(" - %s" % suggestion)
|
|
226
|
+
return 0
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _cmd_formats() -> int:
|
|
230
|
+
info = format_info()
|
|
231
|
+
for name in ("openapi", "graphql", "protobuf", "jsonschema"):
|
|
232
|
+
item = info[name]
|
|
233
|
+
print("%s - %s" % (name, item["description"]))
|
|
234
|
+
print(" extensions: %s" % item["extensions"])
|
|
235
|
+
print(" coverage: %s" % item["coverage"])
|
|
236
|
+
print("")
|
|
237
|
+
return 0
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
241
|
+
_start_services()
|
|
242
|
+
parser = _build_parser()
|
|
243
|
+
args = parser.parse_args(argv)
|
|
244
|
+
config = load_config()
|
|
245
|
+
try:
|
|
246
|
+
if args.command == "diff":
|
|
247
|
+
return _cmd_diff(args, config)
|
|
248
|
+
if args.command == "gate":
|
|
249
|
+
return _cmd_gate(args, config)
|
|
250
|
+
if args.command == "impact":
|
|
251
|
+
return _cmd_impact(args, config)
|
|
252
|
+
if args.command == "explain":
|
|
253
|
+
return _cmd_explain(args)
|
|
254
|
+
if args.command == "formats":
|
|
255
|
+
return _cmd_formats()
|
|
256
|
+
except Exception as exc:
|
|
257
|
+
print("apimpact: error: %s" % exc, file=sys.stderr)
|
|
258
|
+
return 2
|
|
259
|
+
return 2
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
if __name__ == "__main__":
|
|
263
|
+
raise SystemExit(main())
|
apimpact/config.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Configuration loading for APImpact.
|
|
2
|
+
|
|
3
|
+
Reads `.apimpact.toml` or `[tool.apimpact]` from `pyproject.toml`, walking up
|
|
4
|
+
from the current directory. Configuration is optional; every value can be
|
|
5
|
+
overridden by a CLI flag. No secrets belong in this file; use
|
|
6
|
+
`APIMPACT_API_TOKEN` for the consumer graph token.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, Dict
|
|
12
|
+
|
|
13
|
+
try: # Python 3.11+
|
|
14
|
+
import tomllib as _toml
|
|
15
|
+
except Exception: # pragma: no cover - exercised on older Pythons
|
|
16
|
+
try:
|
|
17
|
+
import tomli as _toml
|
|
18
|
+
except Exception:
|
|
19
|
+
_toml = None
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _load_toml(path: Path) -> Dict[str, Any]:
|
|
23
|
+
if _toml is None:
|
|
24
|
+
return {}
|
|
25
|
+
try:
|
|
26
|
+
with open(path, "rb") as f:
|
|
27
|
+
return _toml.load(f)
|
|
28
|
+
except Exception:
|
|
29
|
+
return {}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def find_config(start: Path = None) -> Dict[str, Any]:
|
|
33
|
+
"""Find and load the nearest APImpact configuration."""
|
|
34
|
+
current = Path(start or os.getcwd()).resolve()
|
|
35
|
+
for directory in [current, *current.parents]:
|
|
36
|
+
candidate = directory / ".apimpact.toml"
|
|
37
|
+
if candidate.is_file():
|
|
38
|
+
data = _load_toml(candidate)
|
|
39
|
+
section = data.get("apimpact", {})
|
|
40
|
+
if isinstance(section, dict):
|
|
41
|
+
return dict(section)
|
|
42
|
+
candidate = directory / "pyproject.toml"
|
|
43
|
+
if candidate.is_file():
|
|
44
|
+
data = _load_toml(candidate)
|
|
45
|
+
tool = data.get("tool", {})
|
|
46
|
+
section = tool.get("apimpact", {}) if isinstance(tool, dict) else {}
|
|
47
|
+
if isinstance(section, dict) and section:
|
|
48
|
+
return dict(section)
|
|
49
|
+
return {}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def load_config(path: str = None) -> Dict[str, Any]:
|
|
53
|
+
if path:
|
|
54
|
+
data = _load_toml(Path(path))
|
|
55
|
+
section = data.get("apimpact", {})
|
|
56
|
+
return dict(section) if isinstance(section, dict) else {}
|
|
57
|
+
return find_config()
|