aedificatoria 0.1.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.
- aedificatoria/__init__.py +3 -0
- aedificatoria/__main__.py +3 -0
- aedificatoria/adr.py +193 -0
- aedificatoria/baseline.py +392 -0
- aedificatoria/cargo.py +90 -0
- aedificatoria/cfamily.py +525 -0
- aedificatoria/checks.py +785 -0
- aedificatoria/cli.py +341 -0
- aedificatoria/config.py +334 -0
- aedificatoria/doctor.py +138 -0
- aedificatoria/forge.py +46 -0
- aedificatoria/git.py +487 -0
- aedificatoria/github.py +139 -0
- aedificatoria/gitlab.py +153 -0
- aedificatoria/history.py +537 -0
- aedificatoria/jsts.py +1173 -0
- aedificatoria/languages.py +159 -0
- aedificatoria/model.py +118 -0
- aedificatoria/pyast.py +614 -0
- aedificatoria/report.py +70 -0
- aedificatoria/rust.py +657 -0
- aedificatoria/syntax.py +26 -0
- aedificatoria-0.1.0.dist-info/METADATA +365 -0
- aedificatoria-0.1.0.dist-info/RECORD +27 -0
- aedificatoria-0.1.0.dist-info/WHEEL +4 -0
- aedificatoria-0.1.0.dist-info/entry_points.txt +2 -0
- aedificatoria-0.1.0.dist-info/licenses/LICENSE +21 -0
aedificatoria/adr.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""Architecture decision record creation and project initialization."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import datetime as _dt
|
|
6
|
+
import re
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from .config import Config
|
|
10
|
+
|
|
11
|
+
CONFIG_TEMPLATE = """# Aedificatoria configuration.
|
|
12
|
+
|
|
13
|
+
[aed]
|
|
14
|
+
base = "HEAD"
|
|
15
|
+
adr_dir = "docs/decisions"
|
|
16
|
+
source_roots = ["src", "."]
|
|
17
|
+
|
|
18
|
+
# Paths whose change requires an architecture decision record.
|
|
19
|
+
# one_way_doors = [
|
|
20
|
+
# "migrations/**", "**/migrations/**",
|
|
21
|
+
# "schema/**", "**/schema/**",
|
|
22
|
+
# "api/**", "**/api/**",
|
|
23
|
+
# "auth/**", "**/auth/**",
|
|
24
|
+
# "*.proto", "**/*.proto",
|
|
25
|
+
# "**/openapi*.yaml", "**/openapi*.json",
|
|
26
|
+
# ]
|
|
27
|
+
|
|
28
|
+
# test_paths = [
|
|
29
|
+
# "tests/**", "**/tests/**", "**/test_*.py", "**/*_test.py",
|
|
30
|
+
# "**/*_test.rs", "**/*_tests.rs", "**/*.test.*", "**/*.spec.*",
|
|
31
|
+
# "**/__tests__/**", "**/__test__/**",
|
|
32
|
+
# "**/test_*.c", "**/*_test.c", "**/test_*.cc", "**/*_test.cc",
|
|
33
|
+
# "**/test_*.cpp", "**/*_test.cpp", "**/test_*.cxx", "**/*_test.cxx",
|
|
34
|
+
# ]
|
|
35
|
+
# test_config_paths = [
|
|
36
|
+
# "conftest.py", "**/conftest.py", "pytest.ini", "tox.ini", "setup.cfg",
|
|
37
|
+
# ".coveragerc", "**/jest.config.*", "**/vitest.config.*", "**/.mocharc.*",
|
|
38
|
+
# "**/karma.conf.*", "**/playwright.config.*", "**/cypress.config.*",
|
|
39
|
+
# "**/jest.setup.*", "**/vitest.setup.*", "**/CTestTestfile.cmake",
|
|
40
|
+
# ]
|
|
41
|
+
# api_paths = ["**/*.py", "**/*.rs", "**/*.js", "**/*.jsx", "**/*.ts", "**/*.tsx", "**/*.mjs", "**/*.cjs", "**/*.mts", "**/*.cts", "**/*.h", "**/*.hpp", "**/*.hh", "**/*.hxx", "**/*.ixx"]
|
|
42
|
+
# metric_excludes = ["docs/**", "examples/**", "benchmarks/**"]
|
|
43
|
+
# allow_new_dependencies = []
|
|
44
|
+
baseline_path = "aed-baseline.json"
|
|
45
|
+
cargo_advisory = true
|
|
46
|
+
require_adr_for_large_change = true
|
|
47
|
+
block_removed_tests = true
|
|
48
|
+
block_removed_asserts = true
|
|
49
|
+
block_new_skips = true
|
|
50
|
+
block_breaking_api = true
|
|
51
|
+
|
|
52
|
+
[thresholds]
|
|
53
|
+
max_changed_files = 25
|
|
54
|
+
max_changed_lines = 800
|
|
55
|
+
max_complexity = 15
|
|
56
|
+
complexity_delta = 5
|
|
57
|
+
max_baseline_complexity_growth = 0
|
|
58
|
+
max_baseline_api_growth = 0
|
|
59
|
+
max_baseline_dependency_growth = 0
|
|
60
|
+
max_baseline_edge_growth = 0
|
|
61
|
+
|
|
62
|
+
# [[aed.forbidden_edges]]
|
|
63
|
+
# from = "api"
|
|
64
|
+
# to = "db"
|
|
65
|
+
# reason = "API must go through the service layer, not the database directly."
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
FIRST_ADR = """# 0001. Record architecture decisions
|
|
69
|
+
|
|
70
|
+
- Status: accepted
|
|
71
|
+
- Date: {date}
|
|
72
|
+
|
|
73
|
+
## Context
|
|
74
|
+
|
|
75
|
+
Coding agents make locally reasonable, confident decisions whose architectural
|
|
76
|
+
cost appears later: coupling, cycles, leaky interfaces, and features that
|
|
77
|
+
require edits across many modules. The rationale for those decisions is usually
|
|
78
|
+
lost when the agent's context is compacted.
|
|
79
|
+
|
|
80
|
+
## Decision
|
|
81
|
+
|
|
82
|
+
Record every irreversible or high-blast-radius decision in a numbered ADR under
|
|
83
|
+
`docs/decisions/`. Each record states the context, the decision, the
|
|
84
|
+
alternatives, the consequences, the invariants, and the rollback path.
|
|
85
|
+
One-way-door changes without a record fail `aed check`.
|
|
86
|
+
|
|
87
|
+
## Alternatives considered
|
|
88
|
+
|
|
89
|
+
- Rely on the agent's chat history. Rejected: it is lossy and not reviewable.
|
|
90
|
+
- Rely on code comments alone. Rejected: they do not capture alternatives or rollback.
|
|
91
|
+
|
|
92
|
+
## Consequences
|
|
93
|
+
|
|
94
|
+
Decisions become durable, reviewable artifacts. The guard can compare the
|
|
95
|
+
current diff against them instead of relying on model confidence.
|
|
96
|
+
|
|
97
|
+
## Invariants
|
|
98
|
+
|
|
99
|
+
- A one-way-door change has an accepted or proposed ADR.
|
|
100
|
+
- Tests are not deleted, weakened, or skipped to make a change pass.
|
|
101
|
+
- New package cycles and forbidden dependency edges fail the check.
|
|
102
|
+
|
|
103
|
+
## Rollback
|
|
104
|
+
|
|
105
|
+
Delete the proposed ADR; for an accepted decision, write a superseding ADR.
|
|
106
|
+
"""
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def slugify(title: str) -> str:
|
|
110
|
+
slug = re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-")
|
|
111
|
+
return slug[:60] or "adr"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _next_number(directory: Path) -> int:
|
|
115
|
+
highest = 0
|
|
116
|
+
for path in directory.glob("*.md"):
|
|
117
|
+
match = re.match(r"^(\d+)-", path.name)
|
|
118
|
+
if match:
|
|
119
|
+
highest = max(highest, int(match.group(1)))
|
|
120
|
+
return highest + 1
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def create_adr(
|
|
124
|
+
root: Path,
|
|
125
|
+
title: str,
|
|
126
|
+
*,
|
|
127
|
+
status: str = "proposed",
|
|
128
|
+
config: Config | None = None,
|
|
129
|
+
) -> Path:
|
|
130
|
+
cfg = config or Config()
|
|
131
|
+
directory = root / cfg.adr_dir
|
|
132
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
133
|
+
number = _next_number(directory)
|
|
134
|
+
path = directory / f"{number:04d}-{slugify(title)}.md"
|
|
135
|
+
date = _dt.date.today().isoformat()
|
|
136
|
+
path.write_text(
|
|
137
|
+
f"""# {number:04d}. {title}
|
|
138
|
+
|
|
139
|
+
- Status: {status}
|
|
140
|
+
- Date: {date}
|
|
141
|
+
|
|
142
|
+
## Context
|
|
143
|
+
|
|
144
|
+
...
|
|
145
|
+
|
|
146
|
+
## Decision
|
|
147
|
+
|
|
148
|
+
...
|
|
149
|
+
|
|
150
|
+
## Alternatives considered
|
|
151
|
+
|
|
152
|
+
...
|
|
153
|
+
|
|
154
|
+
## Consequences
|
|
155
|
+
|
|
156
|
+
...
|
|
157
|
+
|
|
158
|
+
## Invariants
|
|
159
|
+
|
|
160
|
+
- ...
|
|
161
|
+
|
|
162
|
+
## Rollback
|
|
163
|
+
|
|
164
|
+
...
|
|
165
|
+
""",
|
|
166
|
+
encoding="utf-8",
|
|
167
|
+
)
|
|
168
|
+
return path
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def init_project(root: Path) -> tuple[list[Path], list[Path]]:
|
|
172
|
+
"""Create aed.toml and the first ADR. Returns (created, already_present)."""
|
|
173
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
174
|
+
created: list[Path] = []
|
|
175
|
+
existing: list[Path] = []
|
|
176
|
+
|
|
177
|
+
config_path = root / "aed.toml"
|
|
178
|
+
if config_path.exists():
|
|
179
|
+
existing.append(config_path)
|
|
180
|
+
else:
|
|
181
|
+
config_path.write_text(CONFIG_TEMPLATE, encoding="utf-8")
|
|
182
|
+
created.append(config_path)
|
|
183
|
+
|
|
184
|
+
adr_dir = root / "docs" / "decisions"
|
|
185
|
+
adr_dir.mkdir(parents=True, exist_ok=True)
|
|
186
|
+
first = adr_dir / "0001-record-architecture-decisions.md"
|
|
187
|
+
existing_adrs = sorted(adr_dir.glob("*.md"))
|
|
188
|
+
if existing_adrs:
|
|
189
|
+
existing.extend(existing_adrs[:1])
|
|
190
|
+
else:
|
|
191
|
+
first.write_text(FIRST_ADR.format(date=_dt.date.today().isoformat()), encoding="utf-8")
|
|
192
|
+
created.append(first)
|
|
193
|
+
return created, existing
|
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
"""Persistent metric baseline: monotonic ratchets across commits.
|
|
2
|
+
|
|
3
|
+
The baseline is a committed JSON snapshot of per-file complexity, public API
|
|
4
|
+
symbols, dependencies, package edges, per-test assertion counts, and
|
|
5
|
+
parameterized test-case counts. `aed check` compares the working tree against it,
|
|
6
|
+
so small increases cannot accumulate commit by commit. Refreshing the baseline is
|
|
7
|
+
a deliberate, ADR-gated change.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
from functools import lru_cache
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from . import jsts, languages, pyast
|
|
18
|
+
from .config import Config
|
|
19
|
+
from .git import _SKIP_DIRS, tracked_source_files
|
|
20
|
+
from .model import Finding, TestInfo
|
|
21
|
+
|
|
22
|
+
VERSION = 3
|
|
23
|
+
_EVIDENCE = "Run `aed baseline` with an accepted ADR to reset the ratchet."
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class BaselineError(RuntimeError):
|
|
27
|
+
pass
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _source_files(root: Path, config: Config) -> list[str]:
|
|
31
|
+
return tracked_source_files(root, config, languages.extensions())
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _mapping(value: object) -> dict[str, Any]:
|
|
35
|
+
return value if isinstance(value, dict) else {}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@lru_cache(maxsize=4096)
|
|
39
|
+
def _file_facts(
|
|
40
|
+
adapter_name: str,
|
|
41
|
+
extension: str,
|
|
42
|
+
text: str,
|
|
43
|
+
) -> tuple[TestInfo, dict[str, int], dict[str, str]]:
|
|
44
|
+
adapter = languages.get("cached" + extension)
|
|
45
|
+
if adapter is None or adapter.name != adapter_name:
|
|
46
|
+
return TestInfo(frozenset(), 0, frozenset()), {}, {}
|
|
47
|
+
tree = adapter.parse_text("cached" + extension, text)
|
|
48
|
+
if tree is None:
|
|
49
|
+
return TestInfo(frozenset(), 0, frozenset()), {}, {}
|
|
50
|
+
return adapter.test_info(tree), adapter.complexity(tree), adapter.public_api(tree)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _collect_file(root: Path, rel: str, config: Config, data: dict[str, Any]) -> None:
|
|
54
|
+
if any(part in _SKIP_DIRS for part in Path(rel).parts[:-1]):
|
|
55
|
+
return
|
|
56
|
+
if config.is_excluded(rel) or config.is_metric_excluded(rel):
|
|
57
|
+
return
|
|
58
|
+
adapter = languages.get(rel)
|
|
59
|
+
if adapter is None:
|
|
60
|
+
return
|
|
61
|
+
try:
|
|
62
|
+
text = (root / rel).read_text(encoding="utf-8")
|
|
63
|
+
except (OSError, UnicodeDecodeError):
|
|
64
|
+
return
|
|
65
|
+
info, scores, surface = _file_facts(adapter.name, Path(rel).suffix, text)
|
|
66
|
+
if info.counts:
|
|
67
|
+
data["tests"][rel] = dict(sorted(info.counts.items()))
|
|
68
|
+
if info.cases:
|
|
69
|
+
data["test_cases"][rel] = dict(sorted(info.cases.items()))
|
|
70
|
+
if config.is_test(rel):
|
|
71
|
+
return
|
|
72
|
+
if scores:
|
|
73
|
+
data["complexity"][rel] = dict(sorted(scores.items()))
|
|
74
|
+
if config.is_api(rel):
|
|
75
|
+
if adapter.name == "python" and Path(rel).name == "__init__.py":
|
|
76
|
+
surface = pyast._resolved_public_api(root, rel, config)
|
|
77
|
+
if surface:
|
|
78
|
+
data["api"][rel] = dict(sorted(surface.items()))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _dependencies(root: Path, config: Config) -> list[str]:
|
|
82
|
+
imports = languages.project_imports(root, config)
|
|
83
|
+
local = {name: languages.local_packages(root, config, name) for name in languages.names()}
|
|
84
|
+
found: set[str] = set()
|
|
85
|
+
for module, (_path, _line, language) in imports.items():
|
|
86
|
+
if module in local.get(language, set()) or languages.is_stdlib(language, module):
|
|
87
|
+
continue
|
|
88
|
+
found.add(module)
|
|
89
|
+
return sorted(found)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _finish(
|
|
93
|
+
root: Path,
|
|
94
|
+
config: Config,
|
|
95
|
+
data: dict[str, Any],
|
|
96
|
+
*,
|
|
97
|
+
preserve_index: bool = False,
|
|
98
|
+
) -> dict[str, Any]:
|
|
99
|
+
if not preserve_index:
|
|
100
|
+
jsts._clear_index_cache()
|
|
101
|
+
try:
|
|
102
|
+
data["dependencies"] = _dependencies(root, config)
|
|
103
|
+
edges, _packages = languages.package_graph(root, config)
|
|
104
|
+
data["edges"] = [list(edge) for edge in sorted(edges)]
|
|
105
|
+
finally:
|
|
106
|
+
if not preserve_index:
|
|
107
|
+
jsts._clear_index_cache()
|
|
108
|
+
return data
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _copy_data(previous: dict[str, Any]) -> dict[str, Any]:
|
|
112
|
+
return {
|
|
113
|
+
"version": VERSION,
|
|
114
|
+
"complexity": {key: dict(value) for key, value in _mapping(previous.get("complexity")).items()},
|
|
115
|
+
"api": {key: dict(value) for key, value in _mapping(previous.get("api")).items()},
|
|
116
|
+
"dependencies": list(previous.get("dependencies") or []),
|
|
117
|
+
"edges": list(previous.get("edges") or []),
|
|
118
|
+
"tests": {key: dict(value) for key, value in _mapping(previous.get("tests")).items()},
|
|
119
|
+
"test_cases": {key: dict(value) for key, value in _mapping(previous.get("test_cases")).items()},
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _drop_file(data: dict[str, Any], path: str | None) -> None:
|
|
124
|
+
if path is None:
|
|
125
|
+
return
|
|
126
|
+
for key in ("complexity", "api", "tests", "test_cases"):
|
|
127
|
+
data[key].pop(path, None)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def update(
|
|
131
|
+
previous: dict[str, Any],
|
|
132
|
+
root: Path,
|
|
133
|
+
config: Config,
|
|
134
|
+
changes: list[tuple[str, str | None, str | None]],
|
|
135
|
+
*,
|
|
136
|
+
preserve_index: bool = False,
|
|
137
|
+
) -> dict[str, Any]:
|
|
138
|
+
"""Recompute only changed paths from a previous full metric snapshot."""
|
|
139
|
+
data = _copy_data(previous)
|
|
140
|
+
if not preserve_index:
|
|
141
|
+
jsts._clear_index_cache()
|
|
142
|
+
for _status, old_path, new_path in changes:
|
|
143
|
+
_drop_file(data, old_path)
|
|
144
|
+
_drop_file(data, new_path)
|
|
145
|
+
if new_path is not None:
|
|
146
|
+
_collect_file(root, new_path, config, data)
|
|
147
|
+
return _finish(root, config, data, preserve_index=preserve_index)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def collect(
|
|
151
|
+
root: Path,
|
|
152
|
+
config: Config,
|
|
153
|
+
*,
|
|
154
|
+
preserve_index: bool = False,
|
|
155
|
+
) -> dict[str, Any]:
|
|
156
|
+
data: dict[str, Any] = {
|
|
157
|
+
"version": VERSION,
|
|
158
|
+
"complexity": {},
|
|
159
|
+
"api": {},
|
|
160
|
+
"dependencies": [],
|
|
161
|
+
"edges": [],
|
|
162
|
+
"tests": {},
|
|
163
|
+
"test_cases": {},
|
|
164
|
+
}
|
|
165
|
+
for rel in _source_files(root, config):
|
|
166
|
+
_collect_file(root, rel, config, data)
|
|
167
|
+
return _finish(root, config, data, preserve_index=preserve_index)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def load(root: Path, path: str) -> dict[str, Any] | None:
|
|
171
|
+
candidate = Path(path)
|
|
172
|
+
if not candidate.is_absolute():
|
|
173
|
+
candidate = root / candidate
|
|
174
|
+
if not candidate.is_file():
|
|
175
|
+
return None
|
|
176
|
+
try:
|
|
177
|
+
data = json.loads(candidate.read_text(encoding="utf-8"))
|
|
178
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
179
|
+
raise BaselineError(str(exc)) from exc
|
|
180
|
+
if not isinstance(data, dict) or data.get("version") not in {1, 2, VERSION}:
|
|
181
|
+
raise BaselineError(f"unsupported baseline format (expected version {VERSION})")
|
|
182
|
+
return data
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def write(root: Path, path: str, data: dict[str, Any]) -> Path:
|
|
186
|
+
candidate = Path(path)
|
|
187
|
+
if not candidate.is_absolute():
|
|
188
|
+
candidate = root / candidate
|
|
189
|
+
candidate.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
|
190
|
+
return candidate
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _nested_total(mapping: dict[str, Any]) -> int:
|
|
194
|
+
return sum(
|
|
195
|
+
score
|
|
196
|
+
for values in mapping.values()
|
|
197
|
+
for score in _mapping(values).values()
|
|
198
|
+
if isinstance(score, int)
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _complexity_findings(
|
|
203
|
+
baseline: dict[str, Any], head: dict[str, Any], config: Config
|
|
204
|
+
) -> list[Finding]:
|
|
205
|
+
base_map = _mapping(baseline.get("complexity"))
|
|
206
|
+
head_map = _mapping(head.get("complexity"))
|
|
207
|
+
findings: list[Finding] = []
|
|
208
|
+
for file, functions in base_map.items():
|
|
209
|
+
current = _mapping(head_map.get(file))
|
|
210
|
+
for name, score in _mapping(functions).items():
|
|
211
|
+
value = current.get(name)
|
|
212
|
+
if isinstance(score, int) and isinstance(value, int) and value > score:
|
|
213
|
+
findings.append(
|
|
214
|
+
Finding(
|
|
215
|
+
"baseline",
|
|
216
|
+
"error",
|
|
217
|
+
f"`{name}` complexity grew {score} -> {value} since baseline",
|
|
218
|
+
path=file,
|
|
219
|
+
evidence=_EVIDENCE,
|
|
220
|
+
)
|
|
221
|
+
)
|
|
222
|
+
base_total = _nested_total(base_map)
|
|
223
|
+
head_total = _nested_total(head_map)
|
|
224
|
+
allowed = base_total + max(0, config.max_baseline_complexity_growth)
|
|
225
|
+
if head_total > allowed:
|
|
226
|
+
findings.append(
|
|
227
|
+
Finding(
|
|
228
|
+
"baseline",
|
|
229
|
+
"error",
|
|
230
|
+
f"total complexity grew {base_total} -> {head_total} since baseline "
|
|
231
|
+
f"(allowed +{max(0, config.max_baseline_complexity_growth)})",
|
|
232
|
+
evidence=_EVIDENCE,
|
|
233
|
+
)
|
|
234
|
+
)
|
|
235
|
+
return findings
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _api_symbols(value: object) -> dict[str, str]:
|
|
239
|
+
if isinstance(value, dict):
|
|
240
|
+
return {str(name): str(signature) for name, signature in value.items()}
|
|
241
|
+
if isinstance(value, list):
|
|
242
|
+
return {str(name): "" for name in value}
|
|
243
|
+
return {}
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _api_findings(baseline: dict[str, Any], head: dict[str, Any], config: Config) -> list[Finding]:
|
|
247
|
+
base_map = _mapping(baseline.get("api"))
|
|
248
|
+
head_map = _mapping(head.get("api"))
|
|
249
|
+
findings: list[Finding] = []
|
|
250
|
+
for file, symbols in base_map.items():
|
|
251
|
+
base_symbols = _api_symbols(symbols)
|
|
252
|
+
head_symbols = _api_symbols(head_map.get(file))
|
|
253
|
+
for symbol, signature in base_symbols.items():
|
|
254
|
+
if symbol not in head_symbols:
|
|
255
|
+
findings.append(
|
|
256
|
+
Finding(
|
|
257
|
+
"baseline",
|
|
258
|
+
"error",
|
|
259
|
+
f"public symbol `{symbol}` removed since baseline",
|
|
260
|
+
path=file,
|
|
261
|
+
evidence=_EVIDENCE,
|
|
262
|
+
)
|
|
263
|
+
)
|
|
264
|
+
elif signature and head_symbols[symbol] and signature != head_symbols[symbol]:
|
|
265
|
+
findings.append(
|
|
266
|
+
Finding(
|
|
267
|
+
"baseline",
|
|
268
|
+
"error",
|
|
269
|
+
f"public symbol `{symbol}` signature changed "
|
|
270
|
+
f"{signature} -> {head_symbols[symbol]} since baseline",
|
|
271
|
+
path=file,
|
|
272
|
+
evidence=_EVIDENCE,
|
|
273
|
+
)
|
|
274
|
+
)
|
|
275
|
+
base_total = sum(len(_api_symbols(value)) for value in base_map.values())
|
|
276
|
+
head_total = sum(len(_api_symbols(value)) for value in head_map.values())
|
|
277
|
+
if head_total > base_total + max(0, config.max_baseline_api_growth):
|
|
278
|
+
findings.append(
|
|
279
|
+
Finding(
|
|
280
|
+
"baseline",
|
|
281
|
+
"error",
|
|
282
|
+
f"public API grew {base_total} -> {head_total} symbols since baseline "
|
|
283
|
+
f"(allowed +{max(0, config.max_baseline_api_growth)})",
|
|
284
|
+
evidence=_EVIDENCE,
|
|
285
|
+
)
|
|
286
|
+
)
|
|
287
|
+
return findings
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _dependency_findings(
|
|
291
|
+
baseline: dict[str, Any], head: dict[str, Any], config: Config
|
|
292
|
+
) -> list[Finding]:
|
|
293
|
+
base = set(baseline.get("dependencies") or [])
|
|
294
|
+
current = set(head.get("dependencies") or [])
|
|
295
|
+
added = sorted(current - base)
|
|
296
|
+
if len(added) <= max(0, config.max_baseline_dependency_growth):
|
|
297
|
+
return []
|
|
298
|
+
listing = ", ".join(added[:8])
|
|
299
|
+
if len(added) > 8:
|
|
300
|
+
listing += f", +{len(added) - 8} more"
|
|
301
|
+
return [
|
|
302
|
+
Finding(
|
|
303
|
+
"baseline",
|
|
304
|
+
"error",
|
|
305
|
+
f"new dependencies since baseline: {listing}",
|
|
306
|
+
evidence=_EVIDENCE,
|
|
307
|
+
)
|
|
308
|
+
]
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _edge_findings(baseline: dict[str, Any], head: dict[str, Any], config: Config) -> list[Finding]:
|
|
312
|
+
base = {tuple(edge) for edge in baseline.get("edges") or [] if isinstance(edge, list) and len(edge) == 2}
|
|
313
|
+
current = {tuple(edge) for edge in head.get("edges") or [] if isinstance(edge, list) and len(edge) == 2}
|
|
314
|
+
added = sorted(current - base)
|
|
315
|
+
if len(added) <= max(0, config.max_baseline_edge_growth):
|
|
316
|
+
return []
|
|
317
|
+
listing = ", ".join(f"{source} -> {target}" for source, target in added[:8])
|
|
318
|
+
if len(added) > 8:
|
|
319
|
+
listing += f", +{len(added) - 8} more"
|
|
320
|
+
return [
|
|
321
|
+
Finding(
|
|
322
|
+
"baseline",
|
|
323
|
+
"error",
|
|
324
|
+
f"new package edges since baseline: {listing}",
|
|
325
|
+
evidence=_EVIDENCE,
|
|
326
|
+
)
|
|
327
|
+
]
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _test_findings(baseline: dict[str, Any], head: dict[str, Any]) -> list[Finding]:
|
|
331
|
+
base_map = _mapping(baseline.get("tests"))
|
|
332
|
+
head_map = _mapping(head.get("tests"))
|
|
333
|
+
findings: list[Finding] = []
|
|
334
|
+
for file, tests in base_map.items():
|
|
335
|
+
current = _mapping(head_map.get(file))
|
|
336
|
+
for name, count in _mapping(tests).items():
|
|
337
|
+
if name not in current:
|
|
338
|
+
findings.append(
|
|
339
|
+
Finding(
|
|
340
|
+
"baseline",
|
|
341
|
+
"error",
|
|
342
|
+
f"test `{name}` removed since baseline",
|
|
343
|
+
path=file,
|
|
344
|
+
evidence=_EVIDENCE,
|
|
345
|
+
)
|
|
346
|
+
)
|
|
347
|
+
elif isinstance(count, int) and isinstance(current[name], int) and current[name] < count:
|
|
348
|
+
findings.append(
|
|
349
|
+
Finding(
|
|
350
|
+
"baseline",
|
|
351
|
+
"error",
|
|
352
|
+
f"test `{name}` assertions are {current[name]} since baseline, was {count}",
|
|
353
|
+
path=file,
|
|
354
|
+
evidence=_EVIDENCE,
|
|
355
|
+
)
|
|
356
|
+
)
|
|
357
|
+
return findings
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _test_case_findings(baseline: dict[str, Any], head: dict[str, Any]) -> list[Finding]:
|
|
361
|
+
base_map = _mapping(baseline.get("test_cases"))
|
|
362
|
+
head_map = _mapping(head.get("test_cases"))
|
|
363
|
+
findings: list[Finding] = []
|
|
364
|
+
for file, cases in base_map.items():
|
|
365
|
+
current = _mapping(head_map.get(file))
|
|
366
|
+
for name, count in _mapping(cases).items():
|
|
367
|
+
if not isinstance(count, int) or name not in current:
|
|
368
|
+
continue
|
|
369
|
+
now = current[name]
|
|
370
|
+
if isinstance(now, int) and now < count:
|
|
371
|
+
findings.append(
|
|
372
|
+
Finding(
|
|
373
|
+
"baseline",
|
|
374
|
+
"error",
|
|
375
|
+
f"test `{name}` parameterized cases are {now} since baseline, was {count}",
|
|
376
|
+
path=file,
|
|
377
|
+
evidence=_EVIDENCE,
|
|
378
|
+
)
|
|
379
|
+
)
|
|
380
|
+
return findings
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def compare(
|
|
384
|
+
baseline: dict[str, Any], head: dict[str, Any], config: Config
|
|
385
|
+
) -> list[Finding]:
|
|
386
|
+
findings = _complexity_findings(baseline, head, config)
|
|
387
|
+
findings.extend(_api_findings(baseline, head, config))
|
|
388
|
+
findings.extend(_dependency_findings(baseline, head, config))
|
|
389
|
+
findings.extend(_edge_findings(baseline, head, config))
|
|
390
|
+
findings.extend(_test_findings(baseline, head))
|
|
391
|
+
findings.extend(_test_case_findings(baseline, head))
|
|
392
|
+
return findings
|
aedificatoria/cargo.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Optional cargo metadata: advisory facts that never affect the verdict.
|
|
2
|
+
|
|
3
|
+
Only `cargo metadata --no-deps --offline` is used: it reads manifests, does not
|
|
4
|
+
resolve dependencies, does not build, and does not write lockfiles or targets.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import shutil
|
|
11
|
+
import subprocess
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class CargoFacts:
|
|
18
|
+
crates: frozenset[str]
|
|
19
|
+
external: frozenset[str]
|
|
20
|
+
edges: frozenset[tuple[str, str]]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def available() -> bool:
|
|
24
|
+
return shutil.which("cargo") is not None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def metadata(root: Path) -> CargoFacts | None:
|
|
28
|
+
if not (root / "Cargo.toml").is_file():
|
|
29
|
+
return None
|
|
30
|
+
try:
|
|
31
|
+
proc = subprocess.run(
|
|
32
|
+
["cargo", "metadata", "--no-deps", "--offline", "--format-version", "1"],
|
|
33
|
+
cwd=root,
|
|
34
|
+
capture_output=True,
|
|
35
|
+
text=True,
|
|
36
|
+
timeout=30,
|
|
37
|
+
check=False,
|
|
38
|
+
)
|
|
39
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
40
|
+
return None
|
|
41
|
+
if proc.returncode != 0:
|
|
42
|
+
return None
|
|
43
|
+
try:
|
|
44
|
+
payload = json.loads(proc.stdout)
|
|
45
|
+
except json.JSONDecodeError:
|
|
46
|
+
return None
|
|
47
|
+
return _facts(payload)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _normalize(name: str) -> str:
|
|
51
|
+
return name.replace("-", "_")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _facts(payload: object) -> CargoFacts | None:
|
|
55
|
+
if not isinstance(payload, dict):
|
|
56
|
+
return None
|
|
57
|
+
packages = payload.get("packages")
|
|
58
|
+
if not isinstance(packages, list):
|
|
59
|
+
return None
|
|
60
|
+
crates: set[str] = set()
|
|
61
|
+
entries: list[tuple[str, list[object]]] = []
|
|
62
|
+
for package in packages:
|
|
63
|
+
if not isinstance(package, dict):
|
|
64
|
+
continue
|
|
65
|
+
name = package.get("name")
|
|
66
|
+
if not isinstance(name, str):
|
|
67
|
+
continue
|
|
68
|
+
crate = _normalize(name)
|
|
69
|
+
crates.add(crate)
|
|
70
|
+
dependencies = package.get("dependencies")
|
|
71
|
+
if isinstance(dependencies, list):
|
|
72
|
+
entries.append((crate, dependencies))
|
|
73
|
+
external: set[str] = set()
|
|
74
|
+
edges: set[tuple[str, str]] = set()
|
|
75
|
+
for crate, dependencies in entries:
|
|
76
|
+
for dependency in dependencies:
|
|
77
|
+
if not isinstance(dependency, dict):
|
|
78
|
+
continue
|
|
79
|
+
package_name = dependency.get("name")
|
|
80
|
+
if not isinstance(package_name, str):
|
|
81
|
+
continue
|
|
82
|
+
target = _normalize(package_name)
|
|
83
|
+
rename = dependency.get("rename")
|
|
84
|
+
key = _normalize(rename) if isinstance(rename, str) else target
|
|
85
|
+
if target in crates:
|
|
86
|
+
if dependency.get("kind") != "dev":
|
|
87
|
+
edges.add((crate, target))
|
|
88
|
+
else:
|
|
89
|
+
external.add(key)
|
|
90
|
+
return CargoFacts(frozenset(crates), frozenset(external), frozenset(edges))
|