codeyear 0.2.14__py3-none-any.whl → 0.2.16__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 CHANGED
@@ -1,3 +1,3 @@
1
1
  """CodeYear · 本地优先的年度代码报告生成器."""
2
2
 
3
- __version__ = "0.2.14"
3
+ __version__ = "0.2.16"
codeyear/card.py CHANGED
@@ -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 (
@@ -14,6 +14,8 @@ from .stats import (
14
14
  fmt_signed_pair,
15
15
  language_breakdown,
16
16
  parse_daily,
17
+ window_days,
18
+ window_months,
17
19
  )
18
20
 
19
21
  W, H = 640, 1254
@@ -247,9 +249,10 @@ MONTHS = [
247
249
 
248
250
 
249
251
  def build_svg(stats: ReportStats, *, dark: bool = False,
250
- theme: str = "paper", lang: str = "zh") -> str:
252
+ theme: str = "paper", lang: str = "zh",
253
+ palette_override: dict | None = None) -> str:
251
254
  light, dark_theme = THEMES.get(theme, THEMES["paper"])
252
- c = dark_theme if dark else light
255
+ c = palette_override if palette_override is not None else (dark_theme if dark else light)
253
256
  en = lang == "en"
254
257
 
255
258
  def t(zh: str, english: str) -> str:
@@ -300,7 +303,7 @@ def build_svg(stats: ReportStats, *, dark: bool = False,
300
303
  header.append(_rule(142, c["line"]))
301
304
 
302
305
  # ---- six summary tiles (3 x 2) ------------------------------------
303
- active_pct = stats.active_days / (366 if _is_leap(stats.year) else 365)
306
+ active_pct = stats.active_days / window_days(stats)
304
307
  tiles = [
305
308
  (t("COMMITS / 提交", "COMMITS"), fmt_int(stats.commit_count),
306
309
  t("年度提交", "commits this year")),
@@ -343,19 +346,18 @@ def build_svg(stats: ReportStats, *, dark: bool = False,
343
346
 
344
347
  # ---- contribution calendar ---------------------------------------
345
348
  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())
349
+ start_w, end_w = date_window(stats)
350
+ grid_start = start_w - timedelta(days=start_w.weekday())
351
+ grid_end = end_w + timedelta(days=6 - end_w.weekday())
350
352
  grid_cols = (grid_end - grid_start).days // 7 + 1
351
353
  grid_w = grid_cols * (cell + gap_h) - gap_h
352
354
  grid_x = (W - grid_w) / 2
353
355
 
354
356
  month_ticks = []
355
- for month in range(1, 13):
356
- col = (date(stats.year, month, 1) - grid_start).days // 7
357
+ for m_date, m_label in window_months(stats):
358
+ col = (m_date - grid_start).days // 7
357
359
  mx = grid_x + col * (cell + gap_h)
358
- month_ticks.append(_text(mx, 588, f"{month:02d}", 9.5, c["muted"]))
360
+ month_ticks.append(_text(mx, 588, m_label, 9.5, c["muted"]))
359
361
 
360
362
  charts = [
361
363
  _text(M, 350, "MONTHLY RHYTHM", 10, c["muted"], spacing=1),
@@ -702,10 +704,6 @@ def build_svg(stats: ReportStats, *, dark: bool = False,
702
704
  """
703
705
 
704
706
 
705
- def _is_leap(year: int) -> bool:
706
- return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
707
-
708
-
709
707
  def render(stats: ReportStats, out_path: str | Path, *,
710
708
  theme: str = "paper", lang: str = "zh") -> list[Path]:
711
709
  path = Path(out_path)
codeyear/cli.py CHANGED
@@ -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,25 @@ 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 detect_identity, discover, render, report_path, scan
16
+ from .stats import fmt_int, window_days
24
17
  from .updater import check_update, cleanup_old_executable, perform_update
25
18
 
26
- _NO_WINDOW = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0
19
+
20
+ class _CopyAppendAction(argparse.Action):
21
+ """Append action that never mutates a config-provided default list."""
22
+
23
+ def __call__(self, parser, namespace, values, option_string=None):
24
+ items = list(getattr(namespace, self.dest, None) or [])
25
+ if getattr(namespace, f"_cy_copied_{self.dest}", False) is False:
26
+ items = [] if values == "" else list(items)
27
+ setattr(namespace, f"_cy_copied_{self.dest}", True)
28
+ if values == "":
29
+ items = []
30
+ else:
31
+ items.append(values)
32
+ setattr(namespace, self.dest, items)
27
33
 
28
34
 
29
35
  def _build_parser() -> argparse.ArgumentParser:
@@ -52,12 +58,14 @@ def _build_parser() -> argparse.ArgumentParser:
52
58
  github.add_argument("--max-commits", type=int, default=cfg.get("max_commits", 200),
53
59
  help="最多拉取多少条提交(无 token 时自动限制为 30)")
54
60
  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="生成后打开报告")
61
+ github.add_argument("--open", action=argparse.BooleanOptionalAction,
62
+ default=cfg.get("open", False), help="生成后打开报告")
57
63
  github.add_argument("--quiet", action="store_true", help="不打印扫描进度")
58
64
  github.add_argument("--theme", choices=sorted(THEMES),
59
65
  default=cfg.get("theme", "paper"),
60
66
  help="卡片主题:paper / mono / forest / ocean")
67
+ github.add_argument("--require-complete", action="store_true",
68
+ help="公开统计有警告时退出,避免自动更新不完整的卡片")
61
69
  github.add_argument("--card-only", action="store_true",
62
70
  help="只生成主页卡片和 embed 片段,不生成完整报告")
63
71
  github.add_argument("--profile-repo", default=None,
@@ -83,30 +91,32 @@ def _build_parser() -> argparse.ArgumentParser:
83
91
  help="要扫描的文件夹(可以多个,默认当前目录)")
84
92
  scan.add_argument("--year", type=int, default=cfg.get("year", date.today().year),
85
93
  help="统计年份,默认今年")
86
- scan.add_argument("--rolling", action="store_true",
94
+ scan.add_argument("--rolling", action=argparse.BooleanOptionalAction,
87
95
  default=cfg.get("rolling", False),
88
96
  help="统计过去 365 天(滚动年度),而非自然年")
89
- scan.add_argument("--exclude", action="append", default=cfg.get("exclude", []),
97
+ scan.add_argument("--exclude", action=_CopyAppendAction, default=list(cfg.get("exclude", [])),
90
98
  help="排除指定仓库名或通配符(可重复或逗号分隔)")
91
99
  scan.add_argument("--out", default=cfg.get("out", "codeyear-output"),
92
100
  help="输出目录,默认 ./codeyear-output")
93
101
  scan.add_argument("--author", default=cfg.get("author"),
94
102
  help="只统计匹配的 git author(--author 参数)")
95
- scan.add_argument("--compare", action="store_true",
103
+ scan.add_argument("--compare", action=argparse.BooleanOptionalAction,
96
104
  default=cfg.get("compare", False),
97
105
  help="同时扫描去年,在报告里生成同比数据")
98
- scan.add_argument("--fallback-previous", action="store_true",
106
+ scan.add_argument("--fallback-previous", action=argparse.BooleanOptionalAction,
99
107
  default=cfg.get("fallback_previous", False),
100
108
  help="当年没有提交时回退到上一年,适合跨年自动更新")
101
- scan.add_argument("--alias", action="append", default=cfg.get("aliases", []),
109
+ scan.add_argument("--alias", action=_CopyAppendAction, default=list(cfg.get("aliases", [])),
102
110
  help="额外作者邮箱或名字,可重复;用于旧提交")
103
111
  scan.add_argument("--no-mailmap", action="store_true",
104
112
  default=cfg.get("no_mailmap", False),
105
113
  help="忽略仓库里的 .mailmap(默认自动使用)")
106
- scan.add_argument("--all-branches", action="store_true",
114
+ scan.add_argument("--mailmap", dest="no_mailmap", action="store_false",
115
+ help="使用仓库里的 .mailmap")
116
+ scan.add_argument("--all-branches", action=argparse.BooleanOptionalAction,
107
117
  default=cfg.get("all_branches", False),
108
118
  help="统计所有本地分支/tag 的提交(默认只看当前分支)")
109
- scan.add_argument("--all-authors", action="store_true",
119
+ scan.add_argument("--all-authors", action=argparse.BooleanOptionalAction,
110
120
  default=cfg.get("all_authors", False),
111
121
  help="统计所有作者的提交(默认只统计你本人,按 git user.name / user.email 识别)")
112
122
  scan.add_argument("--max-depth", type=int, default=cfg.get("max_depth", 6),
@@ -126,7 +136,7 @@ def _build_parser() -> argparse.ArgumentParser:
126
136
  help="本地 GitHub Profile 仓库路径;只写入本地,不联网")
127
137
  scan.add_argument("--push-profile", action="store_true",
128
138
  help="更新后提交并推送 Profile 仓库(联网);需同时指定 --profile-repo")
129
- scan.add_argument("--open", action="store_true", default=cfg.get("open", False),
139
+ scan.add_argument("--open", action=argparse.BooleanOptionalAction, default=cfg.get("open", False),
130
140
  help="生成后自动打开报告")
131
141
  scan.add_argument("--quiet", action="store_true", help="不打印扫描进度")
132
142
  i18n.localize_parser(parser)
@@ -147,22 +157,7 @@ def _open_path(path: Path) -> None:
147
157
 
148
158
  def _detect_identity() -> tuple[str, str] | None:
149
159
  """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
160
+ return detect_identity()
166
161
 
167
162
 
168
163
  def main(argv: list[str] | None = None) -> int:
@@ -224,7 +219,7 @@ def main(argv: list[str] | None = None) -> int:
224
219
  cache_dir=args.cache_dir,
225
220
  no_cache=args.no_cache,
226
221
  lang=i18n.get_lang(),
227
- tz=args.tz,
222
+ tz=args.tz, require_complete=args.require_complete,
228
223
  )
229
224
  if args.command == "serve":
230
225
  from .server import serve
@@ -292,6 +287,7 @@ def main(argv: list[str] | None = None) -> int:
292
287
  jobs=max(1, args.jobs), progress=progress,
293
288
  compare=args.compare, use_mailmap=not args.no_mailmap,
294
289
  all_branches=args.all_branches,
290
+ rolling=args.rolling,
295
291
  )
296
292
  if previous.commit_count:
297
293
  stats, warnings = previous, prev_warnings
@@ -308,56 +304,31 @@ def main(argv: list[str] | None = None) -> int:
308
304
  return 3
309
305
 
310
306
  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
-
307
+ formats = {"json"}
323
308
  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
-
309
+ formats.add("html")
329
310
  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))
311
+ formats.add("png")
336
312
  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"
313
+ formats.add("long")
348
314
  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]))
