Repository navigation
Expand file tree
/
Copy pathcompare.py
More file actions
427 lines (346 loc) · 18 KB
/
Copy pathcompare.py
File metadata and controls
427 lines (346 loc) · 18 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
#!/usr/bin/env python3
"""
Compares two scorer runs and reports what changed, declaration by declaration.
Used by the weekly report (this week's develop against last week's) and the PR check (PR head against its base).
Both runs must come from the same Scorer.java, so every difference is a code change rather than a method change.
Usage:
compare.py --before DIR --after DIR --mode weekly|pr --out-md FILE [--out-json FILE] [--title TEXT]
[--weekly-report [--baseline DIR]] [--rules-url URL] [--link-base URL]
The JSON has `changed` (any finding or score differs), `regressed` (a new finding or a lower module score), the after-run
fleet numbers, and new findings grouped by module and rule for asana_sync.py.
"""
import argparse
import csv
import glob
import json
import os
from collections import defaultdict
from dataclasses import dataclass, field
FLOOR_EXCLUDED_MODULE = "browser-api"
MAX_DETAILED_FINDINGS = 200
PR_COMMENT_MARKER = "<!-- api-quality-check -->"
RULES_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rules.json")
# Filled in by asana_sync.py, which can count the Asana tasks; a dash where nothing posts.
AWAITING_TRIAGE_CELL = "— <!-- awaiting-triage -->"
# Replaced by asana_sync.py with a link to the week's regressions task; invisible where nothing posts.
REGRESSIONS_TASK_MARKER = "<!-- regressions-task -->"
# O1's proposed goals for 2027-06-30, from the objective; shown next to the weekly numbers.
GOALS = {"weighted": "75%", "unweighted": "90%", "floor": "4", "awaiting_triage": "0"}
@dataclass(frozen=True)
class Finding:
module: str
rule: str
file: str
line: str
declaration: str
detail: str
def key(self):
# The file stands in for the package: declarations are simple names, so two packages can both have an `A.f()`.
return (self.module, self.rule, self.file, self.declaration, self.detail)
def location(self):
return (self.module, self.file, self.declaration)
def moved_key(self):
return (self.rule, self.declaration, self.detail)
@dataclass
class ModuleScore:
module: str
score: int
declarations: int
kdoc_documented: int = 0
kdoc_total: int = 0
failing: set = field(default_factory=set)
@dataclass
class Run:
scores: dict
findings: list
# Every (module, file, declaration) that exists in the run, with or without a finding.
locations: set = field(default_factory=set)
def fleet(self):
modules = list(self.scores.values())
total_decls = sum(m.declarations for m in modules)
floor_candidates = [m for m in modules if m.module != FLOOR_EXCLUDED_MODULE]
floor = min((m.score for m in floor_candidates), default=0)
kdoc_total = sum(m.kdoc_total for m in modules)
return {
"modules": len(modules),
"points": sum(m.score for m in modules),
"max_points": len(modules) * MAX_SCORE,
"weighted": sum(m.score / MAX_SCORE * m.declarations for m in modules) / total_decls if total_decls else 0.0,
"unweighted": sum(m.score / MAX_SCORE for m in modules) / len(modules) if modules else 0.0,
"floor": floor,
"floor_modules": sorted(m.module for m in floor_candidates if m.score == floor),
"declarations": total_decls,
"open_findings": len(self.findings),
"kdoc_coverage": sum(m.kdoc_documented for m in modules) / kdoc_total if kdoc_total else 1.0,
}
def _single(directory, pattern):
matches = sorted(glob.glob(os.path.join(directory, pattern)))
if len(matches) != 1:
raise SystemExit(f"Expected exactly one {pattern} in {directory}, found {len(matches)}")
return matches[0]
def load_run(directory):
scores = {}
with open(_single(directory, "api-quality-scores-*.csv"), newline="") as f:
for row in csv.DictReader(f):
scores[row["module"]] = ModuleScore(
module=row["module"],
score=int(row["score"]),
declarations=int(row["declarations"]),
kdoc_documented=int(row["kdoc_documented"]),
kdoc_total=int(row["kdoc_total"]),
failing=set(row["failing"].split()) if row["failing"] else set(),
)
with open(_single(directory, "api-quality-findings-*.csv"), newline="") as f:
findings = [Finding(**row) for row in csv.DictReader(f)]
locations = {f.location() for f in findings}
# Constructors aren't counted as declarations, so they have their own inventory, private ones included.
for pattern in ("api-quality-declarations-*.csv", "api-quality-constructors-*.csv"):
for path in glob.glob(os.path.join(directory, pattern)):
with open(path, newline="") as f:
locations |= {(row["module"], row["file"], row["declaration"]) for row in csv.DictReader(f)}
return Run(scores=scores, findings=findings, locations=locations)
@dataclass
class Diff:
new: list
resolved: list
moved: list
score_changes: list
def by_key(findings):
keyed = defaultdict(list)
for f in findings:
keyed[f.key()].append(f)
return keyed
def relocated(source: Finding, target: Finding, before: Run, after: Run):
"""The declaration left the source's file and wasn't in the target's file before: it moved."""
return source.location() not in after.locations and target.location() not in before.locations
def diff_runs(before: Run, after: Run) -> Diff:
before_keys, after_keys = by_key(before.findings), by_key(after.findings)
new = [f for k, items in after_keys.items() for f in items[len(before_keys.get(k, [])):]]
resolved = [f for k, items in before_keys.items() for f in items[len(after_keys.get(k, [])):]]
# A finding that changed file with its declaration was renamed within its module, or moved to another one: neither
# fixed nor created. A rename isn't reported; a move is, since it changes which module carries the debt.
resolved_by_moved_key = defaultdict(list)
for f in resolved:
resolved_by_moved_key[f.moved_key()].append(f)
moved = []
renamed_sources = set()
genuinely_new = []
for f in new:
candidates = [r for r in resolved_by_moved_key.get(f.moved_key(), []) if relocated(r, f, before, after)]
if candidates:
source = candidates[0]
resolved_by_moved_key[f.moved_key()].remove(source)
if source.module == f.module:
renamed_sources.add(id(source))
else:
moved.append((source, f))
else:
genuinely_new.append(f)
paired_sources = renamed_sources | {id(source) for source, _ in moved}
genuinely_resolved = [f for f in resolved if id(f) not in paired_sources]
score_changes = []
for module in sorted(set(before.scores) | set(after.scores)):
b, a = before.scores.get(module), after.scores.get(module)
if b is None or a is None or b.score != a.score:
score_changes.append((module, b, a))
order = lambda f: (f.module, f.rule, f.file, f.declaration)
return Diff(
new=sorted(genuinely_new, key=order),
resolved=sorted(genuinely_resolved, key=order),
moved=sorted(moved, key=lambda pair: order(pair[1])),
score_changes=score_changes,
)
def load_rules(path=RULES_PATH):
with open(path) as f:
return json.load(f)["rules"]
# rules.json is the single source of the rule texts; the Asana rules task links to it.
_rules = load_rules()
RULES = {r["id"]: (r["name"], r["why"], r["fix"]) for r in _rules}
SHORT_FIXES = {r["id"]: r["short_fix"] for r in _rules}
MAX_SCORE = len(RULES)
def detail_md(detail):
"""`Any in Pair<Int, Any>?` keeps its type in code: GitHub would read `<Int, Any>` in plain text as an HTML tag."""
what, sep, type_text = detail.partition(" in ")
return f"{what} in `{type_text}`" if sep else detail
def rule_label(rule):
return f"{rule}: {RULES[rule][0]}" if rule in RULES else rule
def location_url(f, link_base):
return f"{link_base}/{f.file}#L{f.line}" if link_base and f.file else None
def location(f, link_base):
if not f.file:
return "—"
text = f"{os.path.basename(f.file)}:{f.line}"
url = location_url(f, link_base)
return f"[{text}]({url})" if url else f"`{text}`"
def score_drops(diff: Diff):
return [(module, b, a) for module, b, a in diff.score_changes if b and a and a.score < b.score]
def moved_in(diff: Diff):
sources = defaultdict(set)
for source, target in diff.moved:
sources[target.module].add(source.module)
return sources
def score_drop_text(module, b, a, diff: Diff):
text = f"Score {b.score}/{MAX_SCORE} → {a.score}/{MAX_SCORE}"
sources = moved_in(diff)[module]
if sources:
text += (f", from findings moved in from {', '.join(f'`{m}`' for m in sorted(sources))}: possibly existing API "
"moving between modules, or two unrelated declarations sharing a name")
return text
def score_drop_line(module, b, a, diff: Diff):
return f"`{module}`: {score_drop_text(module, b, a, diff)}"
def regression_reasons(before: Run, after: Run, diff: Diff):
"""New finding groups, and score drops in modules without new findings: a moved finding isn't new, but a score it
lowers still counts."""
reasons = [f"`{module}` {rule_label(rule)}" for (module, rule), _ in group(diff.new)]
modules_with_new = {f.module for f in diff.new}
reasons += [score_drop_line(m, b, a, diff) for m, b, a in score_drops(diff) if m not in modules_with_new]
return reasons
def regressed(before: Run, after: Run, diff: Diff):
return bool(diff.new or score_drops(diff))
def group(findings):
groups = defaultdict(list)
for f in findings:
groups[(f.module, f.rule)].append(f)
return sorted(groups.items())
def pct(value):
return f"{value * 100:.1f}%"
def score_change_row(module, b, a):
return f"| `{module}` | {f'{b.score}/{MAX_SCORE}' if b else 'new'} | {f'{a.score}/{MAX_SCORE}' if a else 'removed'} |"
def rules_line(rules_url):
return ["", f"For more details on fixing the issues, rules, and how scores are calculated: [API quality rules and scores]({rules_url})"] if rules_url else []
def summary_table(before: Run, after: Run, diff: Diff, baseline: Run = None, weekly_report=False):
runs = ([baseline] if baseline else []) + [before, after]
fleets = [r.fleet() for r in runs]
if weekly_report:
header = ["Metric"] + (["Baseline"] if baseline else []) + ["Last week", "This week", "Goal"]
else:
header = ["Metric", "Before", "After"]
blanks = [""] * (len(runs) - 1)
rows = [
["Score, weighted by declarations"] + [pct(f["weighted"]) for f in fleets] + [GOALS["weighted"]],
["Score, average per module"] + [pct(f["unweighted"]) for f in fleets] + [GOALS["unweighted"]],
["Lowest module score"] + [f"{f['floor']}/{MAX_SCORE}" for f in fleets]
+ [f"{GOALS['floor']}/{MAX_SCORE}"],
["Open findings"] + [f"{f['open_findings']:,}" for f in fleets] + [""],
["KDoc coverage of public declarations"] + [pct(f["kdoc_coverage"]) for f in fleets] + [""],
["New findings"] + blanks + [str(len(diff.new)), ""],
["Resolved findings"] + blanks + [str(len(diff.resolved)), ""],
]
if weekly_report:
rows.append(["Finding tasks untriaged after 14 days"] + blanks + [AWAITING_TRIAGE_CELL, GOALS["awaiting_triage"]])
else:
rows = [row[:-1] for row in rows]
lines = ["| " + " | ".join(header) + " |", "|" + "---|" * len(header)]
return lines + ["| " + " | ".join(row) + " |" for row in rows]
def regressions_table(diff: Diff, link_base=None, detailed=False):
"""The weekly report lists one row per API and rule, and its regressions task has every finding; a comparison has no
such task, so it lists every finding with its line, like the PR comment."""
modules_with_new = {f.module for f in diff.new}
drops = [(m, score_drop_text(m, x, y, diff)) for m, x, y in score_drops(diff) if m not in modules_with_new]
if detailed:
rows = [f"| `{f.module}` | {location(f, link_base)} | `{f.declaration}`: {detail_md(f.detail)} | {SHORT_FIXES.get(f.rule, '')} |"
for f in diff.new[:MAX_DETAILED_FINDINGS]]
if len(diff.new) > MAX_DETAILED_FINDINGS:
rows.append(f"| | | …and {len(diff.new) - MAX_DETAILED_FINDINGS} more in the run's artifact | |")
rows += [f"| `{m}` | | {text} | |" for m, text in drops]
return (["| API | Line | Details | Fix |", "|---|---|---|---|"] + rows) if rows else ["None."]
rows = [f"| `{module}` | {rule_label(rule)} | {len(items)} |" for (module, rule), items in group(diff.new)]
rows += [f"| `{m}` | {text} | |" for m, text in drops]
link = [REGRESSIONS_TASK_MARKER, ""] if diff.new else []
return (link + ["| API | Rule | Findings |", "|---|---|---|"] + rows) if rows else ["None."]
def findings_sections(diff: Diff, link_base=None, detailed=False):
md = ["", "### Regressions", ""] + regressions_table(diff, link_base, detailed)
if diff.resolved:
md += ["", "### Resolved", "", "| API | Rules |", "|---|---|"]
for module, items in sorted(group_by_module(diff.resolved).items()):
md.append(f"| `{module}` | {', '.join(sorted({f.rule for f in items}))} |")
if diff.moved:
pairs = defaultdict(set)
for source, target in diff.moved:
pairs[(source.module, target.module)].add(target.rule)
md += ["", "### Moved between modules", "", "| From | To | Rules |", "|---|---|---|"]
md += [f"| `{s}` | `{t}` | {', '.join(sorted(rules))} |" for (s, t), rules in sorted(pairs.items())]
if diff.score_changes:
md += ["", "### Score changes", "", "| API | Before | After |", "|---|---|---|"]
md += [score_change_row(m, x, y) for m, x, y in diff.score_changes]
return md
def render_weekly(before: Run, after: Run, diff: Diff, title="O1: code quality", rules_url=None, baseline: Run = None,
weekly_report=False, link_base=None):
"""The comparison of two runs. As the weekly report, it opens with a summary against the baseline and the goals,
and closes with the O2 section."""
if weekly_report:
md = ["## Summary", ""] + summary_table(before, after, diff, baseline, weekly_report=True)
md += ["", "## O1: API code quality"] + findings_sections(diff)
md += ["", "## O2: API review process", "", "[Under construction]"]
else:
md = [f"## {title}", ""] + summary_table(before, after, diff) + findings_sections(diff, link_base, detailed=True)
md += rules_line(rules_url)
return "\n".join(md) + "\n"
def group_by_module(findings):
modules = defaultdict(list)
for f in findings:
modules[f.module].append(f)
return modules
def render_pr(before: Run, after: Run, diff: Diff, rules_url=None, link_base=None):
md = [PR_COMMENT_MARKER, "### API quality check", ""]
if regressed(before, after, diff):
md.append("❌ This PR adds API quality findings.")
else:
md.append("✅ No new API quality findings.")
if diff.new:
shown = diff.new[:MAX_DETAILED_FINDINGS]
md += ["", "| API | Line | Details |", "|---|---|---|"]
md += [f"| `{f.module}` | {location(f, link_base)} | `{f.declaration}`: {detail_md(f.detail)}<br>**Fix:** {SHORT_FIXES.get(f.rule, '')} |"
for f in shown]
if len(diff.new) > len(shown):
md.append(f"\n…and {len(diff.new) - len(shown)} more in the run's artifact.")
modules_with_new = {f.module for f in diff.new}
drops = [score_drop_line(m, b, a, diff) for m, b, a in score_drops(diff) if m not in modules_with_new]
if drops:
md += [""] + [f"- {d}" for d in drops]
if diff.resolved:
md += ["", f"Resolved {len(diff.resolved)} finding{'' if len(diff.resolved) == 1 else 's'}, thank you!"]
md += rules_line(rules_url)
return "\n".join(md) + "\n"
def new_finding_groups(diff: Diff, link_base=None):
groups = []
for (module, rule), items in group(diff.new):
groups.append({
"module": module,
"rule": rule,
"findings": [{"file": f.file, "line": f.line, "declaration": f.declaration, "detail": f.detail,
"url": location_url(f, link_base)} for f in items],
})
return groups
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--before", required=True)
parser.add_argument("--after", required=True)
parser.add_argument("--mode", choices=["weekly", "pr"], required=True)
parser.add_argument("--out-md", required=True)
parser.add_argument("--out-json")
parser.add_argument("--rules-url", help="The rules and scores reference, linked at the end")
parser.add_argument("--link-base", help="URL that file paths are appended to, e.g. https://github.com/o/r/blob/<sha>")
parser.add_argument("--title", default="O1: code quality", help="Heading of the weekly report section")
parser.add_argument("--weekly-report", action="store_true", help="Weekly mode: the full weekly report layout")
parser.add_argument("--baseline", help="Weekly report: a scorer run for the summary's baseline column")
args = parser.parse_args()
before, after = load_run(args.before), load_run(args.after)
diff = diff_runs(before, after)
with open(args.out_md, "w") as f:
if args.mode == "weekly":
baseline = load_run(args.baseline) if args.baseline else None
f.write(render_weekly(before, after, diff, args.title, args.rules_url, baseline, args.weekly_report, args.link_base))
else:
f.write(render_pr(before, after, diff, args.rules_url, args.link_base))
if args.out_json:
with open(args.out_json, "w") as f:
changed = bool(diff.new or diff.resolved or diff.moved or diff.score_changes)
json.dump({
"changed": changed,
"regressed": regressed(before, after, diff),
"fleet": after.fleet(),
"new": new_finding_groups(diff, args.link_base),
}, f, indent=2)
if __name__ == "__main__":
main()

