返回 CodeWhale
contributor-wall.py
根目录 / scripts / release / contributor-wall.py
1 #!/usr/bin/env python3
2 """Everyone whose work landed in or is credited by Codewhale, on one wall.
3
4 GitHub's contributor count takes only commit authors and co-author trailers
5 whose email is linked to an account. Harvested pull requests without a trailer,
6 unlinked commit emails and credited bug reports never reach it, so it shows
7 about half of the people who built Codewhale.
8
9 refresh rebuild docs/contributors.json from git history, the CHANGELOG,
10 docs/CONTRIBUTORS.md and GitHub (needs `gh`)
11 render draw docs/assets/contributors.png and the "Everyone" list in
12 docs/CONTRIBUTORS.md from docs/contributors.json (offline except
13 for avatar downloads, which are cached)
14
15 Usage: scripts/release/contributor-wall.py refresh|render
16 """
17 from __future__ import annotations
18
19 import concurrent.futures
20 import io
21 import json
22 import os
23 import re
24 import subprocess
25 import sys
26 import urllib.request
27 from pathlib import Path
28
29 ROOT = Path(__file__).resolve().parents[2]
30 REPO = "codewhale-hq/Codewhale"
31 SIBLINGS = ["codewhale-cu-plugin", "codewhale-ratatui", "codewhale-plugin-marketplace", "CodeWhale-VSCode"]
32 DATA = ROOT / "docs" / "contributors.json"
33 WALL = ROOT / "docs" / "assets" / "contributors.png"
34 CACHE = Path(os.environ.get("CODEWHALE_AVATAR_CACHE") or ROOT / "target" / "contributor-avatars")
35 NOREPLY = re.compile(r"^(?:(\d+)\+)?([A-Za-z0-9-]+)@users\.noreply\.github\.com$", re.I)
36 NOT_PEOPLE = re.compile(
37 r"\[bot\]|^bot$|copilot|^gemini|dependabot|github-actions|^claude|anthropic|codex|cursor|devin|jules|grok|deepseek-v4|"
38 r"^codewhale|openclaw|autoghclaw|nanookclaw|agentmail\.to|happy\.engineering|codalume|g1 agent|^bot_|"
39 r"^hmbown$|^hunter b(own)?$|^username$|^handle$|^host$", re.I)
40
41
42 def sh(*args: str) -> str:
43 return subprocess.run(args, cwd=ROOT, capture_output=True, text=True, check=True).stdout
44
45
46 def gh_json(*args: str):
47 out = subprocess.run(["gh", *args], cwd=ROOT, capture_output=True, text=True, check=True).stdout
48 return [json.loads(line) for line in out.splitlines() if line.strip()]
49
50
51 def author_map() -> dict[str, str]:
52 out = {}
53 for line in (ROOT / ".github" / "AUTHOR_MAP").read_text().splitlines():
54 line = line.split("#", 1)[0].strip()
55 if "=" in line:
56 alias, target = (p.strip() for p in line.split("=", 1))
57 m = re.search(r"\d+\+([^@<>\s]+)@users\.noreply\.github\.com", target)
58 if m:
59 out[alias.lower()] = m.group(1)
60 return out
61
62
63 def users_exist(logins: set[str]) -> dict[str, dict]:
64 found, logins = {}, sorted(logins)
65 for i in range(0, len(logins), 80):
66 chunk = logins[i:i + 80]
67 query = "query{" + " ".join(f"u{j}: user(login: {json.dumps(x)}) {{ login name }}" for j, x in enumerate(chunk)) + "}"
68 proc = subprocess.run(["gh", "api", "graphql", "-f", f"query={query}"], cwd=ROOT, capture_output=True, text=True)
69 try:
70 payload = json.loads(proc.stdout) if proc.stdout.strip() else {}
71 except json.JSONDecodeError as err:
72 raise RuntimeError(f"gh api graphql returned invalid JSON (rc={proc.returncode}): {proc.stderr.strip() or proc.stdout[:200]}") from err
73 errors = [e for e in (payload.get("errors") or []) if e.get("type") != "NOT_FOUND"]
74 data = payload.get("data")
75 if errors or not isinstance(data, dict):
76 raise RuntimeError(f"gh api graphql failed (rc={proc.returncode}): {errors or proc.stderr.strip() or proc.stdout.strip()}")
77 for j, x in enumerate(chunk):
78 if data.get(f"u{j}"):
79 found[x.lower()] = data[f"u{j}"]
80 return found
81
82
83 def refresh() -> None:
84 amap = author_map()
85 sources: dict[str, set[str]] = {}
86 names: dict[str, set[str]] = {}
87 ids: dict[str, str] = {}
88
89 def credit(login: str, why: str) -> None:
90 if login and not NOT_PEOPLE.search(login):
91 sources.setdefault(login, set()).add(why)
92
93 def person(name: str, email: str, why: str) -> None:
94 if NOT_PEOPLE.search(name) or NOT_PEOPLE.search(email) or email.lower().endswith(("anthropic.com", "openai.com")):
95 return
96 handle = amap.get(email.lower()) or amap.get(name.lower())
97 m = NOREPLY.match(email)
98 if m and m.group(1):
99 ids[m.group(2).lower()] = m.group(1)
100 if handle or m:
101 credit(handle or m.group(2), why)
102 else:
103 names.setdefault(name.strip(), set()).add(why)
104
105 for line in sh("git", "log", "--format=%an\t%ae").splitlines():
106 person(*line.split("\t", 1), "commit")
107 for name, email in re.findall(r"(?im)^co-authored-by:\s*(.+?)\s*<([^>]+)>", sh("git", "log", "--format=%b")):
108 person(name, email, "co-author")
109 for handle in re.findall(r"(?i)harvested from (?:pr )?#?\d+ by @([A-Za-z0-9-]+)", sh("git", "log", "--format=%B")):
110 credit(handle, "harvested pull request")
111 for handle in re.findall(r"(?im)^integrated from (?:pr )?#\d+ by @([A-Za-z0-9-]+)[ \t]*\r?$", sh("git", "log", "--format=%B")):
112 credit(handle, "integrated contribution")
113 record = (ROOT / "docs" / "CONTRIBUTORS.md").read_text().split("## Contributors by time", 1)[-1]
114 for handle in re.findall(r"\]\(https://github\.com/([A-Za-z0-9-]+)\)", record):
115 credit(handle, "contributor record")
116 changelog = (ROOT / "CHANGELOG.md").read_text() + (ROOT / "crates" / "tui" / "CHANGELOG.md").read_text()
117 for handle in re.findall(r"(?<![A-Za-z0-9._%+/-])@([A-Za-z0-9][A-Za-z0-9-]{0,38})(?![A-Za-z0-9-]*\.[A-Za-z]{2,})(?![A-Za-z0-9-]*/)", changelog):
118 if not handle.isdigit():
119 credit(handle, "changelog credit")
120 for repo in [REPO] + [f"codewhale-hq/{r}" for r in SIBLINGS]:
121 for row in gh_json("api", f"repos/{repo}/contributors?per_page=100", "--paginate", "--jq", ".[] | {login, type}"):
122 if row["type"] == "User":
123 credit(row["login"], "commit")
124 for row in gh_json("api", f"repos/{repo}/pulls?state=closed&per_page=100", "--paginate", "--jq",
125 ".[] | select(.merged_at != null) | {login: .user.login, type: .user.type}"):
126 if row["type"] == "User":
127 credit(row["login"], "merged pull request")
128 known = users_exist(set(sources))
129 for login in set(sources):
130 uid = ids.get(login.lower())
131 if login.lower() not in known and uid:
132 proc = subprocess.run(["gh", "api", f"/user/{uid}"], cwd=ROOT, capture_output=True, text=True)
133 user = json.loads(proc.stdout) if proc.stdout.strip().startswith("{") else {}
134 if proc.returncode != 0 and str(user.get("status")) != "404" and "Not Found" not in (user.get("message") or proc.stderr):
135 raise RuntimeError(f"gh api /user/{uid} failed (rc={proc.returncode}): {proc.stderr.strip() or proc.stdout.strip()}")
136 if user.get("login"):
137 known[login.lower()] = {"login": user["login"], "name": user.get("name")}
138 people: dict[str, set[str]] = {}
139 for login, why in sources.items():
140 user = known.get(login.lower())
141 if user:
142 people.setdefault(user["login"], set()).update(why)
143 display = {re.sub(r"[^a-z0-9]", "", k.lower()): k for k in people}
144 display.update({re.sub(r"[^a-z0-9]", "", (u.get("name") or "").lower()): u["login"]
145 for u in known.values() if u.get("name") and u["login"] in people})
146 aliases = json.loads(DATA.read_text()).get("unlinked_aliases", {}) if DATA.exists() else {}
147 unlinked = {login for login, why in sources.items() if login.lower() not in known and why & {"commit", "co-author", "merged pull request"}}
148 for n in names:
149 key = re.sub(r"[^a-z0-9]", "", n.lower())
150 if key and key in display:
151 continue
152 n = aliases.get(n, n)
153 if n:
154 unlinked.add(n)
155 data = {
156 "generated_by": "scripts/release/contributor-wall.py refresh",
157 "github_contributor_list": sum(1 for v in people.values() if "commit" in v),
158 "people": [{"login": k, "credited_for": sorted(v)} for k, v in sorted(people.items(), key=lambda kv: kv[0].lower())],
159 "unlinked_commit_names": sorted(unlinked, key=str.lower),
160 "unlinked_aliases": aliases,
161 }
162 DATA.write_text(json.dumps(data, ensure_ascii=False, indent=1) + "\n")
163 print(f"{len(people)} accounts and {len(unlinked)} unlinked commit names -> {DATA.relative_to(ROOT)}")
164
165
166 def avatar(login: str) -> Path:
167 CACHE.mkdir(parents=True, exist_ok=True)
168 path = CACHE / f"{login.lower()}.png"
169 if not path.exists():
170 with urllib.request.urlopen(f"https://github.com/{login}.png?size=96", timeout=30) as resp:
171 path.write_bytes(resp.read())
172 return path
173
174
175 def render() -> None:
176 from PIL import Image, ImageDraw, ImageFont
177
178 data = json.loads(DATA.read_text())
179 logins = [p["login"] for p in data["people"]]
180 extra = [n for n in data["unlinked_commit_names"] if n.lower() not in {x.lower() for x in logins}]
181 total = len(logins) + len(extra)
182 with concurrent.futures.ThreadPoolExecutor(16) as pool:
183 paths = list(pool.map(avatar, logins))
184 cell, cols, pad, head = 52, 26, 24, 76
185 rows = -(-total // cols)
186 img = Image.new("RGB", (pad * 2 + cols * cell, head + pad + rows * cell), (5, 16, 28))
187 draw = ImageDraw.Draw(img)
188 mask = Image.new("L", (44, 44), 0)
189 ImageDraw.Draw(mask).ellipse((0, 0, 43, 43), fill=255)
190 def face_font(size: int, cjk: bool = False):
191 for path in (["/System/Library/Fonts/Hiragino Sans GB.ttc"] if cjk else []) + ["/System/Library/Fonts/HelveticaNeue.ttc"]:
192 try:
193 return ImageFont.truetype(path, size)
194 except OSError:
195 continue
196 return ImageFont.load_default()
197
198 font, small, small_cjk = face_font(30), face_font(15), face_font(15, cjk=True)
199 draw.text((pad, 22), f"{total} people built Codewhale", font=font, fill=(244, 247, 250))
200 for i, path in enumerate(paths):
201 r, c = divmod(i, cols)
202 face = Image.open(io.BytesIO(path.read_bytes())).convert("RGB").resize((44, 44), Image.LANCZOS)
203 img.paste(face, (pad + c * cell + 4, head + r * cell + 4), mask)
204 for k, name in enumerate(extra, start=len(paths)):
205 r, c = divmod(k, cols)
206 x, y = pad + c * cell + 4, head + r * cell + 4
207 draw.ellipse((x, y, x + 43, y + 43), fill=(16, 46, 70))
208 draw.text((x + 22, y + 22), name[:2], font=small if name.isascii() else small_cjk, fill=(159, 179, 200), anchor="mm")
209 WALL.parent.mkdir(parents=True, exist_ok=True)
210 img.quantize(256, method=Image.Quantize.MEDIANCUT).save(WALL, optimize=True)
211
212 links = " · ".join(f"[{x}](https://github.com/{x})" for x in logins)
213 section = (
214 "<!-- contributor-wall:start -->\n## Everyone\n\n"
215 f"[![{total} people built Codewhale](assets/contributors.png)](#everyone)\n\n"
216 f"{total} people have code, co-authored commits, carried-forward pull requests or credited reports in Codewhale. "
217 "GitHub's contributor count includes only commit authors and co-authors whose email is linked to their "
218 "account, so it misses many of them. If your commits are missing there, add your commit email to your "
219 "GitHub account and they will link.\n\n"
220 f"{links}\n\nAlso with us, credited without a linked GitHub account: {' · '.join(extra)}.\n"
221 "<!-- contributor-wall:end -->\n"
222 )
223 doc = ROOT / "docs" / "CONTRIBUTORS.md"
224 text = doc.read_text()
225 if "<!-- contributor-wall:start -->" in text:
226 text = re.sub(r"<!-- contributor-wall:start -->.*?<!-- contributor-wall:end -->\n", lambda _: section, text, flags=re.S)
227 else:
228 text = text.replace("## Organizational thanks", section + "\n## Organizational thanks", 1)
229 doc.write_text(text)
230 print(f"{total} people -> {WALL.relative_to(ROOT)} and docs/CONTRIBUTORS.md")
231
232
233 if __name__ == "__main__":
234 if len(sys.argv) != 2 or sys.argv[1] not in ("refresh", "render"):
235 sys.exit(__doc__)
236 {"refresh": refresh, "render": render}[sys.argv[1]]()
237
237 lines PYTHON