315
+ formats.add("card")
316
+ card_theme = getattr(args, "theme", "paper") or "paper"
317
+ written = render(
318
+ stats, out_dir, formats=formats,
319
+ card_theme=card_theme, lang=i18n.get_lang(),
320
+ )
321
+ by_label = dict(written)
322
+ card_paths = (
323
+ [by_label["CARD"], by_label["CARD-DARK"]]
324
+ if "CARD" in by_label and "CARD-DARK" in by_label
325
+ else []
326
+ )
327
+ en_cards = (
328
+ [by_label["CARD-EN"], by_label["CARD-DARK-EN"]]
329
+ if "CARD-EN" in by_label and "CARD-DARK-EN" in by_label
330
+ else []
331
+ )
361
332
 
362
333
  exit_code = 0
363
334
  if args.profile_repo:
@@ -394,7 +365,7 @@ def main(argv: list[str] | None = None) -> int:
394
365
  exit_code = 1
395
366
 
396
367
  # Console summary
397
- active_pct = stats.active_days / (366 if _is_leap(args.year) else 365)
368
+ active_pct = stats.active_days / window_days(stats)
398
369
  print()
399
370
  print(i18n.tr(
400
371
  "CodeYear {year} · {title}",
@@ -442,9 +413,5 @@ def main(argv: list[str] | None = None) -> int:
442
413
  return exit_code
443
414
 
444
415
 
445
- def _is_leap(year: int) -> bool:
446
- return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
447
-
448
-
449
416
  if __name__ == "__main__": # pragma: no cover
450
417
  raise SystemExit(main())
codeyear/config.py CHANGED
@@ -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)