codeyear 0.2.14__py3-none-any.whl
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.
- codeyear/__init__.py +3 -0
- codeyear/__main__.py +6 -0
- codeyear/card.py +720 -0
- codeyear/cli.py +450 -0
- codeyear/config.py +114 -0
- codeyear/github_public.py +590 -0
- codeyear/gui.py +960 -0
- codeyear/html_report.py +1663 -0
- codeyear/i18n.py +345 -0
- codeyear/keywords.py +98 -0
- codeyear/languages.py +132 -0
- codeyear/personas.py +171 -0
- codeyear/poster.py +992 -0
- codeyear/profile.py +180 -0
- codeyear/report_theme.py +890 -0
- codeyear/runner.py +304 -0
- codeyear/scanner.py +491 -0
- codeyear/server.py +293 -0
- codeyear/stats.py +736 -0
- codeyear/updater.py +238 -0
- codeyear/wizard.py +221 -0
- codeyear-0.2.14.dist-info/METADATA +559 -0
- codeyear-0.2.14.dist-info/RECORD +27 -0
- codeyear-0.2.14.dist-info/WHEEL +5 -0
- codeyear-0.2.14.dist-info/entry_points.txt +5 -0
- codeyear-0.2.14.dist-info/licenses/LICENSE +21 -0
- codeyear-0.2.14.dist-info/top_level.txt +1 -0
codeyear/cli.py
ADDED
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
"""Command line entry point."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
import webbrowser
|
|
11
|
+
from datetime import date
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from . import __version__, i18n
|
|
15
|
+
from .card import THEMES
|
|
16
|
+
from .card import render as render_card
|
|
17
|
+
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
|
|
24
|
+
from .updater import check_update, cleanup_old_executable, perform_update
|
|
25
|
+
|
|
26
|
+
_NO_WINDOW = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
30
|
+
cfg = load_config()
|
|
31
|
+
parser = argparse.ArgumentParser(
|
|
32
|
+
prog="codeyear",
|
|
33
|
+
description="扫描本地 git 仓库,生成一份年度代码报告(HTML + PNG 海报)。",
|
|
34
|
+
)
|
|
35
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
36
|
+
parser.add_argument("--lang", choices=["zh", "en"], default=None,
|
|
37
|
+
help="界面与 Profile 卡片语言 / UI and profile-card language")
|
|
38
|
+
|
|
39
|
+
sub = parser.add_subparsers(dest="command", required=False)
|
|
40
|
+
sub.add_parser("gui", help="图形界面:点选目录、看进度、选输出位置")
|
|
41
|
+
sub.add_parser("tui", help="终端交互向导:选目录、看进度、选输出位置")
|
|
42
|
+
updater = sub.add_parser("update", help="检查或安装最新版本")
|
|
43
|
+
updater.add_argument("--check", action="store_true",
|
|
44
|
+
help="只检查是否有新版本,不安装")
|
|
45
|
+
github = sub.add_parser("github", help="从公开 GitHub 账号生成(联网,仅公开仓库)")
|
|
46
|
+
github.add_argument("username", help="GitHub 用户名")
|
|
47
|
+
github.add_argument("--year", type=int, default=cfg.get("year", date.today().year),
|
|
48
|
+
help="统计年份")
|
|
49
|
+
github.add_argument("--out", default=cfg.get("out", "codeyear-output"),
|
|
50
|
+
help="输出目录")
|
|
51
|
+
github.add_argument("--token", default=None, help="GitHub token;也可用 GITHUB_TOKEN")
|
|
52
|
+
github.add_argument("--max-commits", type=int, default=cfg.get("max_commits", 200),
|
|
53
|
+
help="最多拉取多少条提交(无 token 时自动限制为 30)")
|
|
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="生成后打开报告")
|
|
57
|
+
github.add_argument("--quiet", action="store_true", help="不打印扫描进度")
|
|
58
|
+
github.add_argument("--theme", choices=sorted(THEMES),
|
|
59
|
+
default=cfg.get("theme", "paper"),
|
|
60
|
+
help="卡片主题:paper / mono / forest / ocean")
|
|
61
|
+
github.add_argument("--card-only", action="store_true",
|
|
62
|
+
help="只生成主页卡片和 embed 片段,不生成完整报告")
|
|
63
|
+
github.add_argument("--profile-repo", default=None,
|
|
64
|
+
help="本地 GitHub Profile 仓库路径;自动更新 README 里的卡片")
|
|
65
|
+
github.add_argument("--push-profile", action="store_true",
|
|
66
|
+
help="更新后提交并推送 Profile 仓库(联网);需同时指定 --profile-repo")
|
|
67
|
+
github.add_argument("--cache-dir", default=None,
|
|
68
|
+
help="缓存公开 commit 详情到该目录,重复运行更快")
|
|
69
|
+
github.add_argument("--no-cache", action="store_true",
|
|
70
|
+
help="禁用公开 commit 详情本地缓存")
|
|
71
|
+
github.add_argument("--fallback-previous", action="store_true",
|
|
72
|
+
help="当年没有提交时回退到上一年,适合跨年自动更新")
|
|
73
|
+
github.add_argument("--tz", default=cfg.get("tz"),
|
|
74
|
+
help="时区(如 UTC+8 或 Asia/Shanghai;默认本机时区)")
|
|
75
|
+
server = sub.add_parser("serve", help="启动公开 GitHub 卡片 HTTP 服务")
|
|
76
|
+
server.add_argument("--host", default="127.0.0.1", help="监听地址,默认 127.0.0.1")
|
|
77
|
+
server.add_argument("--port", type=int, default=8000, help="监听端口,默认 8000")
|
|
78
|
+
server.add_argument("--token", default=None, help="GitHub token;也可用 GITHUB_TOKEN")
|
|
79
|
+
server.add_argument("--max-commits", type=int, default=200,
|
|
80
|
+
help="每张卡片最多拉取多少条提交")
|
|
81
|
+
scan = sub.add_parser("scan", help="扫描一个文件夹下的所有 git 仓库")
|
|
82
|
+
scan.add_argument("path", nargs="*", default=(cfg.get("roots") or ["."]),
|
|
83
|
+
help="要扫描的文件夹(可以多个,默认当前目录)")
|
|
84
|
+
scan.add_argument("--year", type=int, default=cfg.get("year", date.today().year),
|
|
85
|
+
help="统计年份,默认今年")
|
|
86
|
+
scan.add_argument("--rolling", action="store_true",
|
|
87
|
+
default=cfg.get("rolling", False),
|
|
88
|
+
help="统计过去 365 天(滚动年度),而非自然年")
|
|
89
|
+
scan.add_argument("--exclude", action="append", default=cfg.get("exclude", []),
|
|
90
|
+
help="排除指定仓库名或通配符(可重复或逗号分隔)")
|
|
91
|
+
scan.add_argument("--out", default=cfg.get("out", "codeyear-output"),
|
|
92
|
+
help="输出目录,默认 ./codeyear-output")
|
|
93
|
+
scan.add_argument("--author", default=cfg.get("author"),
|
|
94
|
+
help="只统计匹配的 git author(--author 参数)")
|
|
95
|
+
scan.add_argument("--compare", action="store_true",
|
|
96
|
+
default=cfg.get("compare", False),
|
|
97
|
+
help="同时扫描去年,在报告里生成同比数据")
|
|
98
|
+
scan.add_argument("--fallback-previous", action="store_true",
|
|
99
|
+
default=cfg.get("fallback_previous", False),
|
|
100
|
+
help="当年没有提交时回退到上一年,适合跨年自动更新")
|
|
101
|
+
scan.add_argument("--alias", action="append", default=cfg.get("aliases", []),
|
|
102
|
+
help="额外作者邮箱或名字,可重复;用于旧提交")
|
|
103
|
+
scan.add_argument("--no-mailmap", action="store_true",
|
|
104
|
+
default=cfg.get("no_mailmap", False),
|
|
105
|
+
help="忽略仓库里的 .mailmap(默认自动使用)")
|
|
106
|
+
scan.add_argument("--all-branches", action="store_true",
|
|
107
|
+
default=cfg.get("all_branches", False),
|
|
108
|
+
help="统计所有本地分支/tag 的提交(默认只看当前分支)")
|
|
109
|
+
scan.add_argument("--all-authors", action="store_true",
|
|
110
|
+
default=cfg.get("all_authors", False),
|
|
111
|
+
help="统计所有作者的提交(默认只统计你本人,按 git user.name / user.email 识别)")
|
|
112
|
+
scan.add_argument("--max-depth", type=int, default=cfg.get("max_depth", 6),
|
|
113
|
+
help="向下查找仓库的最大文件夹层数,默认 6")
|
|
114
|
+
scan.add_argument("--timeout", type=int, default=cfg.get("timeout", 300),
|
|
115
|
+
help="单个仓库的扫描超时秒数")
|
|
116
|
+
scan.add_argument("--jobs", type=int, default=cfg.get("jobs", 1),
|
|
117
|
+
help="并行扫描的仓库数,默认 1")
|
|
118
|
+
scan.add_argument("--theme", choices=sorted(THEMES),
|
|
119
|
+
default=cfg.get("theme", "paper"),
|
|
120
|
+
help="卡片主题:paper / mono / forest / ocean")
|
|
121
|
+
scan.add_argument("--no-png", action="store_true", help="不生成 PNG 海报")
|
|
122
|
+
scan.add_argument("--no-long", action="store_true", help="不生成完整版长图")
|
|
123
|
+
scan.add_argument("--no-card", action="store_true", help="不生成 GitHub 主页卡片")
|
|
124
|
+
scan.add_argument("--no-html", action="store_true", help="不生成 HTML 报告")
|
|
125
|
+
scan.add_argument("--profile-repo", default=None,
|
|
126
|
+
help="本地 GitHub Profile 仓库路径;只写入本地,不联网")
|
|
127
|
+
scan.add_argument("--push-profile", action="store_true",
|
|
128
|
+
help="更新后提交并推送 Profile 仓库(联网);需同时指定 --profile-repo")
|
|
129
|
+
scan.add_argument("--open", action="store_true", default=cfg.get("open", False),
|
|
130
|
+
help="生成后自动打开报告")
|
|
131
|
+
scan.add_argument("--quiet", action="store_true", help="不打印扫描进度")
|
|
132
|
+
i18n.localize_parser(parser)
|
|
133
|
+
return parser
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _open_path(path: Path) -> None:
|
|
137
|
+
try:
|
|
138
|
+
if path.suffix.lower() in {".html", ".htm"}:
|
|
139
|
+
webbrowser.open(path.resolve().as_uri())
|
|
140
|
+
elif hasattr(os, "startfile"):
|
|
141
|
+
os.startfile(str(path)) # type: ignore[attr-defined]
|
|
142
|
+
else:
|
|
143
|
+
webbrowser.open(path.resolve().as_uri())
|
|
144
|
+
except Exception as exc: # pragma: no cover - platform dependent
|
|
145
|
+
print(i18n.tr("无法自动打开文件: {exc}", exc=exc), file=sys.stderr)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _detect_identity() -> tuple[str, str] | None:
|
|
149
|
+
"""The runner's git identity, used to keep only their own commits."""
|
|
150
|
+
|
|
151
|
+
def config(key: str) -> str:
|
|
152
|
+
try:
|
|
153
|
+
proc = subprocess.run(
|
|
154
|
+
["git", "config", "--global", key],
|
|
155
|
+
capture_output=True, text=True, encoding="utf-8",
|
|
156
|
+
errors="replace", timeout=10, creationflags=_NO_WINDOW,
|
|
157
|
+
)
|
|
158
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
159
|
+
return ""
|
|
160
|
+
return (proc.stdout or "").strip()
|
|
161
|
+
|
|
162
|
+
email, name = config("user.email"), config("user.name")
|
|
163
|
+
if email or name:
|
|
164
|
+
return (email, name)
|
|
165
|
+
return None
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def main(argv: list[str] | None = None) -> int:
|
|
169
|
+
cleanup_old_executable()
|
|
170
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
171
|
+
i18n.set_lang(i18n.detect(argv))
|
|
172
|
+
parser = _build_parser()
|
|
173
|
+
args = parser.parse_args(argv)
|
|
174
|
+
|
|
175
|
+
if args.command == "update":
|
|
176
|
+
info = check_update(timeout=6.0)
|
|
177
|
+
if not info:
|
|
178
|
+
print(i18n.tr("无法连接更新服务器,请检查网络。"), file=sys.stderr)
|
|
179
|
+
return 1
|
|
180
|
+
if not info["has_update"]:
|
|
181
|
+
print(i18n.tr(
|
|
182
|
+
"当前已是最新版本(v{version})。", version=info["current"]
|
|
183
|
+
))
|
|
184
|
+
return 0
|
|
185
|
+
print(i18n.tr(
|
|
186
|
+
"发现新版本 v{latest}(当前 v{current}): {url}",
|
|
187
|
+
latest=info["latest"], current=info["current"], url=info["url"],
|
|
188
|
+
))
|
|
189
|
+
if args.check:
|
|
190
|
+
return 0
|
|
191
|
+
ok, msg = perform_update(info)
|
|
192
|
+
stream = sys.stdout if ok else sys.stderr
|
|
193
|
+
print(msg, file=stream)
|
|
194
|
+
return 0 if ok else 1
|
|
195
|
+
|
|
196
|
+
if args.command in {None, "gui"}:
|
|
197
|
+
try:
|
|
198
|
+
from .gui import run as run_gui
|
|
199
|
+
except ImportError as exc:
|
|
200
|
+
print(i18n.tr("无法加载图形界面(Tkinter): {exc}", exc=exc),
|
|
201
|
+
file=sys.stderr)
|
|
202
|
+
print(i18n.tr("请改用 codeyear tui 或 codeyear scan。"),
|
|
203
|
+
file=sys.stderr)
|
|
204
|
+
return 1
|
|
205
|
+
return run_gui()
|
|
206
|
+
if args.command == "tui":
|
|
207
|
+
from .wizard import run as run_wizard
|
|
208
|
+
|
|
209
|
+
return run_wizard()
|
|
210
|
+
if args.command == "github":
|
|
211
|
+
from .github_public import run as run_github
|
|
212
|
+
|
|
213
|
+
if args.push_profile and not args.profile_repo:
|
|
214
|
+
parser.error(i18n.tr("--push-profile 需要同时指定 --profile-repo"))
|
|
215
|
+
return run_github(
|
|
216
|
+
args.username, args.year, Path(args.out),
|
|
217
|
+
token=args.token, max_commits=args.max_commits,
|
|
218
|
+
include_forks=args.include_forks,
|
|
219
|
+
open_report=args.open, quiet=args.quiet,
|
|
220
|
+
theme=args.theme, card_only=args.card_only,
|
|
221
|
+
profile_repo=args.profile_repo,
|
|
222
|
+
push_profile=args.push_profile,
|
|
223
|
+
fallback_previous=args.fallback_previous,
|
|
224
|
+
cache_dir=args.cache_dir,
|
|
225
|
+
no_cache=args.no_cache,
|
|
226
|
+
lang=i18n.get_lang(),
|
|
227
|
+
tz=args.tz,
|
|
228
|
+
)
|
|
229
|
+
if args.command == "serve":
|
|
230
|
+
from .server import serve
|
|
231
|
+
|
|
232
|
+
return serve(
|
|
233
|
+
args.host, args.port,
|
|
234
|
+
token=args.token, max_commits=args.max_commits,
|
|
235
|
+
)
|
|
236
|
+
if args.command != "scan":
|
|
237
|
+
parser.print_help()
|
|
238
|
+
return 0
|
|
239
|
+
|
|
240
|
+
if args.push_profile and not args.profile_repo:
|
|
241
|
+
parser.error(i18n.tr("--push-profile 需要同时指定 --profile-repo"))
|
|
242
|
+
|
|
243
|
+
roots = [Path(path).expanduser() for path in (args.path or ["."])]
|
|
244
|
+
try:
|
|
245
|
+
repos = discover(roots, args.max_depth, exclude=args.exclude)
|
|
246
|
+
except (FileNotFoundError, NotADirectoryError) as exc:
|
|
247
|
+
print(i18n.tr("错误: {exc}", exc=exc), file=sys.stderr)
|
|
248
|
+
return 2
|
|
249
|
+
|
|
250
|
+
if not repos:
|
|
251
|
+
where = " + ".join(str(root) for root in roots)
|
|
252
|
+
print(i18n.tr("在 {where} 下没有找到 git 仓库。", where=where),
|
|
253
|
+
file=sys.stderr)
|
|
254
|
+
return 2
|
|
255
|
+
|
|
256
|
+
if not args.quiet:
|
|
257
|
+
where = " + ".join(str(root) for root in roots)
|
|
258
|
+
print(i18n.tr(
|
|
259
|
+
"CodeYear {year} · 在 {where} 下找到 {count} 个仓库",
|
|
260
|
+
year=args.year, where=where, count=len(repos),
|
|
261
|
+
), file=sys.stderr)
|
|
262
|
+
|
|
263
|
+
identity = None
|
|
264
|
+
if not args.all_authors and not args.author:
|
|
265
|
+
identity = _detect_identity()
|
|
266
|
+
if identity is None and not args.quiet:
|
|
267
|
+
print(i18n.tr(
|
|
268
|
+
" ! 未检测到 git user.name / user.email,将统计所有作者的提交"
|
|
269
|
+
), file=sys.stderr)
|
|
270
|
+
|
|
271
|
+
def progress(done: int, total: int, name: str) -> None:
|
|
272
|
+
if not args.quiet and done:
|
|
273
|
+
print(f" [{done}/{total}] {name}", file=sys.stderr)
|
|
274
|
+
|
|
275
|
+
stats, warnings = scan(
|
|
276
|
+
repos, roots, args.year, identity,
|
|
277
|
+
aliases=args.alias, author=args.author, timeout=args.timeout,
|
|
278
|
+
jobs=max(1, args.jobs), progress=progress,
|
|
279
|
+
compare=args.compare, use_mailmap=not args.no_mailmap,
|
|
280
|
+
all_branches=args.all_branches,
|
|
281
|
+
rolling=args.rolling,
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
if (
|
|
285
|
+
args.fallback_previous
|
|
286
|
+
and stats.commit_count == 0
|
|
287
|
+
and args.year == date.today().year
|
|
288
|
+
):
|
|
289
|
+
previous, prev_warnings = scan(
|
|
290
|
+
repos, roots, args.year - 1, identity,
|
|
291
|
+
aliases=args.alias, author=args.author, timeout=args.timeout,
|
|
292
|
+
jobs=max(1, args.jobs), progress=progress,
|
|
293
|
+
compare=args.compare, use_mailmap=not args.no_mailmap,
|
|
294
|
+
all_branches=args.all_branches,
|
|
295
|
+
)
|
|
296
|
+
if previous.commit_count:
|
|
297
|
+
stats, warnings = previous, prev_warnings
|
|
298
|
+
args.year = previous.year
|
|
299
|
+
|
|
300
|
+
if stats.commit_count == 0:
|
|
301
|
+
print(
|
|
302
|
+
i18n.tr(
|
|
303
|
+
"{year} 年没有找到提交。可以换 --year,或检查 --author 过滤条件。",
|
|
304
|
+
year=args.year,
|
|
305
|
+
),
|
|
306
|
+
file=sys.stderr,
|
|
307
|
+
)
|
|
308
|
+
return 3
|
|
309
|
+
|
|
310
|
+
out_dir = Path(args.out)
|
|
311
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
312
|
+
base = out_dir / f"codeyear-{args.year}"
|
|
313
|
+
|
|
314
|
+
written: list[tuple[str, Path]] = []
|
|
315
|
+
|
|
316
|
+
json_path = base.with_suffix(".json")
|
|
317
|
+
json_path.write_text(
|
|
318
|
+
json.dumps(stats.as_dict(), ensure_ascii=False, indent=2),
|
|
319
|
+
encoding="utf-8",
|
|
320
|
+
)
|
|
321
|
+
written.append(("JSON", json_path))
|
|
322
|
+
|
|
323
|
+
if not args.no_html:
|
|
324
|
+
html_path = render_html(stats, base.with_suffix(".html"))
|
|
325
|
+
written.append(("HTML", html_path))
|
|
326
|
+
en_path = render_html_en(stats, out_dir / f"codeyear-{args.year}-en.html")
|
|
327
|
+
written.append(("HTML-EN", en_path))
|
|
328
|
+
|
|
329
|
+
if not args.no_png:
|
|
330
|
+
png_path = render_poster(stats, base.with_suffix(".png"))
|
|
331
|
+
written.append(("PNG", png_path))
|
|
332
|
+
if i18n.get_lang() == "en":
|
|
333
|
+
png_en = render_poster(
|
|
334
|
+
stats, out_dir / f"codeyear-{args.year}-en.png", lang="en")
|
|
335
|
+
written.append(("PNG-EN", png_en))
|
|
336
|
+
if not args.no_long:
|
|
337
|
+
long_path = render_long(stats, out_dir / f"codeyear-{args.year}-long.png")
|
|
338
|
+
written.append(("LONG", long_path))
|
|
339
|
+
if i18n.get_lang() == "en":
|
|
340
|
+
long_en = render_long(
|
|
341
|
+
stats, out_dir / f"codeyear-{args.year}-en-long.png",
|
|
342
|
+
lang="en")
|
|
343
|
+
written.append(("LONG-EN", long_en))
|
|
344
|
+
|
|
345
|
+
card_paths = []
|
|
346
|
+
en_cards = []
|
|
347
|
+
card_theme = getattr(args, "theme", "paper") or "paper"
|
|
348
|
+
if not args.no_card:
|
|
349
|
+
card_paths = render_card(
|
|
350
|
+
stats, out_dir / f"codeyear-{args.year}-card.svg",
|
|
351
|
+
theme=card_theme,
|
|
352
|
+
)
|
|
353
|
+
written.append(("CARD", card_paths[0]))
|
|
354
|
+
written.append(("CARD-DARK", card_paths[1]))
|
|
355
|
+
en_cards = render_card(
|
|
356
|
+
stats, out_dir / f"codeyear-{args.year}-card-en.svg",
|
|
357
|
+
theme=card_theme, lang="en",
|
|
358
|
+
)
|
|
359
|
+
written.append(("CARD-EN", en_cards[0]))
|
|
360
|
+
written.append(("CARD-DARK-EN", en_cards[1]))
|
|
361
|
+
|
|
362
|
+
exit_code = 0
|
|
363
|
+
if args.profile_repo:
|
|
364
|
+
if not card_paths:
|
|
365
|
+
print(i18n.tr(
|
|
366
|
+
" ! 指定了 --profile-repo,但 --no-card 关闭了卡片生成"
|
|
367
|
+
), file=sys.stderr)
|
|
368
|
+
exit_code = 1
|
|
369
|
+
else:
|
|
370
|
+
from .profile import update_profile
|
|
371
|
+
|
|
372
|
+
profile_cards = en_cards if i18n.get_lang() == "en" else card_paths
|
|
373
|
+
try:
|
|
374
|
+
profile_repo, changed, pushed = update_profile(
|
|
375
|
+
args.profile_repo, args.year,
|
|
376
|
+
profile_cards[0], profile_cards[1],
|
|
377
|
+
push=args.push_profile,
|
|
378
|
+
)
|
|
379
|
+
written.append(("PROFILE", profile_repo))
|
|
380
|
+
if changed:
|
|
381
|
+
state = "已提交并推送" if pushed else "仅写入本地"
|
|
382
|
+
print("\n" + i18n.tr(
|
|
383
|
+
"Profile {state} · {repo}",
|
|
384
|
+
state=i18n.tr(state), repo=profile_repo,
|
|
385
|
+
))
|
|
386
|
+
else:
|
|
387
|
+
print("\n" + i18n.tr(
|
|
388
|
+
"Profile 卡片已是最新 · {repo}", repo=profile_repo,
|
|
389
|
+
))
|
|
390
|
+
except Exception as exc: # pragma: no cover - user environment
|
|
391
|
+
print(i18n.tr(
|
|
392
|
+
" ! 更新 Profile 失败: {exc}", exc=exc
|
|
393
|
+
), file=sys.stderr)
|
|
394
|
+
exit_code = 1
|
|
395
|
+
|
|
396
|
+
# Console summary
|
|
397
|
+
active_pct = stats.active_days / (366 if _is_leap(args.year) else 365)
|
|
398
|
+
print()
|
|
399
|
+
print(i18n.tr(
|
|
400
|
+
"CodeYear {year} · {title}",
|
|
401
|
+
year=args.year, title=stats.persona.title,
|
|
402
|
+
))
|
|
403
|
+
print("-" * 46)
|
|
404
|
+
print(f"{i18n.tr('仓库'):<10}{stats.repo_count}")
|
|
405
|
+
if stats.identity_label:
|
|
406
|
+
print(f"{i18n.tr('身份'):<10}{stats.identity_label}")
|
|
407
|
+
if stats.filtered_commits:
|
|
408
|
+
print(f"{i18n.tr('已过滤'):<10}{stats.filtered_commits} "
|
|
409
|
+
f"{i18n.tr('次他人提交')}")
|
|
410
|
+
elif args.author:
|
|
411
|
+
print(f"{i18n.tr('身份'):<10}--author={args.author}")
|
|
412
|
+
else:
|
|
413
|
+
print(f"{i18n.tr('身份'):<10}{i18n.tr('全部作者')}")
|
|
414
|
+
print(f"{i18n.tr('提交'):<10}{fmt_int(stats.commit_count)}")
|
|
415
|
+
print(f"{i18n.tr('代码行'):<10}{fmt_int(stats.lines_changed)} "
|
|
416
|
+
f"(+{fmt_int(stats.insertions)} / -{fmt_int(stats.deletions)})")
|
|
417
|
+
print(i18n.tr(
|
|
418
|
+
"活跃 {days} 天({pct})· 最长连续 {streak} 天",
|
|
419
|
+
days=stats.active_days, pct=f"{active_pct:.0%}",
|
|
420
|
+
streak=stats.longest_streak,
|
|
421
|
+
))
|
|
422
|
+
print(i18n.tr("语言 {count} 种", count=stats.language_count))
|
|
423
|
+
if stats.busiest_day:
|
|
424
|
+
print(i18n.tr(
|
|
425
|
+
"最忙一天 {day} · {count} 次提交",
|
|
426
|
+
day=stats.busiest_day[0], count=stats.busiest_count,
|
|
427
|
+
))
|
|
428
|
+
print("-" * 46)
|
|
429
|
+
for label, path in written:
|
|
430
|
+
print(f"{label:<9} {path.resolve()}")
|
|
431
|
+
|
|
432
|
+
if warnings:
|
|
433
|
+
print()
|
|
434
|
+
print(i18n.tr("警告:"))
|
|
435
|
+
for warning in warnings:
|
|
436
|
+
print(f" - {warning}")
|
|
437
|
+
|
|
438
|
+
if args.open and written:
|
|
439
|
+
target = report_path(written, lang=i18n.get_lang()) or written[0][1]
|
|
440
|
+
_open_path(target)
|
|
441
|
+
|
|
442
|
+
return exit_code
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def _is_leap(year: int) -> bool:
|
|
446
|
+
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
if __name__ == "__main__": # pragma: no cover
|
|
450
|
+
raise SystemExit(main())
|
codeyear/config.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Optional user-level defaults for the CLI.
|
|
2
|
+
|
|
3
|
+
Reads ``~/.codeyear.json`` (or ``$CODEYEAR_CONFIG``). Invalid keys/types are
|
|
4
|
+
ignored so a broken config never prevents a scan. Explicit CLI flags win.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
ENV_PATH = "CODEYEAR_CONFIG"
|
|
14
|
+
|
|
15
|
+
# key -> expected type
|
|
16
|
+
SCHEMA = {
|
|
17
|
+
"roots": list,
|
|
18
|
+
"year": int,
|
|
19
|
+
"out": str,
|
|
20
|
+
"author": str,
|
|
21
|
+
"all_authors": bool,
|
|
22
|
+
"aliases": list,
|
|
23
|
+
"compare": bool,
|
|
24
|
+
"fallback_previous": bool,
|
|
25
|
+
"all_branches": bool,
|
|
26
|
+
"no_mailmap": bool,
|
|
27
|
+
"jobs": int,
|
|
28
|
+
"max_depth": int,
|
|
29
|
+
"timeout": int,
|
|
30
|
+
"theme": str,
|
|
31
|
+
"max_commits": int,
|
|
32
|
+
"open": bool,
|
|
33
|
+
"tz": str,
|
|
34
|
+
"exclude": list,
|
|
35
|
+
"rolling": bool,
|
|
36
|
+
"github_user": str,
|
|
37
|
+
"profile_repo": str,
|
|
38
|
+
"push_profile": bool,
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def path() -> Path:
|
|
43
|
+
override = os.environ.get(ENV_PATH)
|
|
44
|
+
if override:
|
|
45
|
+
return Path(override).expanduser()
|
|
46
|
+
return Path.home() / ".codeyear.json"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def load() -> dict:
|
|
50
|
+
file = path()
|
|
51
|
+
if not file.exists():
|
|
52
|
+
return {}
|
|
53
|
+
try:
|
|
54
|
+
raw = json.loads(file.read_text(encoding="utf-8"))
|
|
55
|
+
except (OSError, ValueError):
|
|
56
|
+
return {}
|
|
57
|
+
if not isinstance(raw, dict):
|
|
58
|
+
return {}
|
|
59
|
+
|
|
60
|
+
clean: dict = {}
|
|
61
|
+
for key, expected in SCHEMA.items():
|
|
62
|
+
if key not in raw:
|
|
63
|
+
continue
|
|
64
|
+
value = raw[key]
|
|
65
|
+
if expected is list:
|
|
66
|
+
if isinstance(value, list) and all(isinstance(item, str) for item in value):
|
|
67
|
+
clean[key] = value
|
|
68
|
+
elif expected is bool:
|
|
69
|
+
if isinstance(value, bool):
|
|
70
|
+
clean[key] = value
|
|
71
|
+
elif expected is int:
|
|
72
|
+
if isinstance(value, int) and not isinstance(value, bool):
|
|
73
|
+
clean[key] = value
|
|
74
|
+
elif expected is str and isinstance(value, str):
|
|
75
|
+
if key == "theme" and value not in {
|
|
76
|
+
"paper", "mono", "forest", "ocean",
|
|
77
|
+
}:
|
|
78
|
+
continue
|
|
79
|
+
clean[key] = value
|
|
80
|
+
if clean.get("max_commits", 1) <= 0:
|
|
81
|
+
clean.pop("max_commits", None)
|
|
82
|
+
if clean.get("jobs", 1) <= 0:
|
|
83
|
+
clean.pop("jobs", None)
|
|
84
|
+
return clean
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def save(values: dict) -> Path:
|
|
88
|
+
"""Validate and persist user defaults to ``~/.codeyear.json``."""
|
|
89
|
+
merged = load()
|
|
90
|
+
merged.update(values)
|
|
91
|
+
clean: dict = {}
|
|
92
|
+
for key, expected in SCHEMA.items():
|
|
93
|
+
if key not in merged:
|
|
94
|
+
continue
|
|
95
|
+
value = merged[key]
|
|
96
|
+
if expected is list:
|
|
97
|
+
if isinstance(value, list) and all(isinstance(item, str) for item in value):
|
|
98
|
+
clean[key] = value
|
|
99
|
+
elif expected is bool:
|
|
100
|
+
if isinstance(value, bool):
|
|
101
|
+
clean[key] = value
|
|
102
|
+
elif expected is int:
|
|
103
|
+
if isinstance(value, int) and not isinstance(value, bool):
|
|
104
|
+
clean[key] = value
|
|
105
|
+
elif expected is str and isinstance(value, str):
|
|
106
|
+
if key == "theme" and value not in {"paper", "mono", "forest", "ocean"}:
|
|
107
|
+
continue
|
|
108
|
+
clean[key] = value
|
|
109
|
+
target = path()
|
|
110
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
111
|
+
target.write_text(
|
|
112
|
+
json.dumps(clean, ensure_ascii=False, indent=2), encoding="utf-8"
|
|
113
|
+
)
|
|
114
|
+
return target
|