codeyear 0.2.14__tar.gz → 0.2.15__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 (41) hide show
  1. {codeyear-0.2.14 → codeyear-0.2.15}/PKG-INFO +22 -11
  2. {codeyear-0.2.14 → codeyear-0.2.15}/README.md +20 -10
  3. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear/__init__.py +1 -1
  4. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear/cli.py +13 -9
  5. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear/github_public.py +61 -21
  6. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear/gui.py +6 -0
  7. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear/i18n.py +15 -1
  8. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear/profile.py +69 -15
  9. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear/scanner.py +15 -3
  10. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear/stats.py +2 -2
  11. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear/updater.py +18 -3
  12. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear.egg-info/PKG-INFO +22 -11
  13. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear.egg-info/SOURCES.txt +9 -1
  14. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear.egg-info/requires.txt +1 -0
  15. {codeyear-0.2.14 → codeyear-0.2.15}/pyproject.toml +2 -2
  16. codeyear-0.2.15/tests/test_cli_boolean_overrides.py +52 -0
  17. codeyear-0.2.15/tests/test_github_fallback.py +65 -0
  18. codeyear-0.2.15/tests/test_github_pagination_completeness.py +24 -0
  19. codeyear-0.2.15/tests/test_profile_push_safety.py +174 -0
  20. codeyear-0.2.15/tests/test_public_push_safety.py +34 -0
  21. codeyear-0.2.15/tests/test_review_regressions.py +45 -0
  22. codeyear-0.2.15/tests/test_updater_prerelease.py +20 -0
  23. codeyear-0.2.15/tests/test_updater_versions.py +16 -0
  24. {codeyear-0.2.14 → codeyear-0.2.15}/LICENSE +0 -0
  25. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear/__main__.py +0 -0
  26. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear/card.py +0 -0
  27. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear/config.py +0 -0
  28. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear/html_report.py +0 -0
  29. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear/keywords.py +0 -0
  30. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear/languages.py +0 -0
  31. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear/personas.py +0 -0
  32. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear/poster.py +0 -0
  33. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear/report_theme.py +0 -0
  34. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear/runner.py +0 -0
  35. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear/server.py +0 -0
  36. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear/wizard.py +0 -0
  37. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear.egg-info/dependency_links.txt +0 -0
  38. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear.egg-info/entry_points.txt +0 -0
  39. {codeyear-0.2.14 → codeyear-0.2.15}/codeyear.egg-info/top_level.txt +0 -0
  40. {codeyear-0.2.14 → codeyear-0.2.15}/setup.cfg +0 -0
  41. {codeyear-0.2.14 → codeyear-0.2.15}/tests/test_core.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: codeyear
3
- Version: 0.2.14
3
+ Version: 0.2.15
4
4
  Summary: Local-first annual coding report generated from your own git history.
5
5
  Author: CodeYear contributors
6
6
  License: MIT
@@ -24,6 +24,7 @@ Requires-Python: >=3.9
24
24
  Description-Content-Type: text/markdown
25
25
  License-File: LICENSE
26
26
  Requires-Dist: Pillow>=9.0
27
+ Requires-Dist: packaging>=23.0
27
28
  Provides-Extra: dev
28
29
  Requires-Dist: pytest>=8; extra == "dev"
29
30
  Requires-Dist: pytest-cov>=5; extra == "dev"
@@ -40,8 +41,8 @@ Dynamic: license-file
40
41
  **简体中文** | [English](README.en.md) · [中文简介](docs/intro.zh.md)
41
42
 
42
43
  > 扫描你本地的 git 仓库,生成一份**只属于你**的年度代码手账:中英双语 HTML 报告、
43
- > 2400×3200 海报、完整长图,以及 GitHub 主页卡片。默认只读本地 git,不登录、不上传;
44
- > 公开 GitHub 模式是可选联网功能。
44
+ > 2400×3200 海报、完整长图,以及 GitHub 主页卡片。CLI 本地扫描默认不联网、不上传;
45
+ > GUI 默认会联网检查更新,公开 GitHub 模式和推送是可选联网功能。
45
46
 
46
47
  ![CodeYear 报告预览](docs/report-preview.png)
47
48
 
@@ -65,7 +66,7 @@ codeyear
65
66
  也可以从 Release 下载 wheel:
66
67
 
67
68
  ```bash
68
- pip install https://github.com/Qiongkura/codeyear/releases/download/v0.2.14/codeyear-0.2.14-py3-none-any.whl
69
+ pip install https://github.com/Qiongkura/codeyear/releases/download/v0.2.15/codeyear-0.2.15-py3-none-any.whl
69
70
  ```
70
71
 
71
72
  > exe 未做代码签名,Windows SmartScreen 可能提示;点「更多信息 → 仍要运行」。
