返回 last30days-skill
update_star_history.py
根目录 / .github / scripts / update_star_history.py
1 #!/usr/bin/env python3
2 """Update star history JSON from GitHub API and render clean light/dark SVGs.
3
4 Zero external dependencies (Python 3 stdlib only). Designed to run daily in
5 GitHub Actions and push only the generated JSON + SVGs to a dedicated orphan
6 branch (`star-history-assets`), avoiding GitHub's 40,000-star stargazer
7 pagination cap and keeping `main` free of automated commits.
8 """
9
10 from __future__ import annotations
11
12 import argparse
13 import json
14 import math
15 import os
16 import urllib.error
17 import urllib.request
18 from datetime import date, datetime, timezone
19 from html import escape
20 from pathlib import Path
21
22 THEMES: dict[str, dict[str, str]] = {
23 "light": {
24 "bg": "#ffffff",
25 "border": "#d0d7de",
26 "text": "#1f2328",
27 "muted": "#656d76",
28 "grid": "#e5e7eb",
29 "line": "#2563eb",
30 "area_top": "#2563eb",
31 "area_top_opacity": "0.20",
32 "area_bottom_opacity": "0.01",
33 "badge_bg": "#eff6ff",
34 "badge_border": "#bfdbfe",
35 "badge_text": "#1d4ed8",
36 "star_fill": "#eab308",
37 "dot_ring": "#ffffff",
38 "streak_fill": "#2563eb",
39 "streak_opacity": "0.08",
40 },
41 "dark": {
42 "bg": "#0d1117",
43 "border": "#30363d",
44 "text": "#e6edf3",
45 "muted": "#8b949e",
46 "grid": "#21262d",
47 "line": "#58a6ff",
48 "area_top": "#58a6ff",
49 "area_top_opacity": "0.24",
50 "area_bottom_opacity": "0.01",
51 "badge_bg": "#16243a",
52 "badge_border": "#1f4270",
53 "badge_text": "#79c0ff",
54 "star_fill": "#facc15",
55 "dot_ring": "#0d1117",
56 "streak_fill": "#58a6ff",
57 "streak_opacity": "0.10",
58 },
59 }
60
61 MONTH_NAMES = [
62 "",
63 "Jan",
64 "Feb",
65 "Mar",
66 "Apr",
67 "May",
68 "Jun",
69 "Jul",
70 "Aug",
71 "Sep",
72 "Oct",
73 "Nov",
74 "Dec",
75 ]
76
77
78 def fetch_live_stars(repo: str, token: str | None = None) -> int:
79 """Fetch current stargazers_count via a single GitHub REST API call."""
80 url = f"https://api.github.com/repos/{repo}"
81 headers = {
82 "Accept": "application/vnd.github+json",
83 "User-Agent": "last30days-star-history-action",
84 "X-GitHub-Api-Version": "2022-11-28",
85 }
86 if token:
87 headers["Authorization"] = f"Bearer {token}"
88 req = urllib.request.Request(url, headers=headers)
89 with urllib.request.urlopen(req, timeout=20) as resp:
90 payload = json.loads(resp.read().decode("utf-8"))
91 count = int(payload["stargazers_count"])
92 if count < 0:
93 raise ValueError(f"Unexpected stargazers_count: {count}")
94 return count
95
96
97 def merge_point(
98 points: list[list[object]], day_iso: str, stars: int
99 ) -> list[list[object]]:
100 """Insert or update (day_iso, stars), preserving sorted monotonic dates."""
101 by_date: dict[str, int] = {}
102 for d, s in points:
103 d_str = str(d)
104 s_int = int(s)
105 by_date[d_str] = max(by_date.get(d_str, 0), s_int)
106
107 prev = by_date.get(day_iso, 0)
108 by_date[day_iso] = max(prev, int(stars))
109
110 ordered = sorted(by_date.items(), key=lambda kv: kv[0])
111 merged: list[list[object]] = []
112 highest = 0
113 for d, s in ordered:
114 highest = max(highest, s)
115 merged.append([d, highest])
116 return merged
117
118
119 def nice_y_scale(max_val: int) -> tuple[int, list[int]]:
120 """Compute a clean ceiling and 4-5 horizontal tick values."""
121 target = max(1000, int(max_val * 1.08))
122 raw_step = target / 4.0
123 mag = 10 ** int(math.floor(math.log10(raw_step)))
124 norm = raw_step / mag
125 if norm <= 1.0:
126 step = 1 * mag
127 elif norm <= 2.0:
128 step = 2 * mag
129 elif norm <= 5.0:
130 step = 5 * mag
131 else:
132 step = 10 * mag
133 y_max = int(math.ceil(max_val * 1.04 / step) * step)
134 if y_max - max_val < step * 0.15:
135 y_max += step
136 ticks = list(range(0, y_max + 1, step))
137 return y_max, ticks
138
139
140 def fmt_k(val: int, decimals: int = 1) -> str:
141 if val >= 1000:
142 if val % 1000 == 0 and decimals == 0:
143 return f"{val // 1000}K"
144 s = f"{val / 1000:.{decimals}f}".rstrip("0").rstrip(".")
145 return f"{s}K"
146 return str(val)
147
148
149 def fmt_date_short(d: date) -> str:
150 return f"{MONTH_NAMES[d.month]} {d.day}, {d.year}"
151
152
153 def iter_month_ticks(start: date, end: date) -> list[tuple[date, str]]:
154 """Return evenly spaced month boundaries that never crowd the X-axis."""
155 months: list[date] = []
156 y, m = start.year, start.month + 1
157 if m > 12:
158 y += 1
159 m = 1
160 while date(y, m, 1) <= end:
161 months.append(date(y, m, 1))
162 m += 1
163 if m > 12:
164 y += 1
165 m = 1
166
167 if not months:
168 return []
169
170 # Thin ticks if the repo spans more than 12 months
171 stride = max(1, math.ceil(len(months) / 11))
172 show_year = start.year != end.year
173 ticks: list[tuple[date, str]] = []
174 for idx, d in enumerate(months):
175 if idx % stride != 0:
176 continue
177 if show_year and (d.month == 1 or idx == 0):
178 label = f"{MONTH_NAMES[d.month]} '{str(d.year)[2:]}"
179 else:
180 label = MONTH_NAMES[d.month]
181 ticks.append((d, label))
182 return ticks
183
184
185 def interpolate_stars(points: list[tuple[date, int]], target: date) -> int:
186 """Linearly interpolate star count at a milestone date."""
187 for d, s in points:
188 if d == target:
189 return s
190 if target <= points[0][0]:
191 return points[0][1]
192 if target >= points[-1][0]:
193 return points[-1][1]
194 for (d1, s1), (d2, s2) in zip(points, points[1:]):
195 if d1 <= target <= d2:
196 span = (d2 - d1).days or 1
197 frac = (target - d1).days / span
198 return round(s1 + frac * (s2 - s1))
199 return points[-1][1]
200
201
202 def compute_recent_delta(points: list[tuple[date, int]], days: int = 30) -> tuple[int, int]:
203 """Return (actual_days, star_delta) over the trailing window."""
204 end_d, end_s = points[-1]
205 target = date.fromordinal(end_d.toordinal() - days)
206 if target < points[0][0]:
207 target = points[0][0]
208 start_s = interpolate_stars(points, target)
209 return (end_d - target).days, max(0, end_s - start_s)
210
211
212 def render_svg(data: dict, theme_name: str) -> str:
213 t = THEMES[theme_name]
214 repo = str(data["repo"])
215 raw_points = data["points"]
216 points: list[tuple[date, int]] = [
217 (date.fromisoformat(str(d)), int(s)) for d, s in raw_points
218 ]
219 milestones = data.get("milestones", [])
220
221 W, H = 840, 390
222 pad_left, pad_right, pad_top, pad_bottom = 62, 86, 74, 54
223 cw = W - pad_left - pad_right
224 ch = H - pad_top - pad_bottom
225
226 start_d = points[0][0]
227 end_d = points[-1][0]
228 total_days = max(1, (end_d - start_d).days)
229 latest_stars = points[-1][1]
230 y_max, y_ticks = nice_y_scale(latest_stars)
231
232 def x_pos(d: date) -> float:
233 return pad_left + ((d - start_d).days / total_days) * cw
234
235 def y_pos(val: int) -> float:
236 return pad_top + ch - (val / y_max) * ch
237
238 coords = [(x_pos(d), y_pos(s), d, s) for d, s in points]
239 line_d = " ".join(
240 f"{'M' if i == 0 else 'L'}{x:.1f},{y:.1f}"
241 for i, (x, y, _, _) in enumerate(coords)
242 )
243 area_d = (
244 f"{line_d} L{coords[-1][0]:.1f},{pad_top + ch:.1f} "
245 f"L{coords[0][0]:.1f},{pad_top + ch:.1f} Z"
246 )
247
248 # Trailing 30-day delta for header subtitle
249 win_days, delta_30d = compute_recent_delta(points, 30)
250 delta_label = f"+{delta_30d:,} last {win_days}d" if delta_30d > 0 else ""
251
252 # Build gridlines & Y ticks
253 y_grid_svg: list[str] = []
254 for tick in y_ticks:
255 yp = y_pos(tick)
256 label = "0" if tick == 0 else fmt_k(tick, decimals=0)
257 dash = "" if tick == 0 else ' stroke-dasharray="4 4"'
258 y_grid_svg.append(
259 f' <line x1="{pad_left}" y1="{yp:.1f}" x2="{W - pad_right}" y2="{yp:.1f}" '
260 f'stroke="{t["grid"]}" stroke-width="1"{dash} />'
261 )
262 y_grid_svg.append(
263 f' <text x="{pad_left - 10}" y="{yp + 4:.1f}" text-anchor="end" '
264 f'fill="{t["muted"]}" font-size="11.5" font-weight="500">{label}</text>'
265 )
266
267 # Build X ticks
268 x_ticks_svg: list[str] = []
269 for md, mlabel in iter_month_ticks(start_d, end_d):
270 xp = x_pos(md)
271 x_ticks_svg.append(
272 f' <line x1="{xp:.1f}" y1="{pad_top + ch:.1f}" x2="{xp:.1f}" y2="{pad_top + ch + 5:.1f}" '
273 f'stroke="{t["border"]}" stroke-width="1" />'
274 )
275 x_ticks_svg.append(
276 f' <text x="{xp:.1f}" y="{pad_top + ch + 20:.1f}" text-anchor="middle" '
277 f'fill="{t["muted"]}" font-size="11.5" font-weight="500">{escape(mlabel)}</text>'
278 )
279
280 # Build milestone callouts (skip any that would crowd the right edge)
281 milestones_svg: list[str] = []
282 for m in milestones:
283 md = date.fromisoformat(str(m["date"]))
284 if md < start_d or md > end_d:
285 continue
286 ms = interpolate_stars(points, md)
287 mx = x_pos(md)
288 my = y_pos(ms)
289 dx = float(m.get("dx", -20))
290 dy = float(m.get("dy", -30))
291 tx = max(pad_left + 12, min(W - pad_right - 12, mx + dx))
292 ty = max(pad_top + 14, min(pad_top + ch - 24, my + dy))
293 anchor = "end" if dx < 0 else "start"
294 leader_y = ty + (6 if dy < 0 else -11)
295 milestones_svg.append(
296 f' <line x1="{mx:.1f}" y1="{my:.1f}" x2="{tx:.1f}" y2="{leader_y:.1f}" '
297 f'stroke="{t["muted"]}" stroke-width="1" stroke-dasharray="2 2" opacity="0.65" />'
298 )
299 milestones_svg.append(
300 f' <circle cx="{mx:.1f}" cy="{my:.1f}" r="3.8" '
301 f'fill="{t["bg"]}" stroke="{t["line"]}" stroke-width="2" />'
302 )
303 milestones_svg.append(
304 f' <text x="{tx:.1f}" y="{ty:.1f}" text-anchor="{anchor}" '
305 f'fill="{t["text"]}" font-size="11.5" font-weight="600">{escape(str(m["label"]))}</text>'
306 )
307 if m.get("sub"):
308 milestones_svg.append(
309 f' <text x="{tx:.1f}" y="{ty + 13:.1f}" text-anchor="{anchor}" '
310 f'fill="{t["muted"]}" font-size="10.5">{escape(str(m["sub"]))}</text>'
311 )
312
313 last_x, last_y, _, _ = coords[-1]
314 pill_text = f"{latest_stars:,}"
315 pill_w = max(84, 30 + len(pill_text) * 8)
316 pill_x = W - 24 - pill_w
317 pill_y = 20
318
319 grad_id = f"starArea_{theme_name}"
320 font_sans = (
321 "-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif"
322 )
323 font_mono = "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace"
324
325 date_span = f"{MONTH_NAMES[start_d.month]} {start_d.year} – {fmt_date_short(end_d)}"
326 footer_right = f"Updated {fmt_date_short(end_d)} · Auto-updated daily"
327
328 return f"""<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}" role="img" aria-label="GitHub Star History for {escape(repo)}: {latest_stars:,} stars">
329 <defs>
330 <linearGradient id="{grad_id}" x1="0" y1="0" x2="0" y2="1">
331 <stop offset="0%" stop-color="{t["area_top"]}" stop-opacity="{t["area_top_opacity"]}" />
332 <stop offset="100%" stop-color="{t["area_top"]}" stop-opacity="{t["area_bottom_opacity"]}" />
333 </linearGradient>
334 </defs>
335
336 <rect x="0.5" y="0.5" width="{W - 1}" height="{H - 1}" rx="12" fill="{t["bg"]}" stroke="{t["border"]}" stroke-width="1" />
337
338 <g font-family="{font_sans}">
339 <text x="24" y="34" fill="{t["text"]}" font-size="16" font-weight="700">Star History</text>
340 <text x="126" y="34" fill="{t["muted"]}" font-size="13" font-family="{font_mono}">{escape(repo)}</text>
341 <text x="24" y="53" fill="{t["muted"]}" font-size="12">{escape(date_span)}{(" · " + escape(delta_label)) if delta_label else ""}</text>
342
343 <rect x="{pill_x}" y="{pill_y}" width="{pill_w}" height="28" rx="14" fill="{t["badge_bg"]}" stroke="{t["badge_border"]}" stroke-width="1" />
344 <path d="M{pill_x + 16} {pill_y + 7.5}l1.85 3.75 4.14.6-3 2.92.71 4.13L{pill_x + 16} {pill_y + 16.95}l-3.7 1.95.71-4.13-3-2.92 4.14-.6z" fill="{t["star_fill"]}" />
345 <text x="{pill_x + 27}" y="{pill_y + 18.5}" fill="{t["badge_text"]}" font-size="13" font-weight="700">{escape(pill_text)}</text>
346
347 {chr(10).join(y_grid_svg)}
348 {chr(10).join(x_ticks_svg)}
349
350 <path d="{area_d}" fill="url(#{grad_id})" />
351 <path d="{line_d}" fill="none" stroke="{t["line"]}" stroke-width="2.75" stroke-linejoin="round" stroke-linecap="round" />
352
353 {chr(10).join(milestones_svg)}
354
355 <circle cx="{last_x:.1f}" cy="{last_y:.1f}" r="9" fill="{t["line"]}" opacity="0.22" />
356 <circle cx="{last_x:.1f}" cy="{last_y:.1f}" r="4.8" fill="{t["line"]}" stroke="{t["dot_ring"]}" stroke-width="2.2" />
357 <text x="{last_x + 11:.1f}" y="{last_y + 4:.1f}" fill="{t["line"]}" font-size="13" font-weight="700">{escape(fmt_k(latest_stars, decimals=1))}</text>
358 <text x="{last_x + 11:.1f}" y="{last_y + 18:.1f}" fill="{t["muted"]}" font-size="10.5">{escape(MONTH_NAMES[end_d.month])} {end_d.day}</text>
359
360 <text x="24" y="{H - 14}" fill="{t["muted"]}" font-size="10.5">GitHub Stars</text>
361 <text x="{W - 24}" y="{H - 14}" text-anchor="end" fill="{t["muted"]}" font-size="10.5">{escape(footer_right)}</text>
362 </g>
363 </svg>
364 """
365
366
367 def main() -> int:
368 parser = argparse.ArgumentParser(description="Update star history JSON and SVGs.")
369 parser.add_argument("--data", required=True, help="Path to star-history.json (read/write)")
370 parser.add_argument("--seed", help="Fallback seed JSON if --data does not exist yet")
371 parser.add_argument("--out-light", required=True, help="Output path for light SVG")
372 parser.add_argument("--out-dark", required=True, help="Output path for dark SVG")
373 parser.add_argument("--repo", help="Override owner/repo for GitHub API fetch")
374 parser.add_argument("--fetch", action="store_true", help="Fetch live star count from GitHub API")
375 parser.add_argument("--stars", type=int, help="Explicit star count override (for testing/manual runs)")
376 parser.add_argument("--date", help="Explicit UTC YYYY-MM-DD date override")
377 args = parser.parse_args()
378
379 data_path = Path(args.data)
380 if data_path.exists():
381 data = json.loads(data_path.read_text(encoding="utf-8"))
382 elif args.seed and Path(args.seed).exists():
383 data = json.loads(Path(args.seed).read_text(encoding="utf-8"))
384 else:
385 raise FileNotFoundError(f"Neither --data ({data_path}) nor --seed ({args.seed}) exists.")
386
387 repo = args.repo or data["repo"]
388 data["repo"] = repo
389
390 # Keep milestones synced with seed if seed exists
391 if args.seed and Path(args.seed).exists():
392 seed_data = json.loads(Path(args.seed).read_text(encoding="utf-8"))
393 if "milestones" in seed_data:
394 data["milestones"] = seed_data["milestones"]
395
396 if args.date is None:
397 day_iso = datetime.now(timezone.utc).date().isoformat()
398 else:
399 try:
400 day_iso = date.fromisoformat(args.date).isoformat()
401 except ValueError:
402 parser.error("--date must be a valid date in YYYY-MM-DD format")
403
404 if args.stars is not None:
405 data["points"] = merge_point(data["points"], day_iso, args.stars)
406 elif args.fetch:
407 token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN")
408 try:
409 live = fetch_live_stars(repo, token=token)
410 except urllib.error.URLError as exc:
411 raise SystemExit(f"Failed to fetch stargazers_count for {repo}: {exc}") from exc
412 data["points"] = merge_point(data["points"], day_iso, live)
413
414 data_path.parent.mkdir(parents=True, exist_ok=True)
415 data_path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
416
417 for theme_name, out_file in (("light", args.out_light), ("dark", args.out_dark)):
418 out_path = Path(out_file)
419 out_path.parent.mkdir(parents=True, exist_ok=True)
420 out_path.write_text(render_svg(data, theme_name), encoding="utf-8")
421
422 latest_date, latest_stars = data["points"][-1]
423 print(f"Updated {repo}: {latest_stars:,} stars as of {latest_date}")
424 return 0
425
426
427 if __name__ == "__main__":
428 raise SystemExit(main())
429
429 lines PYTHON