codeyear 0.2.15__tar.gz → 0.2.17__tar.gz

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.
Files changed (44) hide show
  1. {codeyear-0.2.15 → codeyear-0.2.17}/PKG-INFO +5 -5
  2. {codeyear-0.2.15 → codeyear-0.2.17}/README.md +4 -4
  3. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear/__init__.py +1 -1
  4. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear/card.py +128 -24
  5. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear/cli.py +54 -81
  6. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear/config.py +5 -0
  7. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear/github_public.py +160 -21
  8. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear/gui.py +123 -25
  9. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear/html_report.py +79 -41
  10. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear/i18n.py +13 -0
  11. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear/languages.py +22 -5
  12. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear/poster.py +23 -21
  13. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear/report_theme.py +9 -0
  14. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear/runner.py +51 -13
  15. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear/scanner.py +96 -35
  16. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear/server.py +88 -11
  17. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear/stats.py +208 -36
  18. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear/updater.py +65 -20
  19. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear/wizard.py +2 -2
  20. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear.egg-info/PKG-INFO +5 -5
  21. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear.egg-info/SOURCES.txt +3 -1
  22. {codeyear-0.2.15 → codeyear-0.2.17}/pyproject.toml +1 -1
  23. codeyear-0.2.17/tests/test_commit_completeness.py +86 -0
  24. codeyear-0.2.17/tests/test_review_regressions.py +450 -0
  25. codeyear-0.2.17/tests/test_v0217_optimizations.py +392 -0
  26. codeyear-0.2.15/tests/test_review_regressions.py +0 -45
  27. {codeyear-0.2.15 → codeyear-0.2.17}/LICENSE +0 -0
  28. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear/__main__.py +0 -0
  29. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear/keywords.py +0 -0
  30. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear/personas.py +0 -0
  31. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear/profile.py +0 -0
  32. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear.egg-info/dependency_links.txt +0 -0
  33. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear.egg-info/entry_points.txt +0 -0
  34. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear.egg-info/requires.txt +0 -0
  35. {codeyear-0.2.15 → codeyear-0.2.17}/codeyear.egg-info/top_level.txt +0 -0
  36. {codeyear-0.2.15 → codeyear-0.2.17}/setup.cfg +0 -0
  37. {codeyear-0.2.15 → codeyear-0.2.17}/tests/test_cli_boolean_overrides.py +0 -0
  38. {codeyear-0.2.15 → codeyear-0.2.17}/tests/test_core.py +0 -0
  39. {codeyear-0.2.15 → codeyear-0.2.17}/tests/test_github_fallback.py +0 -0
  40. {codeyear-0.2.15 → codeyear-0.2.17}/tests/test_github_pagination_completeness.py +0 -0
  41. {codeyear-0.2.15 → codeyear-0.2.17}/tests/test_profile_push_safety.py +0 -0
  42. {codeyear-0.2.15 → codeyear-0.2.17}/tests/test_public_push_safety.py +0 -0
  43. {codeyear-0.2.15 → codeyear-0.2.17}/tests/test_updater_prerelease.py +0 -0
  44. {codeyear-0.2.15 → codeyear-0.2.17}/tests/test_updater_versions.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: codeyear
3
- Version: 0.2.15
3
+ Version: 0.2.17
4
4
  Summary: Local-first annual coding report generated from your own git history.
5
5
  Author: CodeYear contributors
6
6
  License: MIT
@@ -66,7 +66,7 @@ codeyear
66
66
  也可以从 Release 下载 wheel:
67
67
 
68
68
  ```bash
69
- pip install https://github.com/Qiongkura/codeyear/releases/download/v0.2.15/codeyear-0.2.15-py3-none-any.whl
69
+ pip install https://github.com/Qiongkura/codeyear/releases/download/v0.2.16/codeyear-0.2.16-py3-none-any.whl
70
70
  ```
71
71
 
72
72
  > exe 未做代码签名,Windows SmartScreen 可能提示;点「更多信息 → 仍要运行」。
