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/updater.py ADDED
@@ -0,0 +1,238 @@
1
+ """Lightweight, zero-dependency version checker and in-app updater.
2
+
3
+ Design principles:
4
+ - Never block startup or fail noisy when offline.
5
+ - Prefer static CDN endpoints (GitHub Pages ``version.json`` / PyPI JSON) over
6
+ rate-limited GitHub REST API calls.
7
+ - On Windows ``CodeYear.exe`` builds, update atomically in-place via
8
+ ``os.replace`` (renaming the running executable to ``.old`` and moving the
9
+ verified download into place) without spawning ``.cmd`` / PowerShell scripts.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import contextlib
15
+ import hashlib
16
+ import json
17
+ import os
18
+ import re
19
+ import subprocess
20
+ import sys
21
+ import urllib.error
22
+ import urllib.request
23
+ from pathlib import Path
24
+
25
+ from . import __version__, i18n
26
+
27
+ VERSION_JSON_URL = "https://qiongkura.github.io/codeyear/version.json"
28
+ PYPI_JSON_URL = "https://pypi.org/pypi/codeyear/json"
29
+ GITHUB_LATEST_URL = (
30
+ "https://api.github.com/repos/Qiongkura/codeyear/releases/latest"
31
+ )
32
+ RELEASE_BASE = "https://github.com/Qiongkura/codeyear/releases"
33
+ _NO_WINDOW = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0
34
+
35
+
36
+ def parse_version(version: str) -> tuple[int, ...]:
37
+ """Convert ``'v0.2.14'`` or ``'0.2.14'`` into a comparable int tuple."""
38
+ cleaned = (version or "").strip().lstrip("vV")
39
+ parts = re.findall(r"\d+", cleaned)
40
+ return tuple(int(p) for p in parts) if parts else (0,)
41
+
42
+
43
+ def is_frozen() -> bool:
44
+ """True when running inside a PyInstaller single-file executable."""
45
+ return bool(getattr(sys, "frozen", False))
46
+
47
+
48
+ def cleanup_old_executable(exe_path: Path | None = None) -> bool:
49
+ """Remove ``CodeYear.exe.old`` left over from a previous in-app update."""
50
+ target = exe_path or (Path(sys.executable) if is_frozen() else None)
51
+ if target is None:
52
+ return False
53
+ old_path = target.with_suffix(target.suffix + ".old")
54
+ if not old_path.exists():
55
+ return False
56
+ with contextlib.suppress(OSError):
57
+ old_path.unlink()
58
+ return True
59
+ return False
60
+
61
+
62
+ def _fetch_json(url: str, timeout: float) -> dict | None:
63
+ req = urllib.request.Request(
64
+ url,
65
+ headers={
66
+ "Accept": "application/json",
67
+ "User-Agent": f"CodeYear/{__version__}",
68
+ },
69
+ )
70
+ try:
71
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
72
+ body = resp.read().decode("utf-8", errors="replace")
73
+ data = json.loads(body)
74
+ return data if isinstance(data, dict) else None
75
+ except (OSError, ValueError, urllib.error.URLError):
76
+ return None
77
+
78
+
79
+ def _build_release_info(
80
+ current: str, latest: str, notes: str = ""
81
+ ) -> dict:
82
+ clean_latest = latest.strip().lstrip("vV")
83
+ tag = f"v{clean_latest}"
84
+ dl_base = f"{RELEASE_BASE}/download/{tag}"
85
+ return {
86
+ "current": current.strip().lstrip("vV"),
87
+ "latest": clean_latest,
88
+ "has_update": parse_version(clean_latest) > parse_version(current),
89
+ "url": f"{RELEASE_BASE}/tag/{tag}",
90
+ "exe_url": f"{dl_base}/CodeYear.exe",
91
+ "wheel_url": f"{dl_base}/codeyear-{clean_latest}-py3-none-any.whl",
92
+ "sums_url": f"{dl_base}/SHA256SUMS.txt",
93
+ "notes": (notes or "").strip(),
94
+ }
95
+
96
+
97
+ def check_update(
98
+ current_version: str = __version__,
99
+ *,
100
+ timeout: float = 3.0,
101
+ ) -> dict | None:
102
+ """Return release metadata dict or ``None`` if all endpoints fail."""
103
+ # 1. Static Pages JSON (Fastly CDN, no API rate limit).
104
+ data = _fetch_json(VERSION_JSON_URL, timeout)
105
+ if data and isinstance(data.get("version"), str) and data["version"].strip():
106
+ return _build_release_info(
107
+ current_version,
108
+ data["version"],
109
+ str(data.get("notes") or ""),
110
+ )
111
+
112
+ # 2. PyPI JSON endpoint (Fastly CDN, no rate limit).
113
+ data = _fetch_json(PYPI_JSON_URL, timeout)
114
+ info = data.get("info") if isinstance(data, dict) else None
115
+ if isinstance(info, dict) and isinstance(info.get("version"), str):
116
+ return _build_release_info(current_version, info["version"])
117
+
118
+ # 3. GitHub Releases API fallback.
119
+ data = _fetch_json(GITHUB_LATEST_URL, timeout)
120
+ if data and isinstance(data.get("tag_name"), str):
121
+ return _build_release_info(
122
+ current_version,
123
+ data["tag_name"],
124
+ str(data.get("body") or ""),
125
+ )
126
+ return None
127
+
128
+
129
+ def verify_sha256(
130
+ file_path: Path, expected_name: str, sums_text: str
131
+ ) -> bool:
132
+ """Verify ``file_path`` against ``SHA256SUMS.txt`` content."""
133
+ expected_hash: str | None = None
134
+ for line in (sums_text or "").splitlines():
135
+ parts = line.strip().split()
136
+ if len(parts) >= 2:
137
+ digest = parts[0].strip().lower()
138
+ name = parts[-1].lstrip("*./").strip()
139
+ if name == expected_name and re.fullmatch(r"[0-9a-f]{64}", digest):
140
+ expected_hash = digest
141
+ break
142
+ if not expected_hash:
143
+ return False
144
+ h = hashlib.sha256()
145
+ with file_path.open("rb") as fh:
146
+ while chunk := fh.read(65536):
147
+ h.update(chunk)
148
+ return h.hexdigest().lower() == expected_hash
149
+
150
+
151
+ def replace_running_executable(
152
+ new_file: Path, target_exe: Path | None = None
153
+ ) -> Path:
154
+ """Atomically swap ``new_file`` into ``target_exe`` without batch scripts."""
155
+ target = (target_exe or Path(sys.executable)).resolve()
156
+ old_path = target.with_suffix(target.suffix + ".old")
157
+ if old_path.exists():
158
+ with contextlib.suppress(OSError):
159
+ old_path.unlink()
160
+ os.replace(target, old_path)
161
+ try:
162
+ os.replace(new_file, target)
163
+ except Exception:
164
+ with contextlib.suppress(OSError):
165
+ os.replace(old_path, target)
166
+ raise
167
+ return target
168
+
169
+
170
+ def _download_bytes(url: str, timeout: float) -> bytes:
171
+ req = urllib.request.Request(
172
+ url, headers={"User-Agent": f"CodeYear/{__version__}"}
173
+ )
174
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
175
+ return resp.read()
176
+
177
+
178
+ def perform_update(
179
+ info: dict | None = None,
180
+ *,
181
+ timeout: float = 60.0,
182
+ ) -> tuple[bool, str]:
183
+ """Download and apply the latest update for either frozen exe or pip."""
184
+ if info is None:
185
+ info = check_update(timeout=min(timeout, 10.0))
186
+ if not info:
187
+ return False, i18n.tr("无法连接更新服务器,请检查网络。")
188
+ if not info.get("has_update"):
189
+ return True, i18n.tr(
190
+ "当前已是最新版本(v{version})。", version=info["current"]
191
+ )
192
+
193
+ latest = info["latest"]
194
+ if is_frozen():
195
+ target = Path(sys.executable).resolve()
196
+ tmp_path = target.with_suffix(target.suffix + ".tmp")
197
+ try:
198
+ payload = _download_bytes(info["exe_url"], timeout=timeout)
199
+ tmp_path.write_bytes(payload)
200
+ sums_text = ""
201
+ with contextlib.suppress(Exception):
202
+ sums_text = _download_bytes(
203
+ info["sums_url"], timeout=15.0
204
+ ).decode("utf-8", errors="replace")
205
+ if sums_text and not verify_sha256(
206
+ tmp_path, "CodeYear.exe", sums_text
207
+ ):
208
+ tmp_path.unlink(missing_ok=True)
209
+ return False, i18n.tr("安装包 SHA256 校验未通过,已取消更新。")
210
+ replace_running_executable(tmp_path, target)
211
+ return True, i18n.tr(
212
+ "已更新到 v{version},重新打开软件即可生效。", version=latest
213
+ )
214
+ except Exception as exc:
215
+ tmp_path.unlink(missing_ok=True)
216
+ return False, i18n.tr("更新失败: {exc}", exc=exc)
217
+
218
+ # Python / pip environment: install the release wheel directly.
219
+ proc = subprocess.run(
220
+ [
221
+ sys.executable,
222
+ "-m",
223
+ "pip",
224
+ "install",
225
+ "--upgrade",
226
+ info["wheel_url"],
227
+ ],
228
+ capture_output=True,
229
+ text=True,
230
+ encoding="utf-8",
231
+ errors="replace",
232
+ check=False,
233
+ creationflags=_NO_WINDOW,
234
+ )
235
+ if proc.returncode == 0:
236
+ return True, i18n.tr("已更新到 v{version}。", version=latest)
237
+ err = (proc.stderr or proc.stdout or "pip install failed").strip()
238
+ return False, i18n.tr("更新失败: {exc}", exc=err.splitlines()[-1])
codeyear/wizard.py ADDED
@@ -0,0 +1,221 @@
1
+ """Interactive terminal wizard for CodeYear.
2
+
3
+ The regular ``codeyear scan`` command stays non-interactive. Running
4
+ ``codeyear tui`` walks through directory selection, shows how many repos
5
+ were found, scans with a progress bar, and lets the user choose where the
6
+ outputs go. The desktop GUI lives in ``gui.py`` and shares the same runner.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import sys
13
+ import webbrowser
14
+ from datetime import date
15
+ from pathlib import Path
16
+
17
+ from . import i18n
18
+ from .config import load as load_config
19
+ from .runner import detect_identity, discover, render, report_path, scan
20
+ from .stats import fmt_human, fmt_int
21
+
22
+
23
+ def _ask(prompt: str, default: str = "") -> str:
24
+ hint = f" [{default}]" if default else ""
25
+ value = input(f"{i18n.tr(prompt)}{hint}: ").strip()
26
+ return value or default
27
+
28
+
29
+ def _yes(prompt: str, default: bool = True) -> bool:
30
+ hint = "Y/n" if default else "y/N"
31
+ value = input(f"{i18n.tr(prompt)} [{hint}]: ").strip().lower()
32
+ if not value:
33
+ return default
34
+ return value in {"y", "yes", "是"}
35
+
36
+
37
+ def _choose_roots(default_roots: list[str] | None = None) -> list[Path]:
38
+ roots: list[Path] = []
39
+ for raw in default_roots or []:
40
+ candidate = Path(raw).expanduser()
41
+ if candidate.is_dir():
42
+ resolved = candidate.resolve()
43
+ if resolved not in roots:
44
+ roots.append(resolved)
45
+ if not roots:
46
+ roots = [Path.cwd().resolve()]
47
+ print(i18n.tr("选择要扫描的目录。默认是当前目录,可以继续添加。"))
48
+ while True:
49
+ print("\n" + i18n.tr("已选择:"))
50
+ if roots:
51
+ for i, root in enumerate(roots, 1):
52
+ print(f" {i}. {root}")
53
+ else:
54
+ print(" " + i18n.tr("(空)"))
55
+ print("\n " + i18n.tr(
56
+ "[Enter] 开始 [a] 添加目录 [r] 删除 [c] 清空"
57
+ ))
58
+ command = input("> ").strip().lower()
59
+
60
+ if command == "":
61
+ if roots:
62
+ return roots
63
+ print(i18n.tr("至少选择一个目录。"))
64
+ continue
65
+ if command == "a":
66
+ path = Path(_ask("目录路径", str(Path.cwd()))).expanduser()
67
+ if not path.is_dir():
68
+ print(i18n.tr("这不是一个文件夹。"))
69
+ continue
70
+ path = path.resolve()
71
+ if path in roots:
72
+ print(i18n.tr("这个目录已经在列表里。"))
73
+ continue
74
+ roots.append(path)
75
+ continue
76
+ if command == "r":
77
+ if not roots:
78
+ continue
79
+ raw = _ask("删除第几个", "1")
80
+ try:
81
+ roots.pop(int(raw) - 1)
82
+ except (ValueError, IndexError):
83
+ print(i18n.tr("编号不对。"))
84
+ continue
85
+ if command == "c":
86
+ roots = []
87
+ continue
88
+ print(i18n.tr("未知选项。"))
89
+
90
+
91
+ def _progress(done: int, total: int, name: str) -> None:
92
+ if not sys.stderr.isatty():
93
+ if done:
94
+ print(f"[{done}/{total}] {name}", file=sys.stderr)
95
+ return
96
+ width = 28
97
+ filled = int(width * done / max(total, 1))
98
+ bar = "[" + "#" * filled + "-" * (width - filled) + f"] {done}/{total}"
99
+ name = name[:36]
100
+ sys.stderr.write("\r" + bar + " " + name.ljust(38))
101
+ sys.stderr.flush()
102
+ if done == total:
103
+ sys.stderr.write("\n")
104
+
105
+
106
+ def _open(path: Path) -> None:
107
+ try:
108
+ if hasattr(os, "startfile"):
109
+ os.startfile(str(path)) # type: ignore[attr-defined]
110
+ else:
111
+ webbrowser.open(path.resolve().as_uri())
112
+ except Exception as exc: # pragma: no cover - platform dependent
113
+ print(i18n.tr("无法自动打开报告: {exc}", exc=exc), file=sys.stderr)
114
+
115
+
116
+ def run() -> int:
117
+ try:
118
+ cfg = load_config()
119
+ roots = _choose_roots(cfg.get("roots"))
120
+ default_depth = int(cfg.get("max_depth", 6))
121
+ depth_raw = _ask("向下扫描层级(文件夹层数)", str(default_depth))
122
+ try:
123
+ depth = max(1, int(depth_raw))
124
+ except ValueError:
125
+ depth = default_depth
126
+
127
+ print("\n" + i18n.tr("正在查找 git 仓库…"))
128
+ repos = discover(roots, depth, exclude=cfg.get("exclude"))
129
+ print(i18n.tr("找到 {count} 个 git 仓库。", count=len(repos)))
130
+ if not repos:
131
+ print(i18n.tr("没有找到仓库,换个目录试试。"))
132
+ return 2
133
+
134
+ default_year = int(cfg.get("year", date.today().year))
135
+ year_raw = _ask("统计年份", str(default_year))
136
+ try:
137
+ year = int(year_raw)
138
+ except ValueError:
139
+ year = default_year
140
+
141
+ identity = detect_identity()
142
+ aliases: list[str] = list(cfg.get("aliases", []))
143
+ if identity:
144
+ email, name = identity
145
+ label = f"{name} <{email}>" if name and email else (email or name)
146
+ only_me_default = not bool(cfg.get("all_authors", False))
147
+ if not _yes(
148
+ i18n.tr("只统计你本人({label})?", label=label), only_me_default
149
+ ):
150
+ identity = None
151
+ else:
152
+ default_aliases = ", ".join(aliases)
153
+ extra = _ask("旧邮箱/名字(逗号分隔,可空)", default_aliases)
154
+ aliases = [item.strip() for item in extra.split(",") if item.strip()]
155
+ else:
156
+ print(i18n.tr("未检测到 git 身份,将统计所有作者。"))
157
+
158
+ out_raw = _ask("输出目录", str(cfg.get("out", "codeyear-output")))
159
+ out_dir = Path(out_raw).expanduser().resolve()
160
+ out_dir.mkdir(parents=True, exist_ok=True)
161
+ compare = _yes("同时统计去年,生成同比?", bool(cfg.get("compare", False)))
162
+ all_branches = _yes("统计所有分支/tag?", bool(cfg.get("all_branches", False)))
163
+ default_jobs = int(cfg.get("jobs", 1))
164
+ jobs_raw = _ask("并行扫描数", str(default_jobs))
165
+ try:
166
+ jobs = max(1, int(jobs_raw))
167
+ except ValueError:
168
+ jobs = default_jobs
169
+ open_after = _yes("完成后打开报告?", bool(cfg.get("open", True)))
170
+
171
+ stats, warnings = scan(
172
+ repos, roots, year, identity, aliases=aliases,
173
+ author=cfg.get("author"),
174
+ timeout=int(cfg.get("timeout", 300)),
175
+ progress=_progress, jobs=jobs, compare=compare,
176
+ use_mailmap=not bool(cfg.get("no_mailmap", False)),
177
+ all_branches=all_branches,
178
+ rolling=bool(cfg.get("rolling", False)),
179
+ )
180
+ if stats.commit_count == 0:
181
+ print("\n" + i18n.tr("{year} 年没有找到提交。", year=year))
182
+ return 3
183
+
184
+ written = render(
185
+ stats, out_dir,
186
+ card_theme=str(cfg.get("theme", "paper")),
187
+ lang=i18n.get_lang(),
188
+ )
189
+
190
+ print()
191
+ print(i18n.tr(
192
+ "CodeYear {year} · {title}",
193
+ year=year, title=stats.persona.title,
194
+ ))
195
+ print("-" * 46)
196
+ print(f"{i18n.tr('仓库'):<10}{stats.repo_count}")
197
+ print(f"{i18n.tr('提交'):<10}{fmt_int(stats.commit_count)}")
198
+ print(f"{i18n.tr('代码行'):<10}{fmt_human(stats.lines_changed)}")
199
+ print(i18n.tr(
200
+ "活跃 {days} 天 · 涉及 {count} 个文件",
201
+ days=stats.active_days, count=stats.file_count,
202
+ ))
203
+ print(f"{i18n.tr('输出'):<10}{out_dir}")
204
+ print("-" * 46)
205
+ for label, path in written:
206
+ print(f"{label:<9} {path.name}")
207
+
208
+ if warnings:
209
+ print()
210
+ print(i18n.tr("警告:"))
211
+ for warning in warnings:
212
+ print(f" - {warning}")
213
+
214
+ if open_after:
215
+ target = report_path(written, lang=i18n.get_lang())
216
+ if target:
217
+ _open(target)
218
+ return 0
219
+ except KeyboardInterrupt:
220
+ print("\n" + i18n.tr("已取消。"))
221
+ return 130