gitannals 0.1.0__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.
chronicle/cli.py ADDED
@@ -0,0 +1,306 @@
1
+ """命令行入口。
2
+
3
+ 一条命令跑完,中间不问问题。所有参数都有默认值。
4
+ `chronicle .` 出项目编年史,`chronicle . --view author` 出个人画像。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import sys
11
+ import webbrowser
12
+ from pathlib import Path
13
+
14
+ import typer
15
+ from rich.console import Console
16
+ from rich.panel import Panel
17
+ from rich.table import Table
18
+ from rich.text import Text
19
+
20
+ from . import __version__
21
+ from .analyze import AuthorLookupError, Options, analyze
22
+ from .config import load_settings
23
+ from .gitio import runner
24
+ from .gitio.runner import GitError
25
+
26
+ app = typer.Typer(
27
+ add_completion=False,
28
+ no_args_is_help=False,
29
+ rich_markup_mode="rich",
30
+ context_settings={"help_option_names": ["-h", "--help"]},
31
+ )
32
+
33
+ console = Console()
34
+
35
+ _DEFAULT_OUTPUT = {"project": "annals-report.html", "author": "annals-author.html"}
36
+
37
+
38
+ def _version_callback(value: bool) -> None:
39
+ if value:
40
+ console.print(f"gitannals {__version__}")
41
+ raise typer.Exit()
42
+
43
+
44
+ @app.command()
45
+ def main(
46
+ path: str = typer.Argument(".", help="本地 Git 仓库路径,默认当前目录。"),
47
+ view: str = typer.Option(
48
+ "project", "--view", help="视角:project 项目编年史 / author 个人开发者画像。"
49
+ ),
50
+ author: str | None = typer.Option(
51
+ None, "--author", "-a", help="画像对象:姓名或邮箱。多邮箱用逗号合并,如 a@x.com,b@y.com。"
52
+ ),
53
+ tone: str = typer.Option("tech", "--tone", "-t", help="叙事风格:tech 硬核纪实 / roast 毒舌吐槽。"),
54
+ no_ai: bool = typer.Option(False, "--no-ai", help="纯离线统计模式,不调用任何 LLM。"),
55
+ anon: bool = typer.Option(False, "--anon", help="脱敏:邮箱打码、作者名替换。"),
56
+ since: str | None = typer.Option(None, "--since", help="起始时间,如 2025-01-01。"),
57
+ until: str | None = typer.Option(None, "--until", help="结束时间。"),
58
+ output: Path | None = typer.Option(None, "--output", "-o", help="报告输出路径(.html)。"),
59
+ save_json: Path | None = typer.Option(None, "--json", help="额外导出中间态 Chronicle JSON。"),
60
+ open_browser: bool = typer.Option(False, "--open", help="生成完成后自动在浏览器打开。"),
61
+ lang: str = typer.Option("zh", "--lang", help="报告语言:zh / en。"),
62
+ all_branches: bool = typer.Option(False, "--all", help="分析所有分支,而非仅当前 HEAD。"),
63
+ follow_renames: bool = typer.Option(
64
+ False, "--follow-renames", help="开启重命名追踪(更准,但大仓库会明显变慢)。"
65
+ ),
66
+ ignore: list[str] = typer.Option(None, "--ignore", help="额外忽略的路径模式,可重复。"),
67
+ top_files: int = typer.Option(15, "--top-files", help="修罗场榜单长度。"),
68
+ model: str | None = typer.Option(None, "--model", help="LLM 模型名,覆盖配置。"),
69
+ base_url: str | None = typer.Option(None, "--base-url", help="OpenAI 兼容接口地址。"),
70
+ api_key: str | None = typer.Option(None, "--api-key", help="API Key,覆盖环境变量。"),
71
+ temperature: float | None = typer.Option(None, "--temperature", help="采样温度,默认 0.7。"),
72
+ quiet: bool = typer.Option(False, "--quiet", "-q", help="只输出结果,不打印过程。"),
73
+ version: bool = typer.Option(
74
+ False, "--version", "-V", callback=_version_callback, is_eager=True, help="显示版本号。"
75
+ ),
76
+ ) -> None:
77
+ """把一段 Git 历史,讲成一个能看的故事。"""
78
+ if view not in ("project", "author"):
79
+ console.print(f"[red]未知的 --view:{view},可选 project / author[/red]")
80
+ raise typer.Exit(2)
81
+ if tone not in ("tech", "roast"):
82
+ console.print(f"[red]未知的 --tone:{tone},可选 tech / roast[/red]")
83
+ raise typer.Exit(2)
84
+ if lang not in ("zh", "en"):
85
+ console.print(f"[red]未知的 --lang:{lang},可选 zh / en[/red]")
86
+ raise typer.Exit(2)
87
+
88
+ try:
89
+ root = runner.resolve_repo(path)
90
+ except GitError as exc:
91
+ console.print(f"[red]✗ {exc}[/red]")
92
+ raise typer.Exit(1) from exc
93
+
94
+ settings = load_settings(
95
+ root,
96
+ overrides={
97
+ "lang": lang,
98
+ "tone": tone,
99
+ "ignore": list(ignore or []),
100
+ "model": model,
101
+ "llm_base_url": base_url,
102
+ "api_key": api_key,
103
+ "temperature": temperature,
104
+ "no_ai": no_ai,
105
+ },
106
+ )
107
+
108
+ options = Options(
109
+ repo=root,
110
+ since=since,
111
+ until=until,
112
+ all_branches=all_branches,
113
+ follow_renames=follow_renames,
114
+ anon=anon,
115
+ lang=settings.lang,
116
+ tone=settings.tone,
117
+ ignore=settings.ignore,
118
+ top_files=top_files,
119
+ view=view,
120
+ author=author,
121
+ author_aliases=settings.author_aliases,
122
+ llm=settings.llm,
123
+ )
124
+
125
+ try:
126
+ if quiet:
127
+ report = analyze(options)
128
+ else:
129
+ with console.status("[dim]读取仓库…[/dim]", spinner="dots") as status:
130
+ report = analyze(
131
+ options, lambda _stage, detail: status.update(f"[dim]{detail}[/dim]")
132
+ )
133
+ except AuthorLookupError as exc:
134
+ console.print(f"[red]✗ {exc}[/red]")
135
+ for candidate in exc.candidates[:12]:
136
+ console.print(f" [dim]{candidate}[/dim]")
137
+ raise typer.Exit(2) from exc
138
+ except GitError as exc:
139
+ console.print(f"[red]✗ {exc}[/red]")
140
+ raise typer.Exit(1) from exc
141
+
142
+ is_author = view == "author"
143
+ total = report["persona"]["commits"] if is_author else report["overview"]["commits"]
144
+ if not total:
145
+ console.print(f"[yellow]{report['warnings'][0]}[/yellow]")
146
+ raise typer.Exit(2)
147
+
148
+ if save_json:
149
+ save_json.parent.mkdir(parents=True, exist_ok=True)
150
+ save_json.write_text(
151
+ json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8"
152
+ )
153
+ if not quiet:
154
+ console.print(f"[green]✓[/green] JSON 已写入 {save_json}")
155
+
156
+ target = output or Path(_DEFAULT_OUTPUT[view])
157
+ html_written = _try_render(report, target, quiet)
158
+
159
+ if not quiet:
160
+ _print_summary(report, is_author)
161
+
162
+ if html_written and open_browser:
163
+ webbrowser.open(target.resolve().as_uri())
164
+
165
+
166
+ def _try_render(report: dict, output: Path, quiet: bool) -> bool:
167
+ try:
168
+ from .render import build_html
169
+ except ImportError:
170
+ if not quiet:
171
+ console.print("[yellow]·[/yellow] 渲染层不可用,本次只做分析。用 --json 导出中间结果。")
172
+ return False
173
+
174
+ output.parent.mkdir(parents=True, exist_ok=True)
175
+ output.write_text(build_html(report), encoding="utf-8")
176
+ if not quiet:
177
+ size_kb = output.stat().st_size / 1024
178
+ console.print(f"[green]✓[/green] 报告已生成 {output} ({size_kb:.0f} KB)")
179
+ return True
180
+
181
+
182
+ def _print_summary(report: dict, is_author: bool) -> None:
183
+ console.print()
184
+ if is_author:
185
+ _print_author_summary(report)
186
+ else:
187
+ _print_project_summary(report)
188
+
189
+ ai = (report.get("meta") or {}).get("ai") or {}
190
+ if ai.get("used"):
191
+ console.print(
192
+ f"\n [dim]叙事由 {ai.get('model')} 生成,耗时 {ai.get('latency_ms')} ms[/dim]"
193
+ )
194
+ elif ai.get("reason") == "no_api_key" and not (report["meta"].get("options") or {}).get("no_ai"):
195
+ console.print(
196
+ "\n [dim]未找到 API Key,使用规则叙事。设置 CHRONICLE_API_KEY 可启用 LLM 旁白。[/dim]"
197
+ )
198
+
199
+ for warning in report.get("warnings") or []:
200
+ console.print(f"\n [yellow]· {warning}[/yellow]")
201
+
202
+
203
+ def _print_project_summary(report: dict) -> None:
204
+ overview = report["overview"]
205
+ meta = report["meta"]
206
+
207
+ title = Text()
208
+ title.append(meta["repo"]["name"] or "repository", style="bold")
209
+ if meta["repo"]["branch"]:
210
+ title.append(f" {meta['repo']['branch']}", style="dim")
211
+
212
+ grid = Table.grid(padding=(0, 3))
213
+ grid.add_column(justify="right", style="dim")
214
+ grid.add_column()
215
+ grid.add_row("提交", f"{overview['commits']:,}")
216
+ grid.add_row(
217
+ "新增 / 删除",
218
+ f"{_signed(overview['insertions'], '+')} / {_signed(overview['deletions'], '-')}",
219
+ )
220
+ grid.add_row("贡献者", f"{overview['authors']}")
221
+ grid.add_row("活跃天数", f"{overview['active_days']} / {overview['span_days']}")
222
+ console.print(Panel(grid, title=title, border_style="dim", padding=(0, 2)))
223
+
224
+ chapters = report.get("chapters") or []
225
+ if chapters:
226
+ table = Table(show_header=True, header_style="dim", box=None, pad_edge=False)
227
+ table.add_column("")
228
+ table.add_column("章节")
229
+ table.add_column("区间", style="dim")
230
+ table.add_column("提交", justify="right")
231
+ table.add_column("±行", justify="right")
232
+ for chapter in chapters:
233
+ table.add_row(
234
+ "·",
235
+ chapter["title"],
236
+ f"{chapter['start']} → {chapter['end']}",
237
+ str(chapter["commits"]),
238
+ f"{_signed(chapter['insertions'], '+')}/{_signed(chapter['deletions'], '-')}",
239
+ )
240
+ console.print()
241
+ console.print(table)
242
+
243
+ _print_facts(report)
244
+ if report.get("quote"):
245
+ console.print()
246
+ console.print(f" [italic dim]{report['quote']}[/italic dim]")
247
+
248
+
249
+ def _print_author_summary(report: dict) -> None:
250
+ persona = report["persona"]
251
+
252
+ title = Text()
253
+ title.append(persona["name"], style="bold")
254
+ title.append(f" {persona['email']}", style="dim")
255
+
256
+ grid = Table.grid(padding=(0, 3))
257
+ grid.add_column(justify="right", style="dim")
258
+ grid.add_column()
259
+ grid.add_row("提交", f"{persona['commits']:,}(占全仓库 {persona['share']}%)")
260
+ grid.add_row(
261
+ "新增 / 删除",
262
+ f"{_signed(persona['insertions'], '+')} / {_signed(persona['deletions'], '-')}",
263
+ )
264
+ grid.add_row("活跃天数", f"{persona['active_days']} / {persona['span_days']}")
265
+ grid.add_row("标签", "、".join(tag["label"] for tag in persona["tags"]) or "—")
266
+ console.print(Panel(grid, title=title, border_style="dim", padding=(0, 2)))
267
+
268
+ console.print()
269
+ console.print(f" [italic]{persona['verdict']}[/italic]")
270
+
271
+ if report.get("chapters"):
272
+ table = Table(show_header=True, header_style="dim", box=None, pad_edge=False)
273
+ table.add_column("阶段")
274
+ table.add_column("区间", style="dim")
275
+ table.add_column("参与", justify="right")
276
+ for phase in report["chapters"]:
277
+ table.add_row(
278
+ phase["title"],
279
+ f"{phase['start']} → {phase['end']}",
280
+ "—" if phase["absent"] else f"{phase['commits']}/{phase['chapter_commits']}",
281
+ )
282
+ console.print()
283
+ console.print(table)
284
+
285
+ _print_facts(report)
286
+ if report.get("quote"):
287
+ console.print()
288
+ console.print(f" [italic dim]{report['quote']}[/italic dim]")
289
+
290
+
291
+ def _signed(value: int, sign: str) -> str:
292
+ """零不带符号:「-0」看起来像 bug。"""
293
+ return f"{sign}{value:,}" if value else "0"
294
+
295
+
296
+ def _print_facts(report: dict) -> None:
297
+ facts = report.get("fun_facts") or []
298
+ if not facts:
299
+ return
300
+ console.print()
301
+ for fact in facts[:3]:
302
+ console.print(f" [dim]{fact['title']}[/dim] {fact['detail']}")
303
+
304
+
305
+ if __name__ == "__main__":
306
+ sys.exit(app())
chronicle/config.py ADDED
@@ -0,0 +1,132 @@
1
+ """配置合并。
2
+
3
+ 优先级:内置默认 < 仓库根的 `.chronicle.toml` < 环境变量 < 命令行参数。
4
+ 最后一条最重要 —— 显式传进来的参数永远该赢。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from dataclasses import dataclass, field
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ __all__ = ["Settings", "LlmSettings", "load_settings", "CONFIG_FILENAME"]
15
+
16
+ CONFIG_FILENAME = ".annals.toml"
17
+
18
+ DEFAULT_BASE_URL = "https://api.deepseek.com/v1"
19
+ DEFAULT_MODEL = "deepseek-chat"
20
+ # 按顺序找,先找到的先用
21
+ _API_KEY_ENVS = ("CHRONICLE_API_KEY", "DEEPSEEK_API_KEY", "OPENAI_API_KEY")
22
+
23
+
24
+ @dataclass(slots=True)
25
+ class LlmSettings:
26
+ base_url: str = DEFAULT_BASE_URL
27
+ model: str = DEFAULT_MODEL
28
+ api_key: str | None = None
29
+ timeout: float = 90.0
30
+ temperature: float = 0.7
31
+ max_tokens: int = 2000
32
+ enabled: bool = True
33
+ retries: int = 1
34
+
35
+ def ready(self) -> bool:
36
+ return self.enabled and bool(self.api_key)
37
+
38
+
39
+ @dataclass(slots=True)
40
+ class Settings:
41
+ lang: str = "zh"
42
+ tone: str = "tech"
43
+ ignore: list[str] = field(default_factory=list)
44
+ author_aliases: dict[str, list[str]] = field(default_factory=dict)
45
+ llm: LlmSettings = field(default_factory=LlmSettings)
46
+
47
+
48
+ def _read_toml(path: Path) -> dict[str, Any]:
49
+ try:
50
+ import tomllib # Python 3.11+
51
+ except ModuleNotFoundError: # pragma: no cover - 3.10 只损失配置文件能力
52
+ return {}
53
+ try:
54
+ with path.open("rb") as handle:
55
+ return tomllib.load(handle)
56
+ except (OSError, ValueError):
57
+ return {}
58
+
59
+
60
+ def load_settings(
61
+ repo_root: Path | None = None,
62
+ *,
63
+ overrides: dict[str, Any] | None = None,
64
+ ) -> Settings:
65
+ settings = Settings()
66
+ overrides = overrides or {}
67
+
68
+ if repo_root:
69
+ data = _read_toml(repo_root / CONFIG_FILENAME)
70
+ report_cfg = data.get("report") or {}
71
+ llm_cfg = data.get("llm") or {}
72
+
73
+ if isinstance(report_cfg.get("lang"), str):
74
+ settings.lang = report_cfg["lang"]
75
+ if isinstance(report_cfg.get("tone"), str):
76
+ settings.tone = report_cfg["tone"]
77
+ ignore = report_cfg.get("ignore")
78
+ if isinstance(ignore, list):
79
+ settings.ignore = [str(item) for item in ignore]
80
+
81
+ if isinstance(llm_cfg.get("base_url"), str):
82
+ settings.llm.base_url = llm_cfg["base_url"]
83
+ if isinstance(llm_cfg.get("model"), str):
84
+ settings.llm.model = llm_cfg["model"]
85
+ if isinstance(llm_cfg.get("timeout"), (int, float)):
86
+ settings.llm.timeout = float(llm_cfg["timeout"])
87
+ if isinstance(llm_cfg.get("temperature"), (int, float)):
88
+ settings.llm.temperature = float(llm_cfg["temperature"])
89
+ if isinstance(llm_cfg.get("enabled"), bool):
90
+ settings.llm.enabled = llm_cfg["enabled"]
91
+
92
+ author_cfg = data.get("author") or {}
93
+ alias_cfg = author_cfg.get("aliases") or {}
94
+ if isinstance(alias_cfg, dict):
95
+ settings.author_aliases = {
96
+ str(name): [str(email) for email in emails]
97
+ for name, emails in alias_cfg.items()
98
+ if isinstance(emails, list)
99
+ }
100
+
101
+ key_env = llm_cfg.get("api_key_env")
102
+ if isinstance(key_env, str) and os.environ.get(key_env):
103
+ settings.llm.api_key = os.environ[key_env]
104
+
105
+ if not settings.llm.api_key:
106
+ for name in _API_KEY_ENVS:
107
+ value = os.environ.get(name)
108
+ if value:
109
+ settings.llm.api_key = value
110
+ break
111
+
112
+ # 命令行覆盖
113
+ for name in ("lang", "tone"):
114
+ if overrides.get(name):
115
+ setattr(settings, name, overrides[name])
116
+ if overrides.get("ignore"):
117
+ settings.ignore = list(overrides["ignore"])
118
+
119
+ llm_overrides = {
120
+ "base_url": overrides.get("llm_base_url"),
121
+ "model": overrides.get("model"),
122
+ "api_key": overrides.get("api_key"),
123
+ "timeout": overrides.get("llm_timeout"),
124
+ "temperature": overrides.get("temperature"),
125
+ }
126
+ for key, value in llm_overrides.items():
127
+ if value not in (None, ""):
128
+ setattr(settings.llm, key, value)
129
+ if overrides.get("no_ai"):
130
+ settings.llm.enabled = False
131
+
132
+ return settings
@@ -0,0 +1,23 @@
1
+ """统计特征层。每个模块只吃 Commit 列表,吐 JSON-ready dict。"""
2
+
3
+ from . import (
4
+ churn,
5
+ contributors,
6
+ fun_facts,
7
+ languages,
8
+ milestones,
9
+ overview,
10
+ profile,
11
+ temporal,
12
+ )
13
+
14
+ __all__ = [
15
+ "churn",
16
+ "contributors",
17
+ "fun_facts",
18
+ "languages",
19
+ "milestones",
20
+ "overview",
21
+ "profile",
22
+ "temporal",
23
+ ]
@@ -0,0 +1,90 @@
1
+ """统计口径共用的数学与时间工具。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from datetime import date, datetime
7
+ from statistics import pstdev
8
+
9
+ __all__ = [
10
+ "pct",
11
+ "safe_div",
12
+ "round2",
13
+ "log_norm",
14
+ "mean",
15
+ "std",
16
+ "week_key",
17
+ "week_bounds",
18
+ "month_key",
19
+ "iter_month_keys",
20
+ "iter_week_keys",
21
+ ]
22
+
23
+
24
+ def pct(part: float, total: float, digits: int = 1) -> float:
25
+ if not total:
26
+ return 0.0
27
+ return round(part / total * 100, digits)
28
+
29
+
30
+ def safe_div(a: float, b: float, default: float = 0.0) -> float:
31
+ return a / b if b else default
32
+
33
+
34
+ def round2(value: float) -> float:
35
+ return round(value, 2)
36
+
37
+
38
+ def log_norm(value: float, ceiling: float) -> float:
39
+ """log1p 归一化到 0..1,防止单个超大文件把评分拉爆。"""
40
+ if ceiling <= 0:
41
+ return 0.0
42
+ return math.log1p(value) / math.log1p(ceiling)
43
+
44
+
45
+ def mean(values: list[float] | list[int]) -> float:
46
+ return sum(values) / len(values) if values else 0.0
47
+
48
+
49
+ def std(values: list[float] | list[int]) -> float:
50
+ return pstdev(values) if len(values) > 1 else 0.0
51
+
52
+
53
+ def week_key(day: date) -> str:
54
+ iso = day.isocalendar()
55
+ return f"{iso.year}-W{iso.week:02d}"
56
+
57
+
58
+ def week_bounds(day: date) -> tuple[date, date]:
59
+ monday = day.fromordinal(day.toordinal() - day.weekday())
60
+ return monday, date.fromordinal(monday.toordinal() + 6)
61
+
62
+
63
+ def month_key(day: date) -> str:
64
+ return f"{day.year}-{day.month:02d}"
65
+
66
+
67
+ def iter_month_keys(start: date, end: date) -> list[str]:
68
+ keys: list[str] = []
69
+ year, month = start.year, start.month
70
+ while (year, month) <= (end.year, end.month):
71
+ keys.append(f"{year}-{month:02d}")
72
+ month += 1
73
+ if month > 12:
74
+ year, month = year + 1, 1
75
+ return keys
76
+
77
+
78
+ def iter_week_keys(start: date, end: date) -> list[str]:
79
+ keys: list[str] = []
80
+ cursor = date.fromordinal(start.toordinal() - start.weekday())
81
+ stop = date.fromordinal(end.toordinal() - end.weekday())
82
+ while cursor <= stop:
83
+ keys.append(week_key(cursor))
84
+ cursor = date.fromordinal(cursor.toordinal() + 7)
85
+ return keys
86
+
87
+
88
+
89
+ def as_date(value: datetime) -> date:
90
+ return value.date()