返回 CodeWhale
check-contributor-credit.py
根目录 / scripts / check-contributor-credit.py
1 #!/usr/bin/env python3
2 """Fail when someone whose work landed in this release is not credited.
3
4 The three credit surfaces -- docs/CONTRIBUTORS.md, the CHANGELOG's Contributors
5 block, and web/lib/release-credits.ts -- were cross-checked only against
6 `requiredCandidateCredits` in docs/public-surface-facts.json, which is itself
7 hand-maintained. That gate proves the three files agree with each other; it
8 never asks whether the list is complete, so a contributor nobody remembered to
9 add was invisible to every check. Nine were missing from 0.10.0 when this was
10 written.
11
12 This derives the expected set from git history instead of from a list a human
13 curates: commit authors, `Co-authored-by:` trailers, and `Integrated from #N
14 by @handle` or `Harvested from PR #N by @handle` lines in the release window.
15 Offline by design -- those handles live in the commit bodies, so no network call
16 is needed.
17
18 Usage: scripts/check-contributor-credit.py [<since-rev>]
19 """
20 from __future__ import annotations
21 import functools, re, subprocess, sys
22 from pathlib import Path
23
24 ROOT = Path(__file__).resolve().parent.parent
25
26 # Bots and the maintainer account: real authors of most commits, never
27 # "contributors" in the credit sense this file guards.
28 SKIP = {
29 "codewhale bot", "codewhalebot", "codewhale agent", "claude", "codex", "dependabot[bot]",
30 "codewhale-maint", "copilot",
31 "hunter bown", "hunter b", "hmbown", "deepseek-v41-flash", "devin", "gemini",
32 }
33
34
35 def sh(*args: str) -> str:
36 return subprocess.run(args, cwd=ROOT, capture_output=True, text=True, check=True).stdout
37
38
39 @functools.cache
40 def author_map() -> dict[str, str]:
41 """alias -> github handle, from .github/AUTHOR_MAP."""
42 out: dict[str, str] = {}
43 path = ROOT / ".github" / "AUTHOR_MAP"
44 if not path.exists():
45 return out
46 for line in path.read_text().splitlines():
47 line = line.split("#", 1)[0].strip()
48 if "=" not in line:
49 continue
50 alias, target = (part.strip() for part in line.split("=", 1))
51 m = re.search(r"\d+\+([^@<>\s]+)@users\.noreply\.github\.com", target)
52 if m:
53 out[alias.lower()] = m.group(1)
54 return out
55
56
57 NOREPLY = re.compile(r"\d+\+([^@<>\s]+)@users\.noreply\.github\.com")
58
59
60 def not_a_person(name: str, email: str) -> bool:
61 low, addr = name.strip().lower(), email.lower()
62 return any(low.startswith(skip) for skip in SKIP) or "[bot]" in addr \
63 or addr.endswith(("noreply@anthropic.com", "noreply@openai.com"))
64
65
66 def maintainer(name: str, email: str) -> bool:
67 handle = author_map().get(email.lower()) or author_map().get(name.strip().lower()) or name.strip()
68 return any(h.lower().startswith(skip) for skip in SKIP for h in (name.strip(), handle))
69
70
71 def restoring(subject: str, name: str, email: str) -> bool:
72 return subject.startswith("chore(credit):") and maintainer(name, email)
73
74
75 def noreply_ids() -> dict[str, str]:
76 out: dict[str, str] = {}
77 path = ROOT / ".github" / "AUTHOR_MAP"
78 if path.exists():
79 for login_id, login in re.findall(r"(\d+)\+([^@<>\s]+)@users\.noreply\.github\.com", path.read_text()):
80 out[login.lower()] = login_id
81 return out
82
83
84 INTEGRATED_RE = re.compile(r"(?im)^integrated from (?:PR )?#(\d+) by @([A-Za-z0-9-]+)[ \t]*\r?$")
85 INTEGRATED_START_RE = re.compile(r"(?im)^integrated from (?:PR )?#(\d+).*$")
86 REVERT_RE = re.compile(r"(?im)^this reverts commit ([0-9a-f]{40})\.?")
87
88
89 def reverted_shas(since: str) -> set[str]:
90 log = sh("git", "log", f"{since}..HEAD", "--format=%B%x00")
91 return {sha.lower() for sha in REVERT_RE.findall(log)}
92
93
94 def expected(since: str, reverted: set[str]) -> dict[str, str]:
95 """handle -> why we think they are owed credit."""
96 amap = author_map()
97 found: dict[str, str] = {}
98
99 def add(name: str, email: str, why: str) -> None:
100 # Model co-authorship ("Claude Opus 5 (1M context)") and bot addresses
101 # are not people owed credit; match on prefix since the model name and
102 # its context window change release to release.
103 if not_a_person(name, email):
104 return
105 handle = amap.get(email.lower()) or amap.get(name.strip().lower())
106 if not handle:
107 m = re.search(r"\d+\+([^@<>\s]+)@users\.noreply\.github\.com", email)
108 handle = m.group(1) if m else name.strip()
109 if any(handle.lower().startswith(skip) for skip in SKIP):
110 return
111 found.setdefault(handle, why)
112
113 log = sh("git", "log", f"{since}..HEAD", "--format=%H%x1f%an%x1f%ae%x1f%s%x1f%b%x00")
114 work = [parts for parts in (entry.lstrip("\n").split("\x1f", 4) for entry in log.split("\0"))
115 if len(parts) == 5 and parts[0].lower() not in reverted and not restoring(parts[3], parts[1], parts[2])]
116 for _, author, email, _, _ in work:
117 add(author, email, "commit author")
118 for _, _, _, _, body in work:
119 for name, addr in re.findall(r"(?im)^co-authored-by:\s*(.+?)\s*<([^>]+)>", body):
120 add(name, addr, "co-author trailer")
121 for pr, handle in re.findall(r"(?i)harvested from PR #(\d+) by @([A-Za-z0-9-]+)", body):
122 if handle.lower() not in SKIP:
123 found.setdefault(handle, f"harvested PR #{pr}")
124 for number, handle in INTEGRATED_RE.findall(body):
125 handle = amap.get(handle.lower(), handle)
126 if handle.lower() not in SKIP:
127 found.setdefault(handle, f"integrated #{number}")
128 return found
129
130
131 def main() -> int:
132 since = sys.argv[1] if len(sys.argv) > 1 else sh("git", "describe", "--tags", "--abbrev=0").strip()
133 reverted = reverted_shas(since)
134 owed = expected(since, reverted)
135 if not owed:
136 print(f"No external contributors found since {since}.")
137 return 0
138
139 surfaces = {
140 "docs/CONTRIBUTORS.md": (ROOT / "docs/CONTRIBUTORS.md").read_text(),
141 "CHANGELOG.md": (ROOT / "CHANGELOG.md").read_text(),
142 "web/lib/release-credits.ts": (ROOT / "web/lib/release-credits.ts").read_text(),
143 }
144
145 missing: list[str] = []
146 for handle, why in sorted(owed.items(), key=lambda kv: kv[0].lower()):
147 absent = [name for name, text in surfaces.items() if handle not in text]
148 if absent:
149 missing.append(f" @{handle} ({why}) -- not in: {', '.join(absent)}")
150
151 print(f"Contributor credit since {since}: {len(owed)} contributor(s) found.")
152 amap = author_map()
153 ids = noreply_ids()
154 lost = []
155 broken: list[tuple[str, str]] = []
156 credited: set[str] = set()
157 integrated_in: dict[str, set[str]] = {}
158 malformed: list[tuple[str, str, str]] = []
159
160 def login(name: str, addr: str) -> str:
161 nm = NOREPLY.search(addr)
162 return (amap.get(addr.lower()) or amap.get(name.strip().lower()) or (nm.group(1) if nm else name.strip())).lower()
163
164 def who(name: str, addr: str) -> str:
165 nm = re.search(r"(\d+)\+([^@<>\s]+)@users\.noreply\.github\.com", addr)
166 if not nm:
167 return amap.get(addr.lower(), "").lower() if "@" in addr else ""
168 known = ids.get(nm.group(2).lower())
169 if known is not None and known != nm.group(1):
170 broken.append((nm.group(2).lower(), f"uses {addr}, but @{nm.group(2)} is id {known} "
171 f"in AUTHOR_MAP; GitHub credits whoever owns id {nm.group(1)}"))
172 return nm.group(2).lower() if known == nm.group(1) else ""
173
174 log = sh("git", "log", f"{since}..HEAD",
175 "--format=%H%x1f%h%x1f%an%x1f%ae%x1f%(trailers:key=Co-authored-by,unfold)%x1f%B%x00")
176 for entry in log.split("\0"):
177 parts = entry.strip().split("\x1f", 5)
178 if len(parts) < 6:
179 continue
180 full_sha, sha, name, email, parsed, body = parts
181 if full_sha.lower() in reverted:
182 continue
183 m = re.search(r"\d+\+([^@<>\s]+)@users\.noreply\.github\.com", email)
184 author = (amap.get(email.lower()) or amap.get(name.lower()) or (m.group(1) if m else name)).lower()
185 trailers = re.findall(r"(?im)^co-authored-by:\s*(.+?)\s*<([^>]+)>", parsed)
186 mark = len(broken)
187 credited.add(who(name, email))
188 credited.update(who(n, e) for n, e in trailers)
189 broken[mark:] = [(login, f"{sha} {why}") for login, why in broken[mark:]]
190 for co_name, co_email in re.findall(r"(?im)^\s*co-authored-by:\s*(.+?)\s*<([^>]+)>", body):
191 if (co_name, co_email) not in trailers and not not_a_person(co_name, co_email):
192 broken.append((login(co_name, co_email),
193 f"{sha} has 'Co-authored-by: {co_name}' outside the final trailer block; GitHub ignores it"))
194 if restoring(body.split("\n", 1)[0], name, email):
195 continue
196 for handle in re.findall(r"(?i)harvested from PR #\d+ by @([A-Za-z0-9-]+)", body):
197 if handle.lower() != author:
198 lost.append(f" {sha} harvested @{handle} but is authored by {name}")
199 broken.append((amap.get(handle.lower(), handle).lower(),
200 f"{sha} harvested @{handle} with neither authorship nor a Co-authored-by trailer for them"))
201 for started in INTEGRATED_START_RE.finditer(body):
202 match = INTEGRATED_RE.fullmatch(started.group(0))
203 if not match:
204 malformed.append((started.group(1), full_sha, f"{sha} has {started.group(0).strip()!r}; "
205 "write one 'Integrated from #N by @handle' line per person"))
206 continue
207 integrated_in.setdefault(match.group(1), set()).add(full_sha)
208 handle = match.group(2)
209 if handle.lower() not in SKIP:
210 broken.append((amap.get(handle.lower(), handle).lower(),
211 f"{sha} integrated @{handle} with neither authorship nor a Co-authored-by trailer for them"))
212 if any(author.startswith(skip) for skip in SKIP):
213 for co_name, co_email in re.findall(r"(?im)^co-authored-by:\s*(.+?)\s*<([^>]+)>", body):
214 cm = re.search(r"\d+\+([^@<>\s]+)@users\.noreply\.github\.com", co_email)
215 human = amap.get(co_email.lower()) or amap.get(co_name.strip().lower()) or (cm.group(1) if cm else None)
216 low = co_name.strip().lower()
217 if human and not any(h.startswith(skip) for skip in SKIP for h in (human.lower(), low)) \
218 and "[bot]" not in co_email.lower() and not co_email.lower().endswith(("noreply@anthropic.com", "noreply@openai.com")):
219 lost.append(f" {sha} credits @{human} only as a co-author; authored by {name}")
220 if lost:
221 print("\nCommits whose human contributor is not the commit author (GitHub counts them only through a\n"
222 "well-formed Co-authored-by trailer whose address is linked to their account):\n")
223 print("\n".join(lost))
224 broken = [(login, why) for login, why in broken if login.lower() not in credited]
225 broken += [(f"#{number}", why) for number, full_sha, why in malformed
226 if not integrated_in.get(number, set()) - {full_sha}]
227 if broken:
228 print("\nCredit GitHub cannot see:\n")
229 print("\n".join(f" {why}" for _, why in broken))
230 print("\nPut each contributor in the final trailer block as\n"
231 "'Co-authored-by: Name <ID+login@users.noreply.github.com>', with no blank line between trailers,\n"
232 "using the id from `gh api users/<login>`. A later commit can carry the trailer when history cannot change.\n"
233 "Credit is taken only from such an address, or from a raw email listed in .github/AUTHOR_MAP; add the\n"
234 "email a contributor commits with there once it is linked to their account.")
235 if missing:
236 print("\nUncredited work landed in this release:\n")
237 print("\n".join(missing))
238 print(
239 "\nAdd each to docs/CONTRIBUTORS.md (canonical), the CHANGELOG's\n"
240 "Contributors block, and web/lib/release-credits.ts. Integrated work\n"
241 "is still their work -- see AGENTS.md 'Landing other people's work'."
242 )
243 return 1
244 if broken:
245 return 1
246 print("Every contributor in the window is credited on all three surfaces.")
247 return 0
248
249
250 if __name__ == "__main__":
251 raise SystemExit(main())
252
252 lines PYTHON