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/gui.py ADDED
@@ -0,0 +1,960 @@
1
+ """Desktop GUI for CodeYear, built with Tkinter (no extra dependency)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import ctypes
7
+ import os
8
+ import queue
9
+ import re
10
+ import sys
11
+ import threading
12
+ import tkinter as tk
13
+ import webbrowser
14
+ from datetime import date
15
+ from pathlib import Path
16
+ from tkinter import filedialog, messagebox, ttk
17
+
18
+ from . import i18n
19
+ from .card import THEMES
20
+ from .config import load as load_config
21
+ from .config import save as save_config
22
+ from .runner import detect_identity, discover, render, report_path, scan
23
+ from .stats import fmt_int
24
+ from .updater import check_update, cleanup_old_executable, perform_update
25
+
26
+ PAPER = "#f5f2e9"
27
+ PAPER2 = "#ece8dc"
28
+ INK = "#141413"
29
+ MUTED = "#6f6a5e"
30
+ ACCENT = "#c8552f"
31
+ LINE = "#d8d2c2"
32
+
33
+
34
+ class App:
35
+ def __init__(self, root: tk.Tk) -> None:
36
+ self.root = root
37
+ self.cfg = load_config()
38
+ self.roots: list[Path] = []
39
+ for raw in self.cfg.get("roots", []):
40
+ candidate = Path(raw).expanduser()
41
+ if candidate.is_dir():
42
+ resolved = candidate.resolve()
43
+ if resolved not in self.roots:
44
+ self.roots.append(resolved)
45
+ self.queue: queue.Queue = queue.Queue()
46
+ self.identity = detect_identity()
47
+ self.written: list[tuple[str, Path]] = []
48
+ self.html_path: Path | None = None
49
+ self.update_info: dict | None = None
50
+ self.busy = False
51
+
52
+ root.title(i18n.tr("CodeYear · 代码手账"))
53
+ root.geometry("860x960")
54
+ root.minsize(760, 720)
55
+ root.configure(bg=PAPER)
56
+ self._style()
57
+ self._build()
58
+ for folder in self.roots:
59
+ self.folder_list.insert("end", str(folder))
60
+ if self.roots:
61
+ self.count_label.configure(
62
+ text=i18n.tr("已添加,开始生成时会统计仓库数量")
63
+ )
64
+ self._poll()
65
+ if not os.environ.get("CODEYEAR_NO_UPDATE_CHECK"):
66
+ threading.Thread(
67
+ target=self._bg_check_update, args=(False,), daemon=True
68
+ ).start()
69
+
70
+ def _style(self) -> None:
71
+ style = ttk.Style()
72
+ with contextlib.suppress(tk.TclError):
73
+ style.theme_use("clam")
74
+ style.configure(
75
+ "CY.Horizontal.TProgressbar",
76
+ troughcolor=PAPER2, background=ACCENT, bordercolor=LINE,
77
+ lightcolor=ACCENT, darkcolor=ACCENT, thickness=8,
78
+ )
79
+ style.configure(
80
+ "CY.Vertical.TScrollbar",
81
+ background=PAPER2, troughcolor=PAPER, bordercolor=LINE,
82
+ arrowcolor=MUTED, relief="flat",
83
+ )
84
+ style.configure(
85
+ "CY.TEntry",
86
+ fieldbackground="white", foreground=INK, bordercolor=LINE,
87
+ lightcolor=LINE, darkcolor=LINE, padding=(6, 4),
88
+ font=("Consolas", 10),
89
+ )
90
+ style.map("CY.TEntry", fieldbackground=[("disabled", PAPER2)],
91
+ foreground=[("disabled", MUTED)])
92
+ style.configure(
93
+ "CY.TSpinbox",
94
+ fieldbackground="white", foreground=INK, background=PAPER2,
95
+ arrowcolor=MUTED, bordercolor=LINE, lightcolor=LINE,
96
+ darkcolor=LINE, padding=(6, 4), font=("Consolas", 10),
97
+ )
98
+ style.map("CY.TSpinbox", fieldbackground=[("disabled", PAPER2)],
99
+ foreground=[("disabled", MUTED)])
100
+ style.configure(
101
+ "CY.TButton",
102
+ background=PAPER2, foreground=INK, bordercolor=LINE,
103
+ lightcolor=PAPER2, darkcolor=PAPER2, padding=(12, 6),
104
+ font=("Microsoft YaHei", 9),
105
+ )
106
+ style.map(
107
+ "CY.TButton",
108
+ background=[("active", "#ddd7c8"), ("disabled", PAPER2)],
109
+ foreground=[("disabled", MUTED)],
110
+ )
111
+ style.configure(
112
+ "Accent.TButton",
113
+ background=ACCENT, foreground="white", bordercolor=ACCENT,
114
+ lightcolor=ACCENT, darkcolor=ACCENT, padding=(18, 8),
115
+ font=("Microsoft YaHei", 10, "bold"),
116
+ )
117
+ style.map(
118
+ "Accent.TButton",
119
+ background=[("active", "#a8431f"), ("disabled", "#d8a08c")],
120
+ foreground=[("disabled", "#f5e6df")],
121
+ )
122
+ style.configure(
123
+ "CY.TCheckbutton",
124
+ background=PAPER, foreground=INK, indicatorbackground="white",
125
+ indicatorforeground=INK, indicatorrelief="flat",
126
+ padding=(0, 2), font=("Microsoft YaHei", 9),
127
+ )
128
+ style.map(
129
+ "CY.TCheckbutton",
130
+ background=[("active", PAPER)],
131
+ foreground=[("disabled", MUTED)],
132
+ )
133
+ style.configure(
134
+ "CY.TLabelframe",
135
+ background=PAPER, bordercolor=LINE, lightcolor=LINE,
136
+ darkcolor=LINE, relief="solid", borderwidth=1,
137
+ )
138
+ style.configure(
139
+ "CY.TLabelframe.Label",
140
+ background=PAPER, foreground=INK,
141
+ font=("Microsoft YaHei", 10, "bold"),
142
+ )
143
+
144
+ def _build(self) -> None:
145
+ pad = {"padx": 22}
146
+ self.root.title(i18n.tr("CodeYear · 代码手账"))
147
+
148
+ header = tk.Frame(self.root, bg=PAPER)
149
+ header.pack(fill="x", **pad, pady=(22, 10))
150
+ header_top = tk.Frame(header, bg=PAPER)
151
+ header_top.pack(fill="x")
152
+ title_col = tk.Frame(header_top, bg=PAPER)
153
+ title_col.pack(side="left", anchor="w")
154
+ tk.Label(
155
+ title_col, text=i18n.tr("代码手账"), bg=PAPER, fg=INK,
156
+ font=("Georgia", 26), anchor="w",
157
+ ).pack(anchor="w")
158
+ self.lang_btn = self._button(
159
+ header_top,
160
+ "中文" if i18n.get_lang() == "en" else "English",
161
+ self._switch_lang,
162
+ )
163
+ self.lang_btn.pack(side="right", anchor="ne", pady=(4, 0))
164
+ has_upd = bool(self.update_info and self.update_info.get("has_update"))
165
+ upd_text = (
166
+ i18n.tr("发现新版 v{version}", version=self.update_info["latest"])
167
+ if has_upd and self.update_info
168
+ else i18n.tr("检查更新")
169
+ )
170
+ self.update_btn = ttk.Button(
171
+ header_top,
172
+ text=upd_text,
173
+ command=self._on_update_click,
174
+ style="Accent.TButton" if has_upd else "CY.TButton",
175
+ cursor="hand2",
176
+ )
177
+ self.update_btn.pack(side="right", anchor="ne", padx=(0, 8), pady=(4, 0))
178
+ tk.Label(
179
+ header, text=i18n.tr("选择目录,生成一份本地年度代码报告。"),
180
+ bg=PAPER, fg=MUTED, font=("Microsoft YaHei", 10), anchor="w",
181
+ ).pack(anchor="w", pady=(4, 0))
182
+
183
+ body = tk.Frame(self.root, bg=PAPER)
184
+ body.pack(fill="both", expand=True, **pad)
185
+
186
+ # ---- folders -------------------------------------------------
187
+ folder_box = ttk.LabelFrame(
188
+ body, text=i18n.tr("扫描目录"), style="CY.TLabelframe", padding=0,
189
+ )
190
+ folder_box.pack(fill="x", pady=(6, 12))
191
+
192
+ list_wrap = tk.Frame(folder_box, bg=PAPER)
193
+ list_wrap.pack(fill="x", padx=12, pady=(8, 6))
194
+ self.folder_list = tk.Listbox(
195
+ list_wrap, height=5, selectmode=tk.EXTENDED, exportselection=False,
196
+ bg="white", fg=INK, relief="flat", highlightthickness=1,
197
+ highlightbackground=LINE, highlightcolor=LINE,
198
+ selectbackground=ACCENT, selectforeground="white",
199
+ font=("Consolas", 10),
200
+ )
201
+ self.folder_list.pack(side="left", fill="x", expand=True)
202
+ scroll = ttk.Scrollbar(
203
+ list_wrap, orient="vertical", style="CY.Vertical.TScrollbar",
204
+ command=self.folder_list.yview)
205
+ scroll.pack(side="right", fill="y")
206
+ self.folder_list.configure(yscrollcommand=scroll.set)
207
+
208
+ buttons = tk.Frame(folder_box, bg=PAPER)
209
+ buttons.pack(fill="x", padx=12, pady=(0, 10))
210
+ self._button(buttons, i18n.tr("添加目录"), self._add_folder).pack(side="left")
211
+ self._button(buttons, i18n.tr("删除选中"), self._remove_folder).pack(
212
+ side="left", padx=(8, 0))
213
+ self._button(buttons, i18n.tr("清空"), self._clear_folders).pack(
214
+ side="left", padx=(8, 0))
215
+ self._button(buttons, i18n.tr("检查仓库"), self._check_repos).pack(
216
+ side="left", padx=(8, 0))
217
+ self.count_label = tk.Label(
218
+ buttons, text=i18n.tr("可添加多个目录"), bg=PAPER, fg=MUTED,
219
+ font=("Microsoft YaHei", 9),
220
+ )
221
+ self.count_label.pack(side="right")
222
+
223
+ # ---- options -------------------------------------------------
224
+ options = tk.Frame(body, bg=PAPER)
225
+ options.pack(fill="x", pady=(0, 12))
226
+
227
+ tk.Label(options, text=i18n.tr("年份"), bg=PAPER, fg=MUTED,
228
+ font=("Microsoft YaHei", 9)).grid(row=0, column=0, sticky="w")
229
+ self.year_var = tk.StringVar(
230
+ value=str(self.cfg.get("year", date.today().year))
231
+ )
232
+ ttk.Entry(
233
+ options, width=8, textvariable=self.year_var, style="CY.TEntry",
234
+ ).grid(row=1, column=0, sticky="w", pady=(2, 0))
235
+
236
+ tk.Label(options, text=i18n.tr("扫描层级"), bg=PAPER, fg=MUTED,
237
+ font=("Microsoft YaHei", 9)).grid(
238
+ row=0, column=1, sticky="w", padx=(22, 0))
239
+ self.depth_var = tk.StringVar(
240
+ value=str(self.cfg.get("max_depth", 6))
241
+ )
242
+ ttk.Entry(
243
+ options, width=6, textvariable=self.depth_var, style="CY.TEntry",
244
+ ).grid(row=1, column=1, sticky="w", padx=(22, 0), pady=(2, 0))
245
+
246
+ tk.Label(options, text=i18n.tr("卡片主题"), bg=PAPER, fg=MUTED,
247
+ font=("Microsoft YaHei", 9)).grid(
248
+ row=0, column=2, sticky="w", padx=(22, 0))
249
+ self.theme_var = tk.StringVar(
250
+ value=str(self.cfg.get("theme", "paper"))
251
+ )
252
+ ttk.Combobox(
253
+ options, width=8, textvariable=self.theme_var,
254
+ values=sorted(THEMES), state="readonly",
255
+ ).grid(row=1, column=2, sticky="w", padx=(22, 0), pady=(2, 0))
256
+
257
+ if self.identity:
258
+ email, name = self.identity
259
+ who = f"{name} <{email}>" if name and email else (email or name)
260
+ identity_text = i18n.tr("只统计我本人({who})", who=who)
261
+ else:
262
+ identity_text = i18n.tr("未检测到 git 身份,将统计所有作者")
263
+ only_me_default = bool(self.identity) and not bool(
264
+ self.cfg.get("all_authors", False)
265
+ )
266
+ self.identity_var = tk.BooleanVar(value=only_me_default)
267
+ self.identity_box, self._identity_draw = self._check(
268
+ options, identity_text, self.identity_var,
269
+ enabled=bool(self.identity),
270
+ )
271
+ self.identity_box.grid(
272
+ row=0, column=3, rowspan=2, sticky="w", padx=(26, 0))
273
+
274
+ tk.Label(
275
+ body, text=i18n.tr(
276
+ "扫描层级 = 向下查找仓库的文件夹层数,默认 6。"
277
+ ),
278
+ bg=PAPER, fg=MUTED, font=("Microsoft YaHei", 8), anchor="w",
279
+ ).pack(fill="x", pady=(0, 10))
280
+
281
+ advanced = tk.Frame(body, bg=PAPER)
282
+ advanced.pack(fill="x", pady=(0, 10))
283
+ tk.Label(advanced, text=i18n.tr("并行数"), bg=PAPER, fg=MUTED,
284
+ font=("Microsoft YaHei", 9)).pack(side="left")
285
+ self.jobs_var = tk.StringVar(
286
+ value=str(self.cfg.get("jobs", 1))
287
+ )
288
+ ttk.Entry(
289
+ advanced, width=4, textvariable=self.jobs_var, style="CY.TEntry",
290
+ ).pack(side="left", padx=(6, 20))
291
+ self.compare_var = tk.BooleanVar(
292
+ value=bool(self.cfg.get("compare", False))
293
+ )
294
+ compare_box, self._compare_draw = self._check(
295
+ advanced, i18n.tr("同比去年"), self.compare_var,
296
+ )
297
+ compare_box.pack(side="left")
298
+ self.all_branches_var = tk.BooleanVar(
299
+ value=bool(self.cfg.get("all_branches", False))
300
+ )
301
+ branches_box, self._branches_draw = self._check(
302
+ advanced, i18n.tr("所有分支"), self.all_branches_var,
303
+ )
304
+ branches_box.pack(side="left", padx=(16, 0))
305
+ self.rolling_var = tk.BooleanVar(
306
+ value=bool(self.cfg.get("rolling", False))
307
+ )
308
+ rolling_box, self._rolling_draw = self._check(
309
+ advanced, i18n.tr("近 365 天"), self.rolling_var,
310
+ )
311
+ rolling_box.pack(side="left", padx=(16, 0))
312
+ tk.Label(advanced, text=i18n.tr("旧邮箱/名字"), bg=PAPER, fg=MUTED,
313
+ font=("Microsoft YaHei", 9)).pack(side="left", padx=(18, 6))
314
+ self.alias_var = tk.StringVar(
315
+ value=", ".join(self.cfg.get("aliases", []))
316
+ )
317
+ ttk.Entry(
318
+ advanced, width=14, textvariable=self.alias_var, style="CY.TEntry",
319
+ ).pack(side="left")
320
+ tk.Label(advanced, text=i18n.tr("排除仓库"), bg=PAPER, fg=MUTED,
321
+ font=("Microsoft YaHei", 9)).pack(side="left", padx=(14, 6))
322
+ self.exclude_var = tk.StringVar(
323
+ value=", ".join(self.cfg.get("exclude", []))
324
+ )
325
+ ttk.Entry(
326
+ advanced, width=14, textvariable=self.exclude_var, style="CY.TEntry",
327
+ ).pack(side="left")
328
+
329
+ out_row = tk.Frame(body, bg=PAPER)
330
+ out_row.pack(fill="x", pady=(0, 8))
331
+ tk.Label(out_row, text=i18n.tr("输出目录"), bg=PAPER, fg=MUTED,
332
+ font=("Microsoft YaHei", 9)).pack(side="left", padx=(0, 8))
333
+ self.out_var = tk.StringVar(
334
+ value=str(self.cfg.get("out", "codeyear-output"))
335
+ )
336
+ ttk.Entry(
337
+ out_row, textvariable=self.out_var, style="CY.TEntry",
338
+ ).pack(side="left", fill="x", expand=True)
339
+ self._button(out_row, i18n.tr("选择…"), self._choose_output).pack(
340
+ side="left", padx=(8, 0))
341
+
342
+ gh_row = tk.Frame(body, bg=PAPER)
343
+ gh_row.pack(fill="x", pady=(0, 14))
344
+ tk.Label(
345
+ gh_row, text=i18n.tr("GitHub 账号(留空扫本地)"),
346
+ bg=PAPER, fg=MUTED, font=("Microsoft YaHei", 9),
347
+ ).pack(side="left", padx=(0, 6))
348
+ self.github_var = tk.StringVar(
349
+ value=str(self.cfg.get("github_user", ""))
350
+ )
351
+ ttk.Entry(
352
+ gh_row, width=14, textvariable=self.github_var, style="CY.TEntry",
353
+ ).pack(side="left")
354
+ tk.Label(
355
+ gh_row, text=i18n.tr("Profile 仓库"),
356
+ bg=PAPER, fg=MUTED, font=("Microsoft YaHei", 9),
357
+ ).pack(side="left", padx=(16, 6))
358
+ self.profile_var = tk.StringVar(
359
+ value=str(self.cfg.get("profile_repo", ""))
360
+ )
361
+ ttk.Entry(
362
+ gh_row, textvariable=self.profile_var, style="CY.TEntry",
363
+ ).pack(side="left", fill="x", expand=True)
364
+ self._button(gh_row, i18n.tr("选择…"), self._choose_profile).pack(
365
+ side="left", padx=(6, 10))
366
+ self.push_profile_var = tk.BooleanVar(
367
+ value=bool(self.cfg.get("push_profile", False))
368
+ )
369
+ push_box, self._push_draw = self._check(
370
+ gh_row, i18n.tr("推送"), self.push_profile_var,
371
+ )
372
+ push_box.pack(side="left")
373
+
374
+ # ---- actions -------------------------------------------------
375
+ actions = tk.Frame(body, bg=PAPER)
376
+ actions.pack(fill="x", pady=(0, 10))
377
+ self.start_btn = ttk.Button(
378
+ actions, text=i18n.tr("开始生成"), command=self._start,
379
+ style="Accent.TButton", cursor="hand2",
380
+ )
381
+ self.start_btn.pack(side="left")
382
+ self.open_btn = self._button(
383
+ actions, i18n.tr("打开报告"), self._open_report,
384
+ )
385
+ self.open_btn.configure(state="disabled")
386
+ self.open_btn.pack(side="left", padx=(10, 0))
387
+ self.folder_btn = self._button(
388
+ actions, i18n.tr("打开输出目录"), self._open_output,
389
+ )
390
+ self.folder_btn.configure(state="disabled")
391
+ self.folder_btn.pack(side="left", padx=(10, 0))
392
+ self._button(
393
+ actions, i18n.tr("保存默认"), self._save_defaults,
394
+ ).pack(side="right")
395
+
396
+ self.progress = ttk.Progressbar(
397
+ body, style="CY.Horizontal.TProgressbar", mode="determinate",
398
+ )
399
+ self.progress.pack(fill="x", pady=(4, 6))
400
+ self.status = tk.Label(
401
+ body, text=i18n.tr("选择目录后点击「开始生成」。"),
402
+ bg=PAPER, fg=MUTED, font=("Microsoft YaHei", 9), anchor="w",
403
+ )
404
+ self.status.pack(fill="x")
405
+
406
+ # ---- result --------------------------------------------------
407
+ result_box = ttk.LabelFrame(
408
+ body, text=i18n.tr("结果"), style="CY.TLabelframe", padding=0,
409
+ )
410
+ result_box.pack(fill="both", expand=True, pady=(12, 0))
411
+ text_wrap = tk.Frame(result_box, bg=PAPER)
412
+ text_wrap.pack(fill="both", expand=True, padx=12, pady=10)
413
+ self.result = tk.Text(
414
+ text_wrap, height=8, wrap="word", bg="white", fg=INK,
415
+ relief="flat", highlightthickness=1, highlightbackground=LINE,
416
+ selectbackground=ACCENT, selectforeground="white",
417
+ font=("Consolas", 9),
418
+ )
419
+ self.result.pack(side="left", fill="both", expand=True)
420
+ rscroll = ttk.Scrollbar(
421
+ text_wrap, orient="vertical", style="CY.Vertical.TScrollbar",
422
+ command=self.result.yview)
423
+ rscroll.pack(side="right", fill="y")
424
+ self.result.configure(yscrollcommand=rscroll.set, state="disabled")
425
+
426
+ def _button(self, parent, text, command):
427
+ return ttk.Button(
428
+ parent, text=text, command=command, style="CY.TButton",
429
+ cursor="hand2",
430
+ )
431
+
432
+ # ---- folder actions ----------------------------------------------
433
+ def _add_folder(self) -> None:
434
+ path = filedialog.askdirectory(
435
+ parent=self.root, title=i18n.tr("选择要扫描的目录"), mustexist=True,
436
+ )
437
+ if not path:
438
+ return
439
+ resolved = Path(path).resolve()
440
+ if resolved in self.roots:
441
+ return
442
+ self.roots.append(resolved)
443
+ self.folder_list.insert("end", str(resolved))
444
+ self.count_label.configure(
445
+ text=i18n.tr("已添加,开始生成时会统计仓库数量")
446
+ )
447
+
448
+ def _remove_folder(self) -> None:
449
+ selected = list(self.folder_list.curselection())
450
+ for index in reversed(selected):
451
+ self.folder_list.delete(index)
452
+ del self.roots[index]
453
+
454
+ def _clear_folders(self) -> None:
455
+ self.folder_list.delete(0, "end")
456
+ self.roots.clear()
457
+
458
+ def _switch_lang(self) -> None:
459
+ if self.busy:
460
+ return
461
+ target = "en" if i18n.get_lang() == "zh" else "zh"
462
+ saved = {
463
+ "roots": list(self.roots),
464
+ "year": self.year_var.get(),
465
+ "depth": self.depth_var.get(),
466
+ "theme": self.theme_var.get(),
467
+ "jobs": self.jobs_var.get(),
468
+ "out": self.out_var.get(),
469
+ "alias": self.alias_var.get(),
470
+ "exclude": self.exclude_var.get(),
471
+ "github": self.github_var.get(),
472
+ "profile": self.profile_var.get(),
473
+ "push": self.push_profile_var.get(),
474
+ "compare": self.compare_var.get(),
475
+ "branches": self.all_branches_var.get(),
476
+ "rolling": self.rolling_var.get(),
477
+ "identity": self.identity_var.get(),
478
+ "result": self.result.get("1.0", "end-1c"),
479
+ }
480
+ i18n.set_lang(target)
481
+ for child in self.root.winfo_children():
482
+ child.destroy()
483
+ self._build()
484
+
485
+ self.roots = saved["roots"]
486
+ for root in self.roots:
487
+ self.folder_list.insert("end", str(root))
488
+ self.year_var.set(saved["year"])
489
+ self.depth_var.set(saved["depth"])
490
+ self.theme_var.set(saved["theme"])
491
+ self.jobs_var.set(saved["jobs"])
492
+ self.out_var.set(saved["out"])
493
+ self.alias_var.set(saved["alias"])
494
+ self.exclude_var.set(saved["exclude"])
495
+ self.github_var.set(saved["github"])
496
+ self.profile_var.set(saved["profile"])
497
+ self.push_profile_var.set(saved["push"])
498
+ self.compare_var.set(saved["compare"])
499
+ self.all_branches_var.set(saved["branches"])
500
+ self.rolling_var.set(saved["rolling"])
501
+ self.identity_var.set(saved["identity"])
502
+ self._identity_draw()
503
+ self._compare_draw()
504
+ self._branches_draw()
505
+ self._rolling_draw()
506
+ self._push_draw()
507
+ if self.roots:
508
+ self.count_label.configure(
509
+ text=i18n.tr("已添加,开始生成时会统计仓库数量"))
510
+ self._set_result(saved["result"])
511
+ self.html_path = report_path(self.written, lang=i18n.get_lang())
512
+ if self.written:
513
+ self.open_btn.configure(
514
+ state="normal" if self.html_path else "disabled")
515
+ self.folder_btn.configure(state="normal")
516
+ self.progress.configure(maximum=1, value=1)
517
+ self.status.configure(text=i18n.tr("完成。"))
518
+ else:
519
+ self.status.configure(
520
+ text=i18n.tr("选择目录后点击「开始生成」。"))
521
+ self._set_busy(False)
522
+
523
+ def _check_repos(self) -> None:
524
+ if not self.roots:
525
+ messagebox.showwarning(
526
+ i18n.tr("没有目录"), i18n.tr("请先添加至少一个目录。"),
527
+ )
528
+ return
529
+ try:
530
+ depth = int(self.depth_var.get())
531
+ except ValueError:
532
+ depth = 6
533
+ excludes = [
534
+ item.strip() for item in self.exclude_var.get().split(",")
535
+ if item.strip()
536
+ ]
537
+ self.count_label.configure(text=i18n.tr("正在检查…"))
538
+ threading.Thread(
539
+ target=self._count_work, args=(list(self.roots), depth, excludes),
540
+ daemon=True,
541
+ ).start()
542
+
543
+ def _count_work(self, roots, depth, excludes=None) -> None:
544
+ try:
545
+ self.queue.put((
546
+ "checked", len(discover(roots, depth, exclude=excludes))
547
+ ))
548
+ except Exception as exc: # pragma: no cover - UI path
549
+ self.queue.put(("error", str(exc)))
550
+
551
+ def _choose_output(self) -> None:
552
+ path = filedialog.askdirectory(
553
+ parent=self.root, title=i18n.tr("选择输出目录"), mustexist=False,
554
+ )
555
+ if path:
556
+ self.out_var.set(path)
557
+
558
+ def _choose_profile(self) -> None:
559
+ path = filedialog.askdirectory(
560
+ parent=self.root, title=i18n.tr("选择 Profile 仓库目录"),
561
+ mustexist=True,
562
+ )
563
+ if path:
564
+ self.profile_var.set(path)
565
+
566
+ def _save_defaults(self) -> None:
567
+ try:
568
+ year = int(self.year_var.get())
569
+ depth = int(self.depth_var.get())
570
+ jobs = max(1, int(self.jobs_var.get()))
571
+ except ValueError:
572
+ messagebox.showwarning(
573
+ i18n.tr("参数不对"),
574
+ i18n.tr("年份、扫描层级和并行数必须是数字。"),
575
+ )
576
+ return
577
+ aliases = [
578
+ item.strip() for item in self.alias_var.get().split(",")
579
+ if item.strip()
580
+ ]
581
+ excludes = [
582
+ item.strip() for item in self.exclude_var.get().split(",")
583
+ if item.strip()
584
+ ]
585
+ data = {
586
+ "roots": [str(r) for r in self.roots],
587
+ "year": year,
588
+ "max_depth": depth,
589
+ "jobs": jobs,
590
+ "compare": bool(self.compare_var.get()),
591
+ "all_branches": bool(self.all_branches_var.get()),
592
+ "rolling": bool(self.rolling_var.get()),
593
+ "all_authors": not bool(self.identity_var.get()),
594
+ "aliases": aliases,
595
+ "exclude": excludes,
596
+ "github_user": self.github_var.get().strip(),
597
+ "profile_repo": self.profile_var.get().strip(),
598
+ "push_profile": bool(self.push_profile_var.get()),
599
+ "out": self.out_var.get().strip() or "codeyear-output",
600
+ "theme": self.theme_var.get() or "paper",
601
+ }
602
+ try:
603
+ save_config(data)
604
+ except OSError as exc:
605
+ messagebox.showerror(i18n.tr("无法保存"), str(exc))
606
+ return
607
+ self.cfg.update(data)
608
+ self.status.configure(text=i18n.tr("已保存默认设置。"))
609
+
610
+ # ---- worker ------------------------------------------------------
611
+ def _start(self) -> None:
612
+ if self.busy:
613
+ return
614
+ github_user = self.github_var.get().strip()
615
+ if not self.roots and not github_user:
616
+ messagebox.showwarning(
617
+ i18n.tr("没有目录"),
618
+ i18n.tr("请先添加至少一个要扫描的目录。"),
619
+ )
620
+ return
621
+ try:
622
+ year = int(self.year_var.get())
623
+ depth = int(self.depth_var.get())
624
+ jobs = max(1, int(self.jobs_var.get()))
625
+ except ValueError:
626
+ messagebox.showwarning(
627
+ i18n.tr("参数不对"),
628
+ i18n.tr("年份、扫描层级和并行数必须是数字。"),
629
+ )
630
+ return
631
+ out_dir = Path(self.out_var.get()).expanduser().resolve()
632
+ identity = self.identity if self.identity_var.get() else None
633
+ compare = self.compare_var.get()
634
+ all_branches = self.all_branches_var.get()
635
+ rolling = self.rolling_var.get()
636
+ aliases = [item.strip() for item in self.alias_var.get().split(",")
637
+ if item.strip()]
638
+ excludes = [item.strip() for item in self.exclude_var.get().split(",")
639
+ if item.strip()]
640
+ profile_repo = self.profile_var.get().strip() or None
641
+ push_profile = bool(self.push_profile_var.get())
642
+
643
+ self._set_busy(True)
644
+ self.written = []
645
+ self.html_path = None
646
+ self.progress.configure(value=0, maximum=1)
647
+ self.status.configure(
648
+ text=i18n.tr("正在拉取公开 GitHub 数据…")
649
+ if github_user
650
+ else i18n.tr("正在查找 git 仓库…")
651
+ )
652
+ self._set_result("")
653
+ threading.Thread(
654
+ target=self._work,
655
+ args=(list(self.roots), depth, year, out_dir, identity,
656
+ jobs, compare, aliases, all_branches, rolling, excludes,
657
+ github_user, profile_repo, push_profile),
658
+ daemon=True,
659
+ ).start()
660
+
661
+ def _work(self, roots, depth, year, out_dir, identity, jobs, compare,
662
+ aliases, all_branches, rolling=False, excludes=None,
663
+ github_user="", profile_repo=None, push_profile=False) -> None:
664
+ try:
665
+ if github_user:
666
+ from .github_public import default_cache_dir, fetch_stats
667
+
668
+ safe_name = re.sub(r"[^a-z0-9_.-]", "_", github_user.lower())
669
+ cache_path = default_cache_dir() / f"github-{safe_name}.json"
670
+ stats, warnings, _login = fetch_stats(
671
+ github_user,
672
+ year,
673
+ max_commits=int(self.cfg.get("max_commits", 500)),
674
+ quiet=True,
675
+ cache_path=cache_path,
676
+ tz=self.cfg.get("tz"),
677
+ )
678
+ else:
679
+ repos = discover(roots, depth, exclude=excludes)
680
+ if not repos:
681
+ raise RuntimeError(i18n.tr("没有找到 git 仓库。"))
682
+ self.queue.put(("count", len(repos)))
683
+
684
+ def progress(done, total, name):
685
+ self.queue.put(("progress", done, total, name))
686
+
687
+ stats, warnings = scan(
688
+ repos, roots, year, identity, aliases=aliases,
689
+ author=self.cfg.get("author"),
690
+ timeout=int(self.cfg.get("timeout", 300)),
691
+ progress=progress, jobs=jobs, compare=compare,
692
+ use_mailmap=not bool(self.cfg.get("no_mailmap", False)),
693
+ all_branches=all_branches,
694
+ rolling=rolling,
695
+ )
696
+ if stats.commit_count == 0:
697
+ raise RuntimeError(i18n.tr(
698
+ "{year} 年没有找到提交。", year=year,
699
+ ))
700
+ theme = self.theme_var.get() or str(self.cfg.get("theme", "paper"))
701
+ written = render(
702
+ stats, out_dir,
703
+ card_theme=theme,
704
+ lang=i18n.get_lang(),
705
+ )
706
+ if profile_repo:
707
+ from .profile import update_profile
708
+
709
+ cards = dict(written)
710
+ if i18n.get_lang() == "en":
711
+ light, dark = cards.get("CARD-EN"), cards.get("CARD-DARK-EN")
712
+ else:
713
+ light, dark = cards.get("CARD"), cards.get("CARD-DARK")
714
+ if light and dark:
715
+ repo_p, _changed, _pushed = update_profile(
716
+ profile_repo, stats.year, light, dark, push=push_profile,
717
+ )
718
+ written.append(("PROFILE", repo_p))
719
+ self.queue.put(("done", stats, written, warnings, out_dir))
720
+ except Exception as exc: # pragma: no cover - UI path
721
+ self.queue.put(("error", str(exc)))
722
+
723
+ def _poll(self) -> None:
724
+ try:
725
+ while True:
726
+ event = self.queue.get_nowait()
727
+ kind = event[0]
728
+ if kind == "count":
729
+ count = event[1]
730
+ self.status.configure(text=i18n.tr(
731
+ "找到 {count} 个仓库,开始扫描…", count=count,
732
+ ))
733
+ elif kind == "checked":
734
+ self.count_label.configure(text=i18n.tr(
735
+ "找到 {count} 个 git 仓库", count=event[1],
736
+ ))
737
+ elif kind == "progress":
738
+ _, done, total, name = event
739
+ self.progress.configure(maximum=max(total, 1), value=done)
740
+ self.status.configure(text=f"{done}/{total} · {name}")
741
+ elif kind == "done":
742
+ _, stats, written, warnings, out_dir = event
743
+ self._finish(stats, written, warnings, out_dir)
744
+ elif kind == "error":
745
+ self._fail(event[1])
746
+ elif kind == "update_checked":
747
+ _, info, manual = event
748
+ self._on_update_checked(info, manual)
749
+ elif kind == "update_applied":
750
+ _, ok, msg, info = event
751
+ self._on_update_applied(ok, msg, info)
752
+ except queue.Empty:
753
+ pass
754
+ self.root.after(100, self._poll)
755
+
756
+ def _finish(self, stats, written, warnings, out_dir) -> None:
757
+ self.written = written
758
+ self.html_path = report_path(written, lang=i18n.get_lang())
759
+ lines = [
760
+ i18n.tr(
761
+ "仓库 {repos} · 提交 {commits} · 活跃 {days} 天 · 涉及 {files} 个文件",
762
+ repos=stats.repo_count, commits=fmt_int(stats.commit_count),
763
+ days=stats.active_days, files=stats.file_count,
764
+ ),
765
+ i18n.tr("输出目录:{path}", path=out_dir),
766
+ "",
767
+ ]
768
+ lines += [f"{label:<9} {path.name}" for label, path in written]
769
+ if warnings:
770
+ lines += ["", i18n.tr("警告:")] + [f"- {item}" for item in warnings]
771
+ self._set_result("\n".join(lines))
772
+ self.status.configure(text=i18n.tr("完成。"))
773
+ self.progress.configure(value=self.progress["maximum"])
774
+ self._set_busy(False)
775
+ self.open_btn.configure(
776
+ state="normal" if self.html_path else "disabled")
777
+ self.folder_btn.configure(state="normal")
778
+
779
+ def _fail(self, message: str) -> None:
780
+ self._set_busy(False)
781
+ self.status.configure(text=i18n.tr(
782
+ "失败:{message}", message=message,
783
+ ))
784
+ messagebox.showerror(i18n.tr("生成失败"), message)
785
+
786
+ def _set_busy(self, busy: bool) -> None:
787
+ self.busy = busy
788
+ state = "disabled" if busy else "normal"
789
+ self.start_btn.configure(state=state)
790
+ if hasattr(self, "lang_btn"):
791
+ self.lang_btn.configure(state=state)
792
+ if hasattr(self, "update_btn"):
793
+ self.update_btn.configure(state=state)
794
+
795
+ def _bg_check_update(self, manual: bool) -> None:
796
+ info = check_update(timeout=5.0 if manual else 2.5)
797
+ self.queue.put(("update_checked", info, manual))
798
+
799
+ def _on_update_click(self) -> None:
800
+ if self.busy:
801
+ return
802
+ if self.update_info and self.update_info.get("has_update"):
803
+ self._prompt_and_update(self.update_info)
804
+ return
805
+ self.status.configure(text=i18n.tr("正在检查更新…"))
806
+ threading.Thread(
807
+ target=self._bg_check_update, args=(True,), daemon=True
808
+ ).start()
809
+
810
+ def _on_update_checked(self, info: dict | None, manual: bool) -> None:
811
+ if info:
812
+ self.update_info = info
813
+ if info and info.get("has_update"):
814
+ if hasattr(self, "update_btn"):
815
+ self.update_btn.configure(
816
+ text=i18n.tr("发现新版 v{version}", version=info["latest"]),
817
+ style="Accent.TButton",
818
+ )
819
+ if manual:
820
+ self._prompt_and_update(info)
821
+ return
822
+ if manual:
823
+ if not info:
824
+ self.status.configure(
825
+ text=i18n.tr("无法连接更新服务器,请检查网络。")
826
+ )
827
+ else:
828
+ self.status.configure(
829
+ text=i18n.tr(
830
+ "当前已是最新版本(v{version})。",
831
+ version=info["current"],
832
+ )
833
+ )
834
+
835
+ def _prompt_and_update(self, info: dict) -> None:
836
+ yes = messagebox.askyesno(
837
+ i18n.tr("发现新版本"),
838
+ i18n.tr(
839
+ "发现新版本 v{latest}(当前 v{current})。\n是否立即在软件内自动更新?",
840
+ latest=info["latest"],
841
+ current=info["current"],
842
+ ),
843
+ )
844
+ if not yes:
845
+ return
846
+ self._set_busy(True)
847
+ self.status.configure(text=i18n.tr("正在下载并更新…"))
848
+ threading.Thread(
849
+ target=self._bg_apply_update, args=(info,), daemon=True
850
+ ).start()
851
+
852
+ def _bg_apply_update(self, info: dict) -> None:
853
+ ok, msg = perform_update(info)
854
+ self.queue.put(("update_applied", ok, msg, info))
855
+
856
+ def _on_update_applied(self, ok: bool, msg: str, info: dict) -> None:
857
+ self._set_busy(False)
858
+ self.status.configure(text=msg)
859
+ if ok:
860
+ if hasattr(self, "update_btn"):
861
+ self.update_btn.configure(
862
+ text=i18n.tr("检查更新"), style="CY.TButton"
863
+ )
864
+ self.update_info = {**info, "has_update": False}
865
+ messagebox.showinfo(i18n.tr("更新完成"), msg)
866
+ else:
867
+ webbrowser.open(info.get("url") or "https://github.com/Qiongkura/codeyear/releases")
868
+
869
+ def _check(self, parent, text, variable, enabled=True):
870
+ frame = tk.Frame(parent, bg=PAPER,
871
+ cursor="hand2" if enabled else "")
872
+ canvas = tk.Canvas(
873
+ frame, width=16, height=16, bg=PAPER,
874
+ highlightthickness=0, bd=0,
875
+ cursor="hand2" if enabled else "",
876
+ )
877
+ canvas.pack(side="left", padx=(0, 8))
878
+ label = tk.Label(
879
+ frame, text=text, bg=PAPER,
880
+ fg=INK if enabled else MUTED,
881
+ font=("Microsoft YaHei", 9),
882
+ cursor="hand2" if enabled else "",
883
+ )
884
+ label.pack(side="left")
885
+
886
+ def draw() -> None:
887
+ canvas.delete("all")
888
+ if not enabled:
889
+ canvas.create_rectangle(1, 1, 15, 15, outline=LINE, fill=PAPER2)
890
+ return
891
+ if variable.get():
892
+ canvas.create_rectangle(1, 1, 15, 15, outline=ACCENT, fill=ACCENT)
893
+ canvas.create_line(
894
+ 4, 8, 7, 11, 12, 4, fill="white", width=2,
895
+ capstyle="round", joinstyle="round",
896
+ )
897
+ else:
898
+ canvas.create_rectangle(1, 1, 15, 15, outline=LINE, fill="white")
899
+
900
+ def toggle(_event=None) -> None:
901
+ if not enabled or self.busy:
902
+ return
903
+ variable.set(not variable.get())
904
+ draw()
905
+
906
+ if enabled:
907
+ canvas.bind("<Button-1>", toggle)
908
+ label.bind("<Button-1>", toggle)
909
+ draw()
910
+ return frame, draw
911
+
912
+ def _set_result(self, text: str) -> None:
913
+ self.result.configure(state="normal")
914
+ self.result.delete("1.0", "end")
915
+ self.result.insert("1.0", text)
916
+ self.result.configure(state="disabled")
917
+
918
+ def _open_report(self) -> None:
919
+ if self.html_path:
920
+ self._open_path(self.html_path)
921
+
922
+ def _open_output(self) -> None:
923
+ if not self.written:
924
+ return
925
+ out_dir = self.written[0][1].parent
926
+ self._open_path(out_dir)
927
+
928
+ def _open_path(self, path: Path) -> None:
929
+ try:
930
+ if hasattr(os, "startfile"):
931
+ os.startfile(str(path)) # type: ignore[attr-defined]
932
+ else:
933
+ webbrowser.open(path.as_uri())
934
+ except Exception as exc: # pragma: no cover - platform dependent
935
+ messagebox.showerror(i18n.tr("无法打开"), str(exc))
936
+
937
+
938
+ def _enable_dpi() -> None:
939
+ with contextlib.suppress(Exception):
940
+ ctypes.windll.shcore.SetProcessDpiAwareness(1)
941
+
942
+
943
+ def run() -> int:
944
+ cleanup_old_executable()
945
+ i18n.set_lang(i18n.detect(sys.argv[1:]))
946
+ _enable_dpi()
947
+ try:
948
+ root = tk.Tk()
949
+ except tk.TclError as exc:
950
+ print(i18n.tr("无法启动图形界面: {exc}", exc=exc), file=sys.stderr)
951
+ print(i18n.tr("请改用 codeyear tui 或 codeyear scan。"),
952
+ file=sys.stderr)
953
+ return 1
954
+ App(root)
955
+ root.mainloop()
956
+ return 0
957
+
958
+
959
+ def main() -> None:
960
+ raise SystemExit(run())