@@ -85,7 +86,7 @@ python -m codeyear scan ~/code --open
85
86
  或者用 uv 一行免安装运行(需要先装 [uv](https://docs.astral.sh/uv/)):
86
87
 
87
88
  ```bash
88
- uvx --from "https://github.com/Qiongkura/codeyear/releases/download/v0.2.14/codeyear-0.2.14-py3-none-any.whl" codeyear scan ~/code --open
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
90
  # 或直接从源码运行:
90
91
  uvx --from git+https://github.com/Qiongkura/codeyear.git codeyear scan ~/code --open
91
92
  ```
@@ -112,7 +113,8 @@ codeyear
112
113
  ```
113
114
 
114
115
  会打开桌面窗口:添加多个目录、检查仓库数量、看进度条、选输出位置,完成后直接打开报告。
115
- Windows 也可以在仓库根目录双击 `CodeYear.cmd`。
116
+ Windows 也可以在仓库根目录双击 `CodeYear.cmd`。GUI 默认启动时联网检查版本更新;
117
+ 设置环境变量 `CODEYEAR_NO_UPDATE_CHECK=1` 可关闭自动检查(手动检查仍可联网)。
116
118
 
117
119
  需要 Tkinter;Windows/macOS 的 Python 自带,Linux 装 `python3-tk`。安装后也可以运行 `codeyear-gui`。
118
120
 
@@ -216,7 +218,7 @@ https://your-host/card.svg?username=Qiongkura&year=2026&lang=en
216
218
  > 文件名绕过 GitHub 的图片缓存;无需手动粘贴 embed 片段。模板默认每天 04:00 UTC
217
219
  > 更新;改 workflow 里的 `cron` 可切成每周一 `0 4 * * 1` 或每月 1 日 `0 4 1 * *`。
218
220
  > 跨年时如果新的一年还没有提交,`--fallback-previous` 会继续显示上一年的卡片。
219
- > 模板直接安装 Release 里的 wheel;升级时改 `CODEYEAR_VERSION`(当前 `0.2.14`)。
221
+ > 模板直接安装 Release 里的 wheel;升级时改 `CODEYEAR_VERSION`(当前 `0.2.15`)。
220
222
  > 提交量大的账号建议在 Profile 仓库添加 `CODEYEAR_TOKEN`(PAT)secret;模板会优先使用它,
221
223
  > 否则回退到 `GITHUB_TOKEN`。`GITHUB_TOKEN` 在 Actions 里通常只有 1,000 次/小时额度,
222
224
  > 超过这个量时提交详情会被截断。
@@ -286,7 +288,7 @@ CodeYear 是给开发者做的「年度报告」。官方的 Wrapped 通常只
286
288
 
287
289
  ## 安装与输出
288
290
 
289
- 上面的命令只会安装 Pillow。想把 CodeYear 安装成全局命令:
291
+ 上面的命令会安装 Pillow 和版本比较所需的 packaging。想把 CodeYear 安装成全局命令:
290
292
 
291
293
  ```bash
292
294
  pip install -e .
@@ -365,6 +367,12 @@ codeyear github Qiongkura --year 2026 --card-only \
365
367
  `codeyear-2026-card-vN.svg` 并重写 README,同时清掉旧版本文件;跨年时也会把 README
366
368
  里上一年的引用替换成新一年的卡片。
367
369
 
370
+ 推送前会联网核对当前分支对应的远端上游分支:本地 HEAD 必须与远端完全一致,
371
+ 否则拒绝修改 Profile 或提交,避免把已有未推送提交一起发出去;没有上游、远端分支
372
+ 无法验证、存在已暂存修改或 README/卡片已有未提交修改时也会拒绝。请先自行处理并
373
+ 同步提交,再重试。推送只指定该上游分支,远端并发更新可能导致推送失败,需手动同步。
374
+ 源码版公开数据获取出现不完整警告时,`--push-profile` 也会取消,需先处理警告。
375
+
368
376
  私有仓库要定时更新,可以用 Windows 任务计划、cron 或 self-hosted runner:
369
377
  [定时更新私有项目卡片](docs/schedule.md)。
370
378
 
@@ -449,12 +457,15 @@ codeyear scan D:\code --year 2026 --compare
449
457
  支持 `roots / year / out / author / all_authors / aliases / compare /
450
458
  fallback_previous / all_branches / no_mailmap / jobs / max_depth / timeout /
451
459
  theme / max_commits / open`。命令行显式参数优先于配置文件;文件不存在或字段
452
- 类型不对时会自动忽略。
460
+ 类型不对时会自动忽略。布尔参数可用反向开关临时覆盖,例如 `--no-compare`、
461
+ `--no-rolling`、`--no-open`;使用 `--mailmap` 可覆盖配置中的 `no_mailmap`。
462
+ 公开模式的 `--require-complete` 会在数据警告时退出,可用于单独提交卡片的自动化脚本。
453
463
 
454
464
  ## 隐私
455
465
 
456
- - 默认 `scan` 模式所有统计都在本地完成,**没有任何网络请求**。
457
- - `github` 公开模式、`serve` 在线服务和 `--push-profile` 是可选联网功能;它们只读取公开 GitHub 数据或推送卡片,不会上传本地代码。
466
+ - CLI `scan` 默认只在本地统计,不发网络请求;显式启用 `--push-profile` 例外。
467
+ - GUI 默认联网检查更新;设置 `CODEYEAR_NO_UPDATE_CHECK=1` 可禁用自动检查。
468
+ - `github` 公开模式、`serve` 在线服务和 `--push-profile` 是可选联网功能;推送会发送卡片和 Profile README,以及这些内容包含的数据。
458
469
  - 本地模式只读 `git log`、`git tag`、仓库根目录 README 的第一行和 `git remote`;不读取其它工作区文件。
459
470
  - 输出文件默认忽略在 `.gitignore` 里。
460
471
  - 本地报告页脚标注 `LOCAL ONLY · 数据未上传`;公开模式报告会标注公开数据来源。
@@ -8,8 +8,8 @@
8
8
  **简体中文** | [English](README.en.md) · [中文简介](docs/intro.zh.md)
9
9
 
10
10
  > 扫描你本地的 git 仓库,生成一份**只属于你**的年度代码手账:中英双语 HTML 报告、
11
- > 2400×3200 海报、完整长图,以及 GitHub 主页卡片。默认只读本地 git,不登录、不上传;
12
- > 公开 GitHub 模式是可选联网功能。
11
+ > 2400×3200 海报、完整长图,以及 GitHub 主页卡片。CLI 本地扫描默认不联网、不上传;
12
+ > GUI 默认会联网检查更新,公开 GitHub 模式和推送是可选联网功能。
13
13
 
14
14
  ![CodeYear 报告预览](docs/report-preview.png)
15
15
 
@@ -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.14/codeyear-0.2.14-py3-none-any.whl
36
+ pip install https://github.com/Qiongkura/codeyear/releases/download/v0.2.15/codeyear-0.2.15-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.14/codeyear-0.2.14-py3-none-any.whl" codeyear scan ~/code --open
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
57
57
  # 或直接从源码运行:
58
58
  uvx --from git+https://github.com/Qiongkura/codeyear.git codeyear scan ~/code --open
59
59
  ```
@@ -80,7 +80,8 @@ codeyear
80
80
  ```
81
81
 
82
82
  会打开桌面窗口:添加多个目录、检查仓库数量、看进度条、选输出位置,完成后直接打开报告。
83
- Windows 也可以在仓库根目录双击 `CodeYear.cmd`。
83
+ Windows 也可以在仓库根目录双击 `CodeYear.cmd`。GUI 默认启动时联网检查版本更新;
84
+ 设置环境变量 `CODEYEAR_NO_UPDATE_CHECK=1` 可关闭自动检查(手动检查仍可联网)。
84
85
 
85
86
  需要 Tkinter;Windows/macOS 的 Python 自带,Linux 装 `python3-tk`。安装后也可以运行 `codeyear-gui`。
86
87
 
@@ -184,7 +185,7 @@ https://your-host/card.svg?username=Qiongkura&year=2026&lang=en
184
185
  > 文件名绕过 GitHub 的图片缓存;无需手动粘贴 embed 片段。模板默认每天 04:00 UTC
185
186
  > 更新;改 workflow 里的 `cron` 可切成每周一 `0 4 * * 1` 或每月 1 日 `0 4 1 * *`。
186
187
  > 跨年时如果新的一年还没有提交,`--fallback-previous` 会继续显示上一年的卡片。
187
- > 模板直接安装 Release 里的 wheel;升级时改 `CODEYEAR_VERSION`(当前 `0.2.14`)。
188
+ > 模板直接安装 Release 里的 wheel;升级时改 `CODEYEAR_VERSION`(当前 `0.2.15`)。
188
189
  > 提交量大的账号建议在 Profile 仓库添加 `CODEYEAR_TOKEN`(PAT)secret;模板会优先使用它,
189
190
  > 否则回退到 `GITHUB_TOKEN`。`GITHUB_TOKEN` 在 Actions 里通常只有 1,000 次/小时额度,
190
191
  > 超过这个量时提交详情会被截断。
@@ -254,7 +255,7 @@ CodeYear 是给开发者做的「年度报告」。官方的 Wrapped 通常只
254
255
 
255
256
  ## 安装与输出
256
257
 
257
- 上面的命令只会安装 Pillow。想把 CodeYear 安装成全局命令:
258
+ 上面的命令会安装 Pillow 和版本比较所需的 packaging。想把 CodeYear 安装成全局命令:
258
259
 
259
260
  ```bash
260
261
  pip install -e .
@@ -333,6 +334,12 @@ codeyear github Qiongkura --year 2026 --card-only \
333
334
  `codeyear-2026-card-vN.svg` 并重写 README,同时清掉旧版本文件;跨年时也会把 README
334
335
  里上一年的引用替换成新一年的卡片。
335
336
 
337
+ 推送前会联网核对当前分支对应的远端上游分支:本地 HEAD 必须与远端完全一致,
338
+ 否则拒绝修改 Profile 或提交,避免把已有未推送提交一起发出去;没有上游、远端分支
339
+ 无法验证、存在已暂存修改或 README/卡片已有未提交修改时也会拒绝。请先自行处理并
340
+ 同步提交,再重试。推送只指定该上游分支,远端并发更新可能导致推送失败,需手动同步。
341
+ 源码版公开数据获取出现不完整警告时,`--push-profile` 也会取消,需先处理警告。
342
+
336
343
  私有仓库要定时更新,可以用 Windows 任务计划、cron 或 self-hosted runner:
337
344
  [定时更新私有项目卡片](docs/schedule.md)。
338
345
 
@@ -417,12 +424,15 @@ codeyear scan D:\code --year 2026 --compare
417
424
  支持 `roots / year / out / author / all_authors / aliases / compare /
418
425
  fallback_previous / all_branches / no_mailmap / jobs / max_depth / timeout /
419
426
  theme / max_commits / open`。命令行显式参数优先于配置文件;文件不存在或字段
420
- 类型不对时会自动忽略。
427
+ 类型不对时会自动忽略。布尔参数可用反向开关临时覆盖,例如 `--no-compare`、
428
+ `--no-rolling`、`--no-open`;使用 `--mailmap` 可覆盖配置中的 `no_mailmap`。
429
+ 公开模式的 `--require-complete` 会在数据警告时退出,可用于单独提交卡片的自动化脚本。
421
430
 
422
431
  ## 隐私
423
432
 
424
- - 默认 `scan` 模式所有统计都在本地完成,**没有任何网络请求**。
425
- - `github` 公开模式、`serve` 在线服务和 `--push-profile` 是可选联网功能;它们只读取公开 GitHub 数据或推送卡片,不会上传本地代码。
433
+ - CLI `scan` 默认只在本地统计,不发网络请求;显式启用 `--push-profile` 例外。
434
+ - GUI 默认联网检查更新;设置 `CODEYEAR_NO_UPDATE_CHECK=1` 可禁用自动检查。
435
+ - `github` 公开模式、`serve` 在线服务和 `--push-profile` 是可选联网功能;推送会发送卡片和 Profile README,以及这些内容包含的数据。
426
436
  - 本地模式只读 `git log`、`git tag`、仓库根目录 README 的第一行和 `git remote`;不读取其它工作区文件。
427
437
  - 输出文件默认忽略在 `.gitignore` 里。
428
438
  - 本地报告页脚标注 `LOCAL ONLY · 数据未上传`;公开模式报告会标注公开数据来源。
@@ -1,3 +1,3 @@
1
1
  """CodeYear · 本地优先的年度代码报告生成器."""
2
2
 
3
- __version__ = "0.2.14"
3
+ __version__ = "0.2.15"
@@ -52,12 +52,14 @@ def _build_parser() -> argparse.ArgumentParser:
52
52
  github.add_argument("--max-commits", type=int, default=cfg.get("max_commits", 200),
53
53
  help="最多拉取多少条提交(无 token 时自动限制为 30)")
54
54
  github.add_argument("--include-forks", action="store_true", help="包含 fork 仓库")
55
- github.add_argument("--open", action="store_true", default=cfg.get("open", False),
56
- help="生成后打开报告")
55
+ github.add_argument("--open", action=argparse.BooleanOptionalAction,
56
+ default=cfg.get("open", False), help="生成后打开报告")
57
57
  github.add_argument("--quiet", action="store_true", help="不打印扫描进度")
58
58
  github.add_argument("--theme", choices=sorted(THEMES),
59
59
  default=cfg.get("theme", "paper"),
60
60
  help="卡片主题:paper / mono / forest / ocean")
61
+ github.add_argument("--require-complete", action="store_true",
62
+ help="公开统计有警告时退出,避免自动更新不完整的卡片")
61
63
  github.add_argument("--card-only", action="store_true",
62
64
  help="只生成主页卡片和 embed 片段,不生成完整报告")
63
65
  github.add_argument("--profile-repo", default=None,
@@ -83,7 +85,7 @@ def _build_parser() -> argparse.ArgumentParser:
83
85
  help="要扫描的文件夹(可以多个,默认当前目录)")
84
86
  scan.add_argument("--year", type=int, default=cfg.get("year", date.today().year),
85
87
  help="统计年份,默认今年")
86
- scan.add_argument("--rolling", action="store_true",
88
+ scan.add_argument("--rolling", action=argparse.BooleanOptionalAction,
87
89
  default=cfg.get("rolling", False),
88
90
  help="统计过去 365 天(滚动年度),而非自然年")
89
91
  scan.add_argument("--exclude", action="append", default=cfg.get("exclude", []),
@@ -92,10 +94,10 @@ def _build_parser() -> argparse.ArgumentParser:
92
94
  help="输出目录,默认 ./codeyear-output")
93
95
  scan.add_argument("--author", default=cfg.get("author"),
94
96
  help="只统计匹配的 git author(--author 参数)")
95
- scan.add_argument("--compare", action="store_true",
97
+ scan.add_argument("--compare", action=argparse.BooleanOptionalAction,
96
98
  default=cfg.get("compare", False),
97
99
  help="同时扫描去年,在报告里生成同比数据")
98
- scan.add_argument("--fallback-previous", action="store_true",
100
+ scan.add_argument("--fallback-previous", action=argparse.BooleanOptionalAction,
99
101
  default=cfg.get("fallback_previous", False),
100
102
  help="当年没有提交时回退到上一年,适合跨年自动更新")
101
103
  scan.add_argument("--alias", action="append", default=cfg.get("aliases", []),
@@ -103,10 +105,12 @@ def _build_parser() -> argparse.ArgumentParser:
103
105
  scan.add_argument("--no-mailmap", action="store_true",
104
106
  default=cfg.get("no_mailmap", False),
105
107
  help="忽略仓库里的 .mailmap(默认自动使用)")
106
- scan.add_argument("--all-branches", action="store_true",
108
+ scan.add_argument("--mailmap", dest="no_mailmap", action="store_false",
109
+ help="使用仓库里的 .mailmap")
110
+ scan.add_argument("--all-branches", action=argparse.BooleanOptionalAction,
107
111
  default=cfg.get("all_branches", False),
108
112
  help="统计所有本地分支/tag 的提交(默认只看当前分支)")
109
- scan.add_argument("--all-authors", action="store_true",
113
+ scan.add_argument("--all-authors", action=argparse.BooleanOptionalAction,
110
114
  default=cfg.get("all_authors", False),
111
115
  help="统计所有作者的提交(默认只统计你本人,按 git user.name / user.email 识别)")
112
116
  scan.add_argument("--max-depth", type=int, default=cfg.get("max_depth", 6),
@@ -126,7 +130,7 @@ def _build_parser() -> argparse.ArgumentParser:
126
130
  help="本地 GitHub Profile 仓库路径;只写入本地,不联网")
127
131
  scan.add_argument("--push-profile", action="store_true",
128
132
  help="更新后提交并推送 Profile 仓库(联网);需同时指定 --profile-repo")
129
- scan.add_argument("--open", action="store_true", default=cfg.get("open", False),
133
+ scan.add_argument("--open", action=argparse.BooleanOptionalAction, default=cfg.get("open", False),
130
134
  help="生成后自动打开报告")
131
135
  scan.add_argument("--quiet", action="store_true", help="不打印扫描进度")
132
136
  i18n.localize_parser(parser)
@@ -224,7 +228,7 @@ def main(argv: list[str] | None = None) -> int:
224
228
  cache_dir=args.cache_dir,
225
229
  no_cache=args.no_cache,
226
230
  lang=i18n.get_lang(),
227
- tz=args.tz,
231
+ tz=args.tz, require_complete=args.require_complete,
228
232
  )
229
233
  if args.command == "serve":
230
234
  from .server import serve
@@ -32,6 +32,12 @@ CACHE_VERSION = 1
32
32
  CACHE_MAX = 5000
33
33
 
34
34
 
35
+ class _IncompleteList(list):
36
+ """List result carrying an API pagination-cap marker."""
37
+
38
+ truncated: bool = False
39
+
40
+
35
41
  def default_cache_dir() -> Path:
36
42
  return Path.home() / ".cache" / "codeyear"
37
43
 
@@ -138,6 +144,10 @@ def _dt(
138
144
  return None
139
145
 
140
146
 
147
+ class NoPublicCommitsError(RuntimeError):
148
+ """The requested year contains no public commits."""
149
+
150
+
141
151
  class GitHubAPI:
142
152
  def __init__(self, token: str | None = None) -> None:
143
153
  self.token = token or os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
@@ -198,7 +208,7 @@ def _repos(
198
208
  tz: str | tzinfo | None = None,
199
209
  ) -> list[dict]:
200
210
  target_tz = _parse_tz(tz)
201
- repos: list[dict] = []
211
+ repos = _IncompleteList()
202
212
  for page in range(1, 11):
203
213
  data = api.get(f"/users/{username}/repos", {
204
214
  "type": "owner", "sort": "pushed", "direction": "desc",
@@ -217,6 +227,8 @@ def _repos(
217
227
  repos.append(repo)
218
228
  if len(data) < 100:
219
229
  break
230
+ else:
231
+ repos.truncated = True
220
232
  return repos
221
233
 
222
234
 
@@ -237,7 +249,7 @@ def _commits(
237
249
  # the local year, so commits near midnight in non-UTC zones are kept.
238
250
  since = f"{year - 1}-12-31T00:00:00Z"
239
251
  until = f"{year + 1}-01-02T00:00:00Z"
240
- listed: list[dict] = []
252
+ listed = _IncompleteList()
241
253
  # A busy repository can exceed 1,000 commits in one year; keep paging
242
254
  # until the caller's budget is reached or GitHub runs out of pages.
243
255
  for page in range(1, 101):
@@ -250,6 +262,8 @@ def _commits(
250
262
  listed.extend(data)
251
263
  if len(data) < 100 or len(listed) >= limit:
252
264
  break
265
+ else:
266
+ listed.truncated = True
253
267
 
254
268
  items = listed[:limit]
255
269
  keys = [f"{full}@{item['sha']}" for item in items]
@@ -380,19 +394,21 @@ def fetch_stats(
380
394
  if not quiet:
381
395
  print(f"CodeYear · github.com/{login} · {year}", file=sys.stderr)
382
396
  repos = _repos(api, login, since, include_forks, tz=target_tz)
397
+ if getattr(repos, "truncated", False):
398
+ warnings = [i18n.tr(
399
+ "公开仓库超过分页上限,统计可能不完整。"
400
+ )]
401
+ else:
402
+ warnings = []
383
403
  except RuntimeError as exc:
384
404
  raise RuntimeError(i18n.tr(
385
405
  "GitHub API 错误: {exc}", exc=exc,
386
406
  )) from exc
387
407
 
388
408
  results: list[RepoResult] = []
389
- warnings: list[str] = []
390
409
  total = 0
391
410
  for index, repo in enumerate(repos, 1):
392
411
  if total >= max_commits:
393
- warnings.append(i18n.tr(
394
- "已达到 --max-commits 上限({limit})", limit=max_commits,
395
- ))
396
412
  break
397
413
  full = repo["full_name"]
398
414
  if not quiet:
@@ -408,6 +424,10 @@ def fetch_stats(
408
424
  if not commits:
409
425
  continue
410
426
  total += len(commits)
427
+ if total >= max_commits:
428
+ warnings.append(i18n.tr(
429
+ "已达到 --max-commits 上限({limit})", limit=max_commits,
430
+ ))
411
431
  try:
412
432
  repo_total = _total_commits(api, full, login)
413
433
  except RuntimeError as exc:
@@ -427,7 +447,9 @@ def fetch_stats(
427
447
 
428
448
  if not results:
429
449
  _save_cache(cache_path, cache)
430
- raise RuntimeError(i18n.tr(
450
+ if warnings:
451
+ raise RuntimeError(warnings[-1])
452
+ raise NoPublicCommitsError(i18n.tr(
431
453
  "{login} 在 {year} 年没有找到公开提交。", login=login, year=year,
432
454
  ))
433
455
 
@@ -441,7 +463,9 @@ def fetch_stats(
441
463
  identity=(login, display_name),
442
464
  )
443
465
  if stats.commit_count == 0:
444
- raise RuntimeError(i18n.tr(
466
+ if warnings:
467
+ raise RuntimeError(warnings[-1])
468
+ raise NoPublicCommitsError(i18n.tr(
445
469
  "{login} 在 {year} 年没有找到公开提交。", login=login, year=year,
446
470
  ))
447
471
  return stats, warnings, login
@@ -466,6 +490,7 @@ def run(
466
490
  no_cache: bool = False,
467
491
  lang: str = "zh",
468
492
  tz: str | None = None,
493
+ require_complete: bool = False,
469
494
  ) -> int:
470
495
  cache_path = None
471
496
  if not no_cache:
@@ -473,27 +498,42 @@ def run(
473
498
  safe_name = re.sub(r"[^a-z0-9_.-]", "_", username.lower())
474
499
  cache_path = effective_dir / f"github-{safe_name}.json"
475
500
  try:
476
- stats, warnings, login = fetch_stats(
477
- username, year, token=token, max_commits=max_commits,
478
- include_forks=include_forks, quiet=quiet,
479
- cache_path=cache_path, tz=tz,
480
- )
481
- if (
482
- fallback_previous
483
- and not stats.commit_count
484
- and year == datetime.now().year
485
- ):
486
- previous, prev_warnings, login = fetch_stats(
501
+ try:
502
+ stats, warnings, login = fetch_stats(
503
+ username, year, token=token, max_commits=max_commits,
504
+ include_forks=include_forks, quiet=quiet,
505
+ cache_path=cache_path, tz=tz,
506
+ )
507
+ except NoPublicCommitsError:
508
+ if not fallback_previous or year != datetime.now().year:
509
+ raise
510
+ stats, warnings, login = fetch_stats(
487
511
  username, year - 1, token=token, max_commits=max_commits,
488
512
  include_forks=include_forks, quiet=quiet,
489
513
  cache_path=cache_path, tz=tz,
490
514
  )
491
- if previous.commit_count:
492
- stats, warnings = previous, prev_warnings
515
+ else:
516
+ if (fallback_previous and not stats.commit_count
517
+ and year == datetime.now().year):
518
+ previous, prev_warnings, login = fetch_stats(
519
+ username, year - 1, token=token, max_commits=max_commits,
520
+ include_forks=include_forks, quiet=quiet,
521
+ cache_path=cache_path, tz=tz,
522
+ )
523
+ if previous.commit_count:
524
+ stats, warnings = previous, prev_warnings
493
525
  except RuntimeError as exc:
494
526
  print(str(exc), file=sys.stderr)
495
527
  return 1
496
528
 
529
+ if warnings and (profile_repo or require_complete):
530
+ print(i18n.tr("公开统计可能不完整:"), file=sys.stderr)
531
+ for warning in warnings:
532
+ print(f" - {warning}", file=sys.stderr)
533
+ if push_profile or require_complete:
534
+ print(i18n.tr("已取消自动更新;请先处理上述警告。"), file=sys.stderr)
535
+ return 1
536
+
497
537
  year = stats.year
498
538
  out = Path(out_dir)
499
539
  formats = {"card"} if card_only else None
@@ -697,6 +697,12 @@ class App:
697
697
  raise RuntimeError(i18n.tr(
698
698
  "{year} 年没有找到提交。", year=year,
699
699
  ))
700
+ if github_user and profile_repo and push_profile and warnings:
701
+ raise RuntimeError(
702
+ i18n.tr("公开统计可能不完整:") + "\n"
703
+ + "\n".join(warnings) + "\n"
704
+ + i18n.tr("已取消推送 Profile;请先处理上述警告。")
705
+ )
700
706
  theme = self.theme_var.get() or str(self.cfg.get("theme", "paper"))
701
707
  written = render(
702
708
  stats, out_dir,
@@ -85,6 +85,7 @@ EN = {
85
85
  "Extra author email/name, repeatable; for old commits",
86
86
  "忽略仓库里的 .mailmap(默认自动使用)":
87
87
  "Ignore the repository's .mailmap (used automatically by default)",
88
+ "使用仓库里的 .mailmap": "Use the repository's .mailmap",
88
89
  "统计所有本地分支/tag 的提交(默认只看当前分支)":
89
90
  "Include every local branch/tag (default: current branch only)",
90
91
  "统计所有作者的提交(默认只统计你本人,按 git user.name / user.email 识别)":
@@ -272,6 +273,13 @@ EN = {
272
273
  "推送": "Push",
273
274
  "选择 Profile 仓库目录": "Choose profile repository folder",
274
275
  "正在拉取公开 GitHub 数据…": "Fetching public GitHub data…",
276
+ "公开统计有警告时退出,避免自动更新不完整的卡片":
277
+ "Exit on public-data warnings to prevent incomplete automatic updates",
278
+ "已取消自动更新;请先处理上述警告。":
279
+ "Automatic update cancelled; resolve the warnings first.",
280
+ "公开统计可能不完整:": "Public statistics may be incomplete:",
281
+ "已取消推送 Profile;请先处理上述警告。":
282
+ "Profile push cancelled; resolve the warnings first.",
275
283
  "无法连接更新服务器,请检查网络。":
276
284
  "Could not reach the update server; check your connection.",
277
285
  "当前已是最新版本(v{version})。":
@@ -336,7 +344,13 @@ def localize_parser(parser: argparse.ArgumentParser) -> None:
336
344
  parser.description = tr(parser.description)
337
345
  for action in parser._actions:
338
346
  if action.help:
339
- action.help = tr(action.help)
347
+ # Python 3.9/3.10 BooleanOptionalAction appends its default to
348
+ # the help text during construction; translate the base string.
349
+ suffix = " (default: %(default)s)"
350
+ if isinstance(action, argparse.BooleanOptionalAction) and action.help.endswith(suffix):
351
+ action.help = tr(action.help[:-len(suffix)]) + suffix
352
+ else:
353
+ action.help = tr(action.help)
340
354
  if isinstance(action, argparse._SubParsersAction):
341
355
  for choice in action._choices_actions:
342
356
  if choice.help:
@@ -11,7 +11,6 @@ import os
11
11
  import re
12
12
  import shutil
13
13
  import subprocess
14
- import time
15
14
  from pathlib import Path
16
15
 
17
16
  _NO_WINDOW = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0
@@ -29,18 +28,51 @@ def _git(repo: Path, *args: str) -> subprocess.CompletedProcess:
29
28
  )
30
29
 
31
30
 
32
- def _push(repo: Path) -> None:
33
- """Push, rebasing once if another workflow committed in the meantime."""
34
- last: subprocess.CompletedProcess | None = None
35
- for attempt in range(3):
36
- result = _git(repo, "push")
37
- if result.returncode == 0:
38
- return
39
- last = result
40
- if attempt < 2:
41
- _git(repo, "pull", "--rebase")
42
- time.sleep(2)
43
- raise RuntimeError(((last.stderr if last else "") or "git push failed").strip())
31
+ def _push_target(repo: Path) -> tuple[str, str, str]:
32
+ """Verify the remote branch exactly matches HEAD before modifying anything."""
33
+ branch = _git(repo, "symbolic-ref", "--quiet", "--short", "HEAD")
34
+ if branch.returncode != 0 or not branch.stdout.strip():
35
+ raise RuntimeError("Cannot push profile: HEAD must be on a branch with an upstream")
36
+ name = branch.stdout.strip()
37
+ remote = _git(repo, "config", "--get", f"branch.{name}.remote")
38
+ merge = _git(repo, "config", "--get-all", f"branch.{name}.merge")
39
+ remote_name = remote.stdout.strip()
40
+ refs = merge.stdout.splitlines()
41
+ if (remote.returncode != 0 or not remote_name or remote_name == "."
42
+ or merge.returncode != 0 or len(refs) != 1
43
+ or not refs[0].startswith("refs/heads/")):
44
+ raise RuntimeError("Cannot push profile: configure a single remote upstream branch")
45
+ head = _git(repo, "rev-parse", "--verify", "HEAD")
46
+ if head.returncode != 0:
47
+ raise RuntimeError("Cannot push profile: no existing HEAD commit")
48
+ # Use this exact push URL and branch explicitly, regardless of push.default
49
+ # or remote.pushDefault. Multiple push URLs cannot be checked atomically.
50
+ urls = _git(repo, "remote", "get-url", "--push", "--all", remote_name)
51
+ if urls.returncode != 0 or len(urls.stdout.splitlines()) != 1:
52
+ raise RuntimeError("Cannot push profile: configure exactly one push URL")
53
+ url = urls.stdout.strip()
54
+ remote_ref = _git(repo, "ls-remote", "--exit-code", "--refs", url, refs[0])
55
+ lines = remote_ref.stdout.splitlines()
56
+ if remote_ref.returncode != 0 or len(lines) != 1:
57
+ raise RuntimeError("Cannot push profile: cannot verify the remote upstream branch")
58
+ fields = lines[0].split()
59
+ if len(fields) != 2 or fields[1] != refs[0] or fields[0] != head.stdout.strip():
60
+ raise RuntimeError("Cannot push profile: local HEAD differs from remote upstream; "
61
+ "resolve existing unpushed or incoming commits first")
62
+ return url, refs[0], fields[0]
63
+
64
+
65
+ def _push(repo: Path, url: str, ref: str, old_head: str) -> None:
66
+ """Push only our commit, if the verified remote ref has not changed."""
67
+ commit = _git(repo, "rev-parse", "--verify", "HEAD")
68
+ parents = _git(repo, "rev-list", "--parents", "-n", "1", "HEAD")
69
+ parts = parents.stdout.split()
70
+ if (commit.returncode != 0 or parents.returncode != 0 or len(parts) != 2
71
+ or parts[0] != commit.stdout.strip() or parts[1] != old_head):
72
+ raise RuntimeError("Cannot push profile: HEAD changed since verification")
73
+ result = _git(repo, "push", url, f"{parts[0]}:{ref}")
74
+ if result.returncode != 0:
75
+ raise RuntimeError((result.stderr or "git push failed").strip())
44
76
 
45
77
 
46
78
  def _latest_version(directory: Path, year: int) -> tuple[int, Path | None]:
@@ -87,6 +119,24 @@ def update_profile(
87
119
  if not (repo / ".git").exists():
88
120
  raise FileNotFoundError(f"不是 git 仓库: {repo}")
89
121
 
122
+ if push:
123
+ # A normal git commit includes the entire index, not just paths we add.
124
+ # Refuse before modifying files so existing staged work cannot be pushed.
125
+ staged = _git(repo, "diff", "--cached", "--quiet")
126
+ if staged.returncode == 1:
127
+ raise RuntimeError("Cannot push profile with existing staged changes")
128
+ if staged.returncode != 0:
129
+ raise RuntimeError((staged.stderr or "git diff failed").strip())
130
+ dirty = _git(
131
+ repo, "status", "--porcelain", "--untracked-files=all", "--",
132
+ "README.md", ":(glob)**/codeyear-*.svg",
133
+ )
134
+ if dirty.returncode != 0:
135
+ raise RuntimeError((dirty.stderr or "git status failed").strip())
136
+ if dirty.stdout.strip():
137
+ raise RuntimeError("Cannot push profile with existing README or card changes")
138
+ push_target = _push_target(repo)
139
+
90
140
  light = Path(light_card)
91
141
  dark = Path(dark_card)
92
142
  if not light.exists() or not dark.exists():
@@ -167,14 +217,18 @@ def update_profile(
167
217
  if push:
168
218
  # -A is required so the old versioned files removed above are staged
169
219
  # as deletions too; glob magic covers cards in nested asset folders.
170
- _git(repo, "add", "-A", "README.md", ":(glob)**/codeyear-*.svg")
220
+ added = _git(repo, "add", "-A", "README.md", ":(glob)**/codeyear-*.svg")
221
+ if added.returncode != 0:
222
+ raise RuntimeError((added.stderr or "git add failed").strip())
171
223
  staged = _git(repo, "diff", "--cached", "--name-only")
224
+ if staged.returncode != 0:
225
+ raise RuntimeError((staged.stderr or "git diff failed").strip())
172
226
  if staged.stdout.strip():
173
227
  commit = _git(
174
228
  repo, "commit", "-m", f"Update CodeYear {year} card to v{version}"
175
229
  )
176
230
  if commit.returncode != 0:
177
231
  raise RuntimeError((commit.stderr or "git commit failed").strip())
178
- _push(repo)
232
+ _push(repo, *push_target)
179
233
  pushed = True
180
234
  return repo, True, pushed
@@ -187,12 +187,24 @@ def _readme_line(repo_path: Path) -> str | None:
187
187
  text = path.read_text(encoding="utf-8", errors="replace")
188
188
  except OSError:
189
189
  continue
190
+ fence = None
190
191
  for raw in text.splitlines():
191
192
  line = raw.strip()
192
- if not line or line.startswith("<") or line.startswith("!"):
193
+ marker = re.match(r"^(`{3,}|~{3,})", line)
194
+ if marker:
195
+ token = marker.group(1)
196
+ if fence is None:
197
+ fence = token
198
+ elif token[0] == fence[0] and len(token) >= len(fence):
199
+ fence = None
193
200
  continue
194
- line = re.sub(r"[\\#>*`_\[\]()]","", line).strip()
195
- line = re.sub(r"\s+", " ", line)
201
+ if fence or not line or line.startswith("<"):
202
+ continue
203
+ line = re.sub(r"^\s*(?:#{1,6}\s+|>\s*)+", "", line).strip()
204
+ line = re.sub(r"\[!\[[^]]*\]\([^)]*\)\]\([^)]*\)", "", line)
205
+ line = re.sub(r"!\[[^]]*\]\([^)]*\)", "", line)
206
+ line = re.sub(r"\[([^]]+)\]\([^)]*\)", r"\1", line)
207
+ line = re.sub(r"\s+", " ", line).strip()
196
208
  if len(line) >= 6:
197
209
  return line[:110]
198
210
  return None