@@ -86,7 +86,7 @@ python -m codeyear scan ~/code --open
86
86
  或者用 uv 一行免安装运行(需要先装 [uv](https://docs.astral.sh/uv/)):
87
87
 
88
88
  ```bash
89
- uvx --from "https://github.com/Qiongkura/codeyear/releases/download/v0.2.15/codeyear-0.2.15-py3-none-any.whl" codeyear scan ~/code --open
89
+ uvx --from "https://github.com/Qiongkura/codeyear/releases/download/v0.2.16/codeyear-0.2.16-py3-none-any.whl" codeyear scan ~/code --open
90
90
  # 或直接从源码运行:
91
91
  uvx --from git+https://github.com/Qiongkura/codeyear.git codeyear scan ~/code --open
92
92
  ```
@@ -218,7 +218,7 @@ https://your-host/card.svg?username=Qiongkura&year=2026&lang=en
218
218
  > 文件名绕过 GitHub 的图片缓存;无需手动粘贴 embed 片段。模板默认每天 04:00 UTC
219
219
  > 更新;改 workflow 里的 `cron` 可切成每周一 `0 4 * * 1` 或每月 1 日 `0 4 1 * *`。
220
220
  > 跨年时如果新的一年还没有提交,`--fallback-previous` 会继续显示上一年的卡片。
221
- > 模板直接安装 Release 里的 wheel;升级时改 `CODEYEAR_VERSION`(当前 `0.2.15`)。
221
+ > 模板直接安装 Release 里的 wheel;升级时改 `CODEYEAR_VERSION`(当前 `0.2.16`)。
222
222
  > 提交量大的账号建议在 Profile 仓库添加 `CODEYEAR_TOKEN`(PAT)secret;模板会优先使用它,
223
223
  > 否则回退到 `GITHUB_TOKEN`。`GITHUB_TOKEN` 在 Actions 里通常只有 1,000 次/小时额度,
224
224
  > 超过这个量时提交详情会被截断。
@@ -410,7 +410,7 @@ codeyear github Qiongkura --year 2026 --card-only \
410
410
  | `--all-branches` | 统计所有本地分支/tag 的提交(默认只看当前分支) |
411
411
  | `--max-depth 6` | 每个根目录向下查找仓库的最大文件夹层数 |
412
412
  | `--timeout 300` | 单个仓库的扫描超时(秒) |
413
- | `--jobs 4` | 并行扫描的仓库数,项目多时明显加快 |
413
+ | `--jobs N` | 并行扫描的仓库数,默认按 CPU 核数(2–8)自动设置 |
414
414
  | `--no-png` / `--no-html` | 跳过 PNG / HTML(可同时使用) |
415
415
  | `--no-long` | 不生成完整版长图(默认生成) |
416
416
  | `--no-card` | 不生成 GitHub 主页卡片 |
@@ -33,7 +33,7 @@ codeyear
33
33
  也可以从 Release 下载 wheel:
34
34
 
35
35
  ```bash
36
- pip install https://github.com/Qiongkura/codeyear/releases/download/v0.2.15/codeyear-0.2.15-py3-none-any.whl
36
+ pip install https://github.com/Qiongkura/codeyear/releases/download/v0.2.16/codeyear-0.2.16-py3-none-any.whl
37
37
  ```
38
38
 
39
39
  > exe 未做代码签名,Windows SmartScreen 可能提示;点「更多信息 → 仍要运行」。
@@ -53,7 +53,7 @@ python -m codeyear scan ~/code --open
53
53
  或者用 uv 一行免安装运行(需要先装 [uv](https://docs.astral.sh/uv/)):
54
54
 
55
55
  ```bash
56
- uvx --from "https://github.com/Qiongkura/codeyear/releases/download/v0.2.15/codeyear-0.2.15-py3-none-any.whl" codeyear scan ~/code --open
56
+ uvx --from "https://github.com/Qiongkura/codeyear/releases/download/v0.2.16/codeyear-0.2.16-py3-none-any.whl" codeyear scan ~/code --open
57
57
  # 或直接从源码运行:
58
58
  uvx --from git+https://github.com/Qiongkura/codeyear.git codeyear scan ~/code --open
59
59
  ```
@@ -185,7 +185,7 @@ https://your-host/card.svg?username=Qiongkura&year=2026&lang=en
185
185
  > 文件名绕过 GitHub 的图片缓存;无需手动粘贴 embed 片段。模板默认每天 04:00 UTC
186
186
  > 更新;改 workflow 里的 `cron` 可切成每周一 `0 4 * * 1` 或每月 1 日 `0 4 1 * *`。
187
187
  > 跨年时如果新的一年还没有提交,`--fallback-previous` 会继续显示上一年的卡片。
188
- > 模板直接安装 Release 里的 wheel;升级时改 `CODEYEAR_VERSION`(当前 `0.2.15`)。
188
+ > 模板直接安装 Release 里的 wheel;升级时改 `CODEYEAR_VERSION`(当前 `0.2.16`)。
189
189
  > 提交量大的账号建议在 Profile 仓库添加 `CODEYEAR_TOKEN`(PAT)secret;模板会优先使用它,
190
190
  > 否则回退到 `GITHUB_TOKEN`。`GITHUB_TOKEN` 在 Actions 里通常只有 1,000 次/小时额度,
191
191
  > 超过这个量时提交详情会被截断。
@@ -377,7 +377,7 @@ codeyear github Qiongkura --year 2026 --card-only \
377
377
  | `--all-branches` | 统计所有本地分支/tag 的提交(默认只看当前分支) |
378
378
  | `--max-depth 6` | 每个根目录向下查找仓库的最大文件夹层数 |
379
379
  | `--timeout 300` | 单个仓库的扫描超时(秒) |
380
- | `--jobs 4` | 并行扫描的仓库数,项目多时明显加快 |
380
+ | `--jobs N` | 并行扫描的仓库数,默认按 CPU 核数(2–8)自动设置 |
381
381
  | `--no-png` / `--no-html` | 跳过 PNG / HTML(可同时使用) |
382
382
  | `--no-long` | 不生成完整版长图(默认生成) |
383
383
  | `--no-card` | 不生成 GitHub 主页卡片 |
@@ -1,3 +1,3 @@
1
1
  """CodeYear · 本地优先的年度代码报告生成器."""
2
2
 
3
- __version__ = "0.2.15"
3
+ __version__ = "0.2.17"
@@ -3,7 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import html
6
- from datetime import date, datetime, timedelta
6
+ from datetime import datetime, timedelta
7
7
  from pathlib import Path
8
8
 
9
9
  from .stats import (
@@ -13,7 +13,11 @@ from .stats import (
13
13
  fmt_int,
14
14
  fmt_signed_pair,
15
15
  language_breakdown,
16
+ month_labels,
16
17
  parse_daily,
18
+ peak_month,
19
+ window_days,
20
+ window_months,
17
21
  )
18
22
 
19
23
  W, H = 640, 1254
@@ -247,9 +251,10 @@ MONTHS = [
247
251
 
248
252
 
249
253
  def build_svg(stats: ReportStats, *, dark: bool = False,
250
- theme: str = "paper", lang: str = "zh") -> str:
254
+ theme: str = "paper", lang: str = "zh",
255
+ palette_override: dict | None = None) -> str:
251
256
  light, dark_theme = THEMES.get(theme, THEMES["paper"])
252
- c = dark_theme if dark else light
257
+ c = palette_override if palette_override is not None else (dark_theme if dark else light)
253
258
  en = lang == "en"
254
259
 
255
260
  def t(zh: str, english: str) -> str:
@@ -257,7 +262,8 @@ def build_svg(stats: ReportStats, *, dark: bool = False,
257
262
 
258
263
  monthly = stats.monthly
259
264
  peak = max(monthly) or 1
260
- peak_month = monthly.index(peak) + 1 if peak else 1
265
+ labels = month_labels(stats)
266
+ _peak_idx, peak_month_no = peak_month(stats)
261
267
  peak_hour = stats.by_hour.index(max(stats.by_hour)) if any(stats.by_hour) else 0
262
268
  owner = (stats.identity_label or "").split(" <")[0].strip()
263
269
 
@@ -300,7 +306,7 @@ def build_svg(stats: ReportStats, *, dark: bool = False,
300
306
  header.append(_rule(142, c["line"]))
301
307
 
302
308
  # ---- six summary tiles (3 x 2) ------------------------------------
303
- active_pct = stats.active_days / (366 if _is_leap(stats.year) else 365)
309
+ active_pct = stats.active_days / window_days(stats)
304
310
  tiles = [
305
311
  (t("COMMITS / 提交", "COMMITS"), fmt_int(stats.commit_count),
306
312
  t("年度提交", "commits this year")),
@@ -338,30 +344,132 @@ def build_svg(stats: ReportStats, *, dark: bool = False,
338
344
  f'<rect x="{x}" y="{baseline - height}" width="{bar_w}" '
339
345
  f'height="{height}" fill="{fill}"/>'
340
346
  )
341
- bars.append(_text(x + bar_w / 2, baseline + 14, f"{i + 1:02d}", 9.5,
347
+ bars.append(_text(x + bar_w / 2, baseline + 14, labels[i], 9.5,
342
348
  c["muted"], anchor="middle"))
343
349
 
344
350
  # ---- contribution calendar ---------------------------------------
345
351
  cell, gap_h = 9, 2
346
- grid_start = date(stats.year, 1, 1)
347
- grid_start -= timedelta(days=grid_start.weekday())
348
- grid_end = date(stats.year, 12, 31)
349
- grid_end += timedelta(days=6 - grid_end.weekday())
352
+ start_w, end_w = date_window(stats)
353
+ grid_start = start_w - timedelta(days=start_w.weekday())
354
+ grid_end = end_w + timedelta(days=6 - end_w.weekday())
350
355
  grid_cols = (grid_end - grid_start).days // 7 + 1
351
356
  grid_w = grid_cols * (cell + gap_h) - gap_h
352
357
  grid_x = (W - grid_w) / 2
353
358
 
354
359
  month_ticks = []
355
- for month in range(1, 13):
356
- col = (date(stats.year, month, 1) - grid_start).days // 7
360
+ for m_date, m_label in window_months(stats):
361
+ col = (m_date - grid_start).days // 7
357
362
  mx = grid_x + col * (cell + gap_h)
358
- month_ticks.append(_text(mx, 588, f"{month:02d}", 9.5, c["muted"]))
363
+ month_ticks.append(_text(mx, 588, m_label, 9.5, c["muted"]))
359
364
 
360
365
  charts = [
361
366
  _text(M, 350, "MONTHLY RHYTHM", 10, c["muted"], spacing=1),
362
367
  _text(RIGHT, 350, t(
363
- f"峰值 {peak_month:02d} 月 · {peak} 次",
364
- f"Peak {MONTHS[peak_month - 1]} · {peak}",
368
+ f"峰值 {peak_month_no:02d} 月 · {peak} 次",
369
+ f"Peak {MONTHS[peak_month_no - 1]} · {peak}",
370
+ ), 10, c["accent"], anchor="end"),
371
+ *bars,
372
+ _rule(462, c["line"]),
373
+ _text(M, 480, "CONTRIBUTION", 10, c["muted"], spacing=1),
374
+ _text(RIGHT, 480, t(
375
+ f"{stats.active_days} 个活跃日",
376
+ f"{stats.active_days} active days",
377
+ ), 10, c["muted"], anchor="end"),
378
+ _heatmap(stats, c, grid_x, 498, cell, gap_h),
379
+ *month_ticks,
380
+ _rule(602, c["line"]),
381
+ ]
382
+
383
+ # ---- derived insights ---------------------------------------------
384
+ cols2 = [M, M + 306]
385
+ top_repo = stats.repo_details[0] if stats.repo_details else None
386
+ if top_repo and stats.commit_count:
387
+ share = top_repo["commits"] / stats.commit_count
388
+ focus_num, focus_unit = f"{share * 100:.0f}", "%"
389
+ focus_sub = t(
390
+ f"大部分提交在 {_truncate(top_repo['name'], 16)}",
391
+ f"Most commits in {_truncate(top_repo['name'], 22)}",
392
+ )
393
+ else:
394
+ focus_num, focus_unit, focus_sub = "—", "", t("暂无数据", "No data")
395
+
396
+ night, weekend = stats.night_share, stats.weekend_share
397
+ rhythm_num, rhythm_unit = f"{peak_hour:02d}:00", ""
398
+ rhythm_sub = t(
399
+ f"深夜提交占 {night:.0%} · 周末 {weekend:.0%}",
400
+ f"{night:.0%} late-night · {weekend:.0%} weekend",
401
+ )
402
+
403
+ size_map = dict(stats.size_buckets)
404
+ size_total = sum(size_map.values()) or 1
405
+ small_share = (size_map.get("0–10", 0) + size_map.get("10–100", 0)) / size_total
406
+ large_share = (size_map.get("500–2k", 0) + size_map.get("2k+", 0)) / size_total
407
+ style_num, style_unit = f"{small_share * 100:.0f}", "%"
408
+ style_sub = t(
409
+ f"小改动为主 · 大改仅 {large_share:.0%}",
410
+ f"Mostly small changes · large {large_share:.0%}",
411
+ )
412
+
413
+ sessions = stats.sessions or {}
414
+ sess_count = int(sessions.get("count") or 0)
415
+ avg_min = int(sessions.get("avg_minutes") or 0)
416
+ long_min = int(sessions.get("longest_minutes") or 0)
417
+ if avg_min:
418
+ if avg_min >= 90:
419
+ pace_num, pace_unit = f"{avg_min / 60:.1f}", t("小时", "h")
420
+ else:
421
+ pace_num, pace_unit = str(avg_min), t("分钟", "min")
422
+ long_label = (
423
+ f"{long_min / 60:.0f}h" if long_min >= 90 else f"{long_min}min"
424
+ ) if en else (
425
+ f"{long_min / 60:.0f} 小时" if long_min >= 90 else f"{long_min} 分钟"
426
+ )
427
+ pace_sub = t(
428
+ f"{sess_count} 次连续写码 · 最长 {long_label}",
429
+ f"{sess_count} sessions · longest {long_label}",
430
+ )
431
+ else:
432
+ pace_num, pace_unit, pace_sub = "—", "", t("暂无会话", "No sessions")
433
+
434
+ churn_total = stats.insertions + stats.deletions
435
+ deletion_share = stats.deletions / churn_total if churn_total else 0
436
+ ratio = stats.insertions / stats.deletions if stats.deletions else 0
437
+ if deletion_share >= 0.5:
438
+ churn_kind = t("重构型", "Refactoring")
439
+ elif deletion_share >= 0.3:
440
+ churn_kind = t("平衡型", "Balanced")
441
+ else:
442
+ churn_kind = t("扩张型", "Expanding")
443
+ if ratio:
444
+ churn_num, churn_unit = f"{ratio:.1f}", ":1"
445
+ churn_sub = t(
446
+ f"每写 {ratio:.1f} 行才删 1 行",
447
+ f"{ratio:.1f} lines written per line deleted",
448
+ )
449
+ else:
450
+ churn_num, churn_unit = t("只增", "add-only"), ""
451
+ churn_sub = t(f"{churn_kind} · 没有删除", f"{churn_kind} · no deletions")
452
+
453
+ # ---- contribution calendar ---------------------------------------
454
+ cell, gap_h = 9, 2
455
+ start_w, end_w = date_window(stats)
456
+ grid_start = start_w - timedelta(days=start_w.weekday())
457
+ grid_end = end_w + timedelta(days=6 - end_w.weekday())
458
+ grid_cols = (grid_end - grid_start).days // 7 + 1
459
+ grid_w = grid_cols * (cell + gap_h) - gap_h
460
+ grid_x = (W - grid_w) / 2
461
+
462
+ month_ticks = []
463
+ for m_date, m_label in window_months(stats):
464
+ col = (m_date - grid_start).days // 7
465
+ mx = grid_x + col * (cell + gap_h)
466
+ month_ticks.append(_text(mx, 588, m_label, 9.5, c["muted"]))
467
+
468
+ charts = [
469
+ _text(M, 350, "MONTHLY RHYTHM", 10, c["muted"], spacing=1),
470
+ _text(RIGHT, 350, t(
471
+ f"峰值 {peak_month_no:02d} 月 · {peak} 次",
472
+ f"Peak {MONTHS[peak_month_no - 1]} · {peak}",
365
473
  ), 10, c["accent"], anchor="end"),
366
474
  *bars,
367
475
  _rule(462, c["line"]),
@@ -447,25 +555,25 @@ def build_svg(stats: ReportStats, *, dark: bool = False,
447
555
 
448
556
  peak_share = peak / max(stats.commit_count, 1)
449
557
  burst_num, burst_unit = f"{peak_share * 100:.0f}", "%"
450
- peak_label = MONTHS[peak_month - 1]
558
+ peak_label = MONTHS[peak_month_no - 1]
451
559
  if peak_share >= 0.5:
452
560
  burst_sub = t(
453
- f"{peak_month} 月占了全年 {peak_share:.0%} 的提交",
561
+ f"{peak_month_no} 月占了全年 {peak_share:.0%} 的提交",
454
562
  f"{peak_label} accounted for {peak_share:.0%} of the year",
455
563
  )
456
564
  elif peak_share >= 0.3:
457
565
  burst_sub = t(
458
- f"{peak_month} 月最忙,占全年 {peak_share:.0%}",
566
+ f"{peak_month_no} 月最忙,占全年 {peak_share:.0%}",
459
567
  f"{peak_label} was busiest at {peak_share:.0%}",
460
568
  )
461
569
  elif peak_share >= 0.18:
462
570
  burst_sub = t(
463
- f"{peak_month} 月提交最多,占 {peak_share:.0%}",
571
+ f"{peak_month_no} 月提交最多,占 {peak_share:.0%}",
464
572
  f"{peak_label} had the most commits ({peak_share:.0%})",
465
573
  )
466
574
  else:
467
575
  burst_sub = t(
468
- f"全年分布比较平均,{peak_month} 月最多",
576
+ f"全年分布比较平均,{peak_month_no} 月最多",
469
577
  f"Fairly even across the year; {peak_label} was slightly ahead",
470
578
  )
471
579
 
@@ -702,10 +810,6 @@ def build_svg(stats: ReportStats, *, dark: bool = False,
702
810
  """
703
811
 
704
812
 
705
- def _is_leap(year: int) -> bool:
706
- return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
707
-
708
-
709
813
  def render(stats: ReportStats, out_path: str | Path, *,
710
814
  theme: str = "paper", lang: str = "zh") -> list[Path]:
711
815
  path = Path(out_path)
@@ -3,9 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import argparse
6
- import json
7
6
  import os
8
- import subprocess
9
7
  import sys
10
8
  import webbrowser
11
9
  from datetime import date
@@ -13,17 +11,32 @@ from pathlib import Path
13
11
 
14
12
  from . import __version__, i18n
15
13
  from .card import THEMES
16
- from .card import render as render_card
17
14
  from .config import load as load_config
18
- from .html_report import render as render_html
19
- from .html_report import render_en as render_html_en
20
- from .poster import render as render_poster
21
- from .poster import render_long
22
- from .runner import discover, report_path, scan
23
- from .stats import fmt_int
15
+ from .runner import (
16
+ DEFAULT_JOBS,
17
+ detect_identity,
18
+ discover,
19
+ render,
20
+ report_path,
21
+ scan,
22
+ )
23
+ from .stats import fmt_int, window_days
24
24
  from .updater import check_update, cleanup_old_executable, perform_update
25
25
 
26
- _NO_WINDOW = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0
26
+
27
+ class _CopyAppendAction(argparse.Action):
28
+ """Append action that never mutates a config-provided default list."""
29
+
30
+ def __call__(self, parser, namespace, values, option_string=None):
31
+ items = list(getattr(namespace, self.dest, None) or [])
32
+ if getattr(namespace, f"_cy_copied_{self.dest}", False) is False:
33
+ items = [] if values == "" else list(items)
34
+ setattr(namespace, f"_cy_copied_{self.dest}", True)
35
+ if values == "":
36
+ items = []
37
+ else:
38
+ items.append(values)
39
+ setattr(namespace, self.dest, items)
27
40
 
28
41
 
29
42
  def _build_parser() -> argparse.ArgumentParser:
@@ -52,6 +65,8 @@ def _build_parser() -> argparse.ArgumentParser:
52
65
  github.add_argument("--max-commits", type=int, default=cfg.get("max_commits", 200),
53
66
  help="最多拉取多少条提交(无 token 时自动限制为 30)")
54
67
  github.add_argument("--include-forks", action="store_true", help="包含 fork 仓库")
68
+ github.add_argument("--include-contributed", action="store_true",
69
+ help="同时统计你向他人/组织公开仓库贡献的提交(PR 合入的外部仓库)")
55
70
  github.add_argument("--open", action=argparse.BooleanOptionalAction,
56
71
  default=cfg.get("open", False), help="生成后打开报告")
57
72
  github.add_argument("--quiet", action="store_true", help="不打印扫描进度")
@@ -88,7 +103,7 @@ def _build_parser() -> argparse.ArgumentParser:
88
103
  scan.add_argument("--rolling", action=argparse.BooleanOptionalAction,
89
104
  default=cfg.get("rolling", False),
90
105
  help="统计过去 365 天(滚动年度),而非自然年")
91
- scan.add_argument("--exclude", action="append", default=cfg.get("exclude", []),
106
+ scan.add_argument("--exclude", action=_CopyAppendAction, default=list(cfg.get("exclude", [])),
92
107
  help="排除指定仓库名或通配符(可重复或逗号分隔)")
93
108
  scan.add_argument("--out", default=cfg.get("out", "codeyear-output"),
94
109
  help="输出目录,默认 ./codeyear-output")
@@ -100,7 +115,7 @@ def _build_parser() -> argparse.ArgumentParser:
100
115
  scan.add_argument("--fallback-previous", action=argparse.BooleanOptionalAction,
101
116
  default=cfg.get("fallback_previous", False),
102
117
  help="当年没有提交时回退到上一年,适合跨年自动更新")
103
- scan.add_argument("--alias", action="append", default=cfg.get("aliases", []),
118
+ scan.add_argument("--alias", action=_CopyAppendAction, default=list(cfg.get("aliases", [])),
104
119
  help="额外作者邮箱或名字,可重复;用于旧提交")
105
120
  scan.add_argument("--no-mailmap", action="store_true",
106
121
  default=cfg.get("no_mailmap", False),
@@ -117,8 +132,8 @@ def _build_parser() -> argparse.ArgumentParser:
117
132
  help="向下查找仓库的最大文件夹层数,默认 6")
118
133
  scan.add_argument("--timeout", type=int, default=cfg.get("timeout", 300),
119
134
  help="单个仓库的扫描超时秒数")
120
- scan.add_argument("--jobs", type=int, default=cfg.get("jobs", 1),
121
- help="并行扫描的仓库数,默认 1")
135
+ scan.add_argument("--jobs", type=int, default=cfg.get("jobs", DEFAULT_JOBS),
136
+ help=f"并行扫描的仓库数,默认 {DEFAULT_JOBS}(机器核数)")
122
137
  scan.add_argument("--theme", choices=sorted(THEMES),
123
138
  default=cfg.get("theme", "paper"),
124
139
  help="卡片主题:paper / mono / forest / ocean")
@@ -151,22 +166,7 @@ def _open_path(path: Path) -> None:
151
166
 
152
167
  def _detect_identity() -> tuple[str, str] | None:
153
168
  """The runner's git identity, used to keep only their own commits."""
154
-
155
- def config(key: str) -> str:
156
- try:
157
- proc = subprocess.run(
158
- ["git", "config", "--global", key],
159
- capture_output=True, text=True, encoding="utf-8",
160
- errors="replace", timeout=10, creationflags=_NO_WINDOW,
161
- )
162
- except (OSError, subprocess.TimeoutExpired):
163
- return ""
164
- return (proc.stdout or "").strip()
165
-
166
- email, name = config("user.email"), config("user.name")
167
- if email or name:
168
- return (email, name)
169
- return None
169
+ return detect_identity()
170
170
 
171
171
 
172
172
  def main(argv: list[str] | None = None) -> int:
@@ -229,6 +229,7 @@ def main(argv: list[str] | None = None) -> int:
229
229
  no_cache=args.no_cache,
230
230
  lang=i18n.get_lang(),
231
231
  tz=args.tz, require_complete=args.require_complete,
232
+ include_contributed=args.include_contributed,
232
233
  )
233
234
  if args.command == "serve":
234
235
  from .server import serve
@@ -296,6 +297,7 @@ def main(argv: list[str] | None = None) -> int:
296
297
  jobs=max(1, args.jobs), progress=progress,
297
298
  compare=args.compare, use_mailmap=not args.no_mailmap,
298
299
  all_branches=args.all_branches,
300
+ rolling=args.rolling,
299
301
  )
300
302
  if previous.commit_count:
301
303
  stats, warnings = previous, prev_warnings
@@ -312,56 +314,31 @@ def main(argv: list[str] | None = None) -> int:
312
314
  return 3
313
315
 
314
316
  out_dir = Path(args.out)
315
- out_dir.mkdir(parents=True, exist_ok=True)
316
- base = out_dir / f"codeyear-{args.year}"
317
-
318
- written: list[tuple[str, Path]] = []
319
-
320
- json_path = base.with_suffix(".json")
321
- json_path.write_text(
322
- json.dumps(stats.as_dict(), ensure_ascii=False, indent=2),
323
- encoding="utf-8",
324
- )
325
- written.append(("JSON", json_path))
326
-
317
+ formats = {"json"}
327
318
  if not args.no_html:
328
- html_path = render_html(stats, base.with_suffix(".html"))
329
- written.append(("HTML", html_path))
330
- en_path = render_html_en(stats, out_dir / f"codeyear-{args.year}-en.html")
331
- written.append(("HTML-EN", en_path))
332
-
319
+ formats.add("html")
333
320
  if not args.no_png:
334
- png_path = render_poster(stats, base.with_suffix(".png"))
335
- written.append(("PNG", png_path))
336
- if i18n.get_lang() == "en":
337
- png_en = render_poster(
338
- stats, out_dir / f"codeyear-{args.year}-en.png", lang="en")
339
- written.append(("PNG-EN", png_en))
321
+ formats.add("png")
340
322
  if not args.no_long:
341
- long_path = render_long(stats, out_dir / f"codeyear-{args.year}-long.png")
342
- written.append(("LONG", long_path))
343
- if i18n.get_lang() == "en":
344
- long_en = render_long(
345
- stats, out_dir / f"codeyear-{args.year}-en-long.png",
346
- lang="en")
347
- written.append(("LONG-EN", long_en))
348
-
349
- card_paths = []
350
- en_cards = []
351
- card_theme = getattr(args, "theme", "paper") or "paper"
323
+ formats.add("long")
352
324
  if not args.no_card:
353
- card_paths = render_card(
354
- stats, out_dir / f"codeyear-{args.year}-card.svg",
355
- theme=card_theme,
356
- )
357
- written.append(("CARD", card_paths[0]))
358
- written.append(("CARD-DARK", card_paths[1]))
359
- en_cards = render_card(
360
- stats, out_dir / f"codeyear-{args.year}-card-en.svg",
361
- theme=card_theme, lang="en",
362
- )
363
- written.append(("CARD-EN", en_cards[0]))
364
- written.append(("CARD-DARK-EN", en_cards[1]))
325
+ formats.add("card")
326
+ card_theme = getattr(args, "theme", "paper") or "paper"
327
+ written = render(
328
+ stats, out_dir, formats=formats,
329
+ card_theme=card_theme, lang=i18n.get_lang(),
330
+ )
331
+ by_label = dict(written)
332
+ card_paths = (
333
+ [by_label["CARD"], by_label["CARD-DARK"]]
334
+ if "CARD" in by_label and "CARD-DARK" in by_label
335
+ else []
336
+ )
337
+ en_cards = (
338
+ [by_label["CARD-EN"], by_label["CARD-DARK-EN"]]
339
+ if "CARD-EN" in by_label and "CARD-DARK-EN" in by_label
340
+ else []
341
+ )
365
342
 
366
343
  exit_code = 0
367
344
  if args.profile_repo:
@@ -398,7 +375,7 @@ def main(argv: list[str] | None = None) -> int:
398
375
  exit_code = 1
399
376
 
400
377
  # Console summary
401
- active_pct = stats.active_days / (366 if _is_leap(args.year) else 365)
378
+ active_pct = stats.active_days / window_days(stats)
402
379
  print()
403
380
  print(i18n.tr(
404
381
  "CodeYear {year} · {title}",
@@ -446,9 +423,5 @@ def main(argv: list[str] | None = None) -> int:
446
423
  return exit_code
447
424
 
448
425
 
449
- def _is_leap(year: int) -> bool:
450
- return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
451
-
452
-
453
426
  if __name__ == "__main__": # pragma: no cover
454
427
  raise SystemExit(main())
@@ -36,6 +36,7 @@ SCHEMA = {
36
36
  "github_user": str,
37
37
  "profile_repo": str,
38
38
  "push_profile": bool,
39
+ "lang": str,
39
40
  }
40
41
 
41
42
 
@@ -76,6 +77,8 @@ def load() -> dict:
76
77
  "paper", "mono", "forest", "ocean",
77
78
  }:
78
79
  continue
80
+ if key == "lang" and value not in {"zh", "en"}:
81
+ continue
79
82
  clean[key] = value
80
83
  if clean.get("max_commits", 1) <= 0:
81
84
  clean.pop("max_commits", None)
@@ -105,6 +108,8 @@ def save(values: dict) -> Path:
105
108
  elif expected is str and isinstance(value, str):
106
109
  if key == "theme" and value not in {"paper", "mono", "forest", "ocean"}:
107
110
  continue
111
+ if key == "lang" and value not in {"zh", "en"}:
112
+ continue
108
113
  clean[key] = value
109
114
  target = path()
110
115
  target.parent.mkdir(parents=True, exist_ok=True)