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.
@@ -0,0 +1,435 @@
1
+ """里程碑检测与章节切分。
2
+
3
+ 关键取舍:章节边界**不交给 LLM**。
4
+ 在「提交频次 + 代码波动」两条序列上跑滑窗突变检测,得到候选断点,再按
5
+ 最小间隔贪心挑选。LLM 只负责给已切好的段起名字、写旁白 —— 这样同样的仓库
6
+ 跑两次结果一致,评审、复盘、CI 都能复现。
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections import Counter, defaultdict
12
+ from datetime import date, datetime
13
+
14
+ from ..i18n import chapter_archetypes, t
15
+ from ..models import Commit
16
+ from ._util import mean, pct, round2, std
17
+
18
+ __all__ = ["build_chapters", "detect_breakpoints", "build_events"]
19
+
20
+ _MIN_SEGMENT = 3 # 每章至少 3 个时间桶
21
+ _MAX_CHAPTERS = 6
22
+ _GAP_DAYS = 21 # 超过三周没提交,视为一次「沉默」
23
+ _DEP_FILES = frozenset(
24
+ {
25
+ "pyproject.toml",
26
+ "setup.py",
27
+ "setup.cfg",
28
+ "requirements.txt",
29
+ "requirements-dev.txt",
30
+ "Pipfile",
31
+ "poetry.lock",
32
+ "package.json",
33
+ "Cargo.toml",
34
+ "go.mod",
35
+ "pom.xml",
36
+ "build.gradle",
37
+ "build.gradle.kts",
38
+ "composer.json",
39
+ "Gemfile",
40
+ "Dockerfile",
41
+ "docker-compose.yml",
42
+ "environment.yml",
43
+ }
44
+ )
45
+
46
+
47
+ def _change_scores(values: list[float], window: int) -> list[float]:
48
+ """滑窗均值差 / 全窗标准差。值越大,说明这个位置前后「画风」变化越剧烈。"""
49
+ n = len(values)
50
+ scores = [0.0] * n
51
+ if n < _MIN_SEGMENT * 2:
52
+ return scores
53
+ for i in range(n):
54
+ before = values[max(0, i - window) : i]
55
+ after = values[i : min(n, i + window)]
56
+ if len(before) < 2 or len(after) < 2:
57
+ continue
58
+ spread = std(values[max(0, i - window) : min(n, i + window)])
59
+ scores[i] = abs(mean(after) - mean(before)) / (spread + 1e-9)
60
+ return scores
61
+
62
+
63
+ def detect_breakpoints(points: list[dict], max_breaks: int) -> list[dict]:
64
+ """在时间桶序列上找候选断点,返回按 index 升序的断点列表。"""
65
+ n = len(points)
66
+ if n < _MIN_SEGMENT * 2 or max_breaks <= 0:
67
+ return []
68
+
69
+ window = max(2, min(6, n // 4))
70
+ commits = [float(p["commits"]) for p in points]
71
+ churn = [float(p["churn"]) for p in points]
72
+
73
+ sc = _change_scores(commits, window)
74
+ sk = _change_scores(churn, window)
75
+ combined = [0.6 * a + 0.4 * b for a, b in zip(sc, sk)]
76
+
77
+ candidates = [
78
+ (i, score)
79
+ for i, score in enumerate(combined)
80
+ if _MIN_SEGMENT <= i <= n - _MIN_SEGMENT and score > 0
81
+ ]
82
+ candidates.sort(key=lambda pair: -pair[1])
83
+
84
+ chosen: list[int] = []
85
+ for index, _score in candidates:
86
+ if len(chosen) >= max_breaks:
87
+ break
88
+ if all(abs(index - other) >= _MIN_SEGMENT for other in chosen):
89
+ chosen.append(index)
90
+
91
+ chosen.sort()
92
+ return [
93
+ {
94
+ "index": index,
95
+ "key": points[index]["key"],
96
+ "date": points[index]["start"],
97
+ "score": round2(combined[index]),
98
+ }
99
+ for index in chosen
100
+ ]
101
+
102
+
103
+ def build_chapters(
104
+ commits: list[Commit],
105
+ points: list[dict],
106
+ *,
107
+ lang: str = "zh",
108
+ granularity: str = "week",
109
+ ) -> dict:
110
+ if not commits:
111
+ return {"chapters": [], "breakpoints": [], "empty_reason": "no_commits"}
112
+
113
+ if len(points) < _MIN_SEGMENT * 2:
114
+ return {
115
+ "chapters": [_single_chapter(commits, points, lang, granularity)],
116
+ "breakpoints": [],
117
+ "flat": True,
118
+ }
119
+
120
+ max_breaks = min(_MAX_CHAPTERS - 1, max(1, len(points) // 8))
121
+ breakpoints = detect_breakpoints(points, max_breaks)
122
+
123
+ bounds = [0] + [bp["index"] for bp in breakpoints] + [len(points)]
124
+ segments = [(bounds[i], bounds[i + 1]) for i in range(len(bounds) - 1)]
125
+
126
+ chapters = []
127
+ prev_end: date | None = None
128
+ for order, (start_idx, end_idx) in enumerate(segments):
129
+ chunk = points[start_idx:end_idx]
130
+ chapter = _build_chapter(
131
+ commits, chunk, order=order, lang=lang, granularity=granularity, prev_end=prev_end
132
+ )
133
+ if chapter is None:
134
+ continue
135
+ chapters.append(chapter)
136
+ prev_end = date.fromisoformat(chapter["end"])
137
+
138
+ # 切碎的小段落(少于 3 天或 0 提交)并回上一章,否则报告里全是残章
139
+ merged = _merge_tiny(chapters)
140
+ _dedupe_titles(merged)
141
+
142
+ return {"chapters": merged, "breakpoints": breakpoints, "flat": len(merged) <= 1}
143
+
144
+
145
+ def _dedupe_titles(chapters: list[dict]) -> None:
146
+ """同一个原型出现多次时加罗马数字后缀,否则目录里会连着两行「功能扩张期」。"""
147
+ roman = ["", " Ⅱ", " Ⅲ", " Ⅳ", " Ⅴ", " Ⅵ", " Ⅶ"]
148
+ seen: Counter[str] = Counter()
149
+ for chapter in chapters:
150
+ archetype = chapter["archetype"]
151
+ seen[archetype] += 1
152
+ count = seen[archetype]
153
+ if count > 1:
154
+ chapter["title"] = chapter["title"] + roman[min(count - 1, len(roman) - 1)]
155
+
156
+
157
+ def _chapter_commits(commits: list[Commit], start: str, end: str) -> list[Commit]:
158
+ lo, hi = date.fromisoformat(start), date.fromisoformat(end)
159
+ return [c for c in commits if lo <= c.authored_at.date() <= hi]
160
+
161
+
162
+ def _build_chapter(
163
+ commits: list[Commit],
164
+ chunk: list[dict],
165
+ *,
166
+ order: int,
167
+ lang: str,
168
+ granularity: str,
169
+ prev_end: date | None,
170
+ ) -> dict | None:
171
+ if not chunk:
172
+ return None
173
+ start, end = chunk[0]["start"], chunk[-1]["end"]
174
+ members = _chapter_commits(commits, start, end)
175
+ if not members:
176
+ return None
177
+
178
+ insertions = sum(c.insertions for c in members)
179
+ deletions = sum(c.deletions for c in members)
180
+ authors = {c.email.lower() for c in members}
181
+ span_days = (date.fromisoformat(end) - date.fromisoformat(start)).days + 1
182
+ weeks = max(1.0, span_days / 7)
183
+ per_week = round2(len(members) / weeks)
184
+ fix_count = sum(1 for c in members if c.kind in ("fix", "revert"))
185
+ fix_share = pct(fix_count, len(members))
186
+ total_lines = insertions + deletions
187
+ del_ratio = (deletions / total_lines) if total_lines else 0.0
188
+ gap_before = (date.fromisoformat(start) - prev_end).days if prev_end else 0
189
+
190
+ dirs = _top_dirs(members, limit=3)
191
+ archetype = _classify(
192
+ order=order,
193
+ per_week=per_week,
194
+ del_ratio=del_ratio,
195
+ fix_share=fix_share,
196
+ gap_before=gap_before,
197
+ span_days=span_days,
198
+ )
199
+
200
+ names = chapter_archetypes(lang)
201
+ summary = t(
202
+ "chapter.summary",
203
+ lang,
204
+ commits=len(members),
205
+ insertions=f"{insertions:,}",
206
+ deletions=f"{deletions:,}",
207
+ authors=len(authors),
208
+ )
209
+ if dirs:
210
+ summary += t("chapter.summary_dirs", lang, dirs="、".join(dirs))
211
+
212
+ return {
213
+ "id": f"ch{order + 1:02d}",
214
+ "archetype": archetype,
215
+ "title": names.get(archetype, archetype),
216
+ "start": start,
217
+ "end": end,
218
+ "span_days": span_days,
219
+ "weeks": round2(weeks),
220
+ "commits": len(members),
221
+ "insertions": insertions,
222
+ "deletions": deletions,
223
+ "net": insertions - deletions,
224
+ "authors": len(authors),
225
+ "commits_per_week": per_week,
226
+ "fix_share": fix_share,
227
+ "delete_ratio": pct(deletions, total_lines),
228
+ "gap_before_days": gap_before,
229
+ "top_dirs": dirs,
230
+ "granularity": granularity,
231
+ "summary": summary,
232
+ "narrative": _narrative(
233
+ archetype=archetype,
234
+ lang=lang,
235
+ start=start,
236
+ per_week=per_week,
237
+ insertions=insertions,
238
+ deletions=deletions,
239
+ commits=len(members),
240
+ fix_share=fix_share,
241
+ gap=gap_before,
242
+ ),
243
+ }
244
+
245
+
246
+ def _classify(
247
+ *,
248
+ order: int,
249
+ per_week: float,
250
+ del_ratio: float,
251
+ fix_share: float,
252
+ gap_before: int,
253
+ span_days: int,
254
+ ) -> str:
255
+ """用四个信号判断这一章的「画风」。
256
+
257
+ 顺序有讲究:空档 > 起点 > 低活跃 > 大删除 > 高频修复 > 高速扩张 > 稳态。
258
+ 把「沉寂」排在「重构」前面,是因为四个月只提交六次的项目,主线是沉寂,
259
+ 不是重构 —— 即使它确实删了很多行。
260
+ """
261
+ if gap_before >= _GAP_DAYS:
262
+ return "renaissance" if per_week >= 1.5 else "silence"
263
+ if order == 0:
264
+ return "genesis"
265
+ if per_week < 0.6 and span_days >= 28:
266
+ return "dormant"
267
+ if del_ratio >= 0.42 and per_week >= 0.25:
268
+ return "refactor"
269
+ if fix_share >= 35:
270
+ return "firefight"
271
+ if per_week >= 2.5:
272
+ return "expansion"
273
+ return "steady"
274
+
275
+
276
+ def _narrative(
277
+ *,
278
+ archetype: str,
279
+ lang: str,
280
+ start: str,
281
+ per_week: float,
282
+ insertions: int,
283
+ deletions: int,
284
+ commits: int,
285
+ fix_share: float,
286
+ gap: int,
287
+ ) -> str:
288
+ key = f"chapter.narrative.{archetype}"
289
+ return t(
290
+ key,
291
+ lang,
292
+ start=start,
293
+ per_week=per_week,
294
+ insertions=f"{insertions:,}",
295
+ deletions=f"{deletions:,}",
296
+ commits=commits,
297
+ fix_share=f"{fix_share:.0f}%",
298
+ gap=gap,
299
+ )
300
+
301
+
302
+ def _single_chapter(commits: list[Commit], points: list[dict], lang: str, granularity: str) -> dict:
303
+ ordered = sorted(commits, key=lambda c: c.authored_at)
304
+ start = ordered[0].authored_at.date().isoformat()
305
+ end = ordered[-1].authored_at.date().isoformat()
306
+ insertions = sum(c.insertions for c in commits)
307
+ deletions = sum(c.deletions for c in commits)
308
+ names = chapter_archetypes(lang)
309
+ return {
310
+ "id": "ch01",
311
+ "archetype": "steady",
312
+ "title": names.get("steady", "steady"),
313
+ "start": start,
314
+ "end": end,
315
+ "span_days": (date.fromisoformat(end) - date.fromisoformat(start)).days + 1,
316
+ "weeks": round2(max(1.0, (date.fromisoformat(end) - date.fromisoformat(start)).days / 7)),
317
+ "commits": len(commits),
318
+ "insertions": insertions,
319
+ "deletions": deletions,
320
+ "net": insertions - deletions,
321
+ "authors": len({c.email.lower() for c in commits}),
322
+ "commits_per_week": round2(len(commits)),
323
+ "fix_share": pct(sum(1 for c in commits if c.kind == "fix"), len(commits)),
324
+ "delete_ratio": pct(deletions, insertions + deletions),
325
+ "gap_before_days": 0,
326
+ "top_dirs": _top_dirs(commits, limit=3),
327
+ "granularity": granularity,
328
+ "summary": t(
329
+ "chapter.summary",
330
+ lang,
331
+ commits=len(commits),
332
+ insertions=f"{insertions:,}",
333
+ deletions=f"{deletions:,}",
334
+ authors=len({c.email.lower() for c in commits}),
335
+ ),
336
+ "narrative": t(
337
+ "chapter.narrative.flat",
338
+ lang,
339
+ commits=len(commits),
340
+ days=(date.fromisoformat(end) - date.fromisoformat(start)).days + 1,
341
+ ),
342
+ }
343
+
344
+
345
+ def _merge_tiny(chapters: list[dict]) -> list[dict]:
346
+ if len(chapters) <= 1:
347
+ return chapters
348
+ merged: list[dict] = []
349
+ for chapter in chapters:
350
+ if merged and (chapter["commits"] == 0 or chapter["span_days"] < 3):
351
+ prev = merged[-1]
352
+ for field in ("commits", "insertions", "deletions"):
353
+ prev[field] += chapter[field]
354
+ prev["end"] = chapter["end"]
355
+ prev["span_days"] = (
356
+ datetime.fromisoformat(prev["end"]) - datetime.fromisoformat(prev["start"])
357
+ ).days + 1
358
+ continue
359
+ merged.append(chapter)
360
+ for index, chapter in enumerate(merged):
361
+ chapter["id"] = f"ch{index + 1:02d}"
362
+ chapter["net"] = chapter["insertions"] - chapter["deletions"]
363
+ return merged
364
+
365
+
366
+ def _top_dirs(commits: list[Commit], limit: int) -> list[str]:
367
+ counter: Counter[str] = Counter()
368
+ for commit in commits:
369
+ for change in commit.changes:
370
+ parts = change.path.split("/")
371
+ name = parts[0] if len(parts) > 1 else "(root)"
372
+ counter[name] += change.churn
373
+ return [name for name, _ in counter.most_common(limit)]
374
+
375
+
376
+ def build_events(
377
+ commits: list[Commit], chapters: list[dict], *, lang: str = "zh", limit: int = 12
378
+ ) -> list[dict]:
379
+ """时间轴上的高亮节点。不追求全,只挑「值得停下来看一眼」的。"""
380
+ if not commits:
381
+ return []
382
+
383
+ events: list[dict] = []
384
+ seen: set[str] = set()
385
+
386
+ def push(commit: Commit, label: str, metric: str) -> None:
387
+ if commit.sha in seen or len(events) >= limit:
388
+ return
389
+ seen.add(commit.sha)
390
+ events.append(
391
+ {
392
+ "date": commit.authored_at.date().isoformat(),
393
+ "sha": commit.sha,
394
+ "short_sha": commit.short_sha,
395
+ "author": commit.author,
396
+ "subject": commit.subject,
397
+ "kind": commit.kind,
398
+ "label": label,
399
+ "label_text": t(f"event.{label}", lang),
400
+ "metric": metric,
401
+ }
402
+ )
403
+
404
+ # 1. 批量导入 —— 历史事故现场,通常值得单独标出来
405
+ for commit in sorted(
406
+ (c for c in commits if c.is_bulk), key=lambda c: -c.dropped_churn
407
+ )[:2]:
408
+ push(commit, "bulk_import", f"{commit.dropped_churn:,} lines")
409
+
410
+ # 2. 依赖清单变更 —— 通常是技术栈转向的信号
411
+ dep_commits = [
412
+ c
413
+ for c in commits
414
+ if any(change.path.rsplit("/", 1)[-1] in _DEP_FILES for change in c.changes)
415
+ ]
416
+ for commit in sorted(dep_commits, key=lambda c: -c.churn)[:2]:
417
+ push(commit, "deps", f"{commit.churn} lines")
418
+
419
+ # 3. 单条最大变更
420
+ for commit in sorted(commits, key=lambda c: -c.churn)[:3]:
421
+ push(commit, "big_commit", f"+{commit.insertions}/-{commit.deletions}")
422
+
423
+ # 4. 回滚
424
+ for commit in [c for c in commits if c.kind == "revert"][:2]:
425
+ push(commit, "revert", commit.subject[:40])
426
+
427
+ # 5. 每章的第一条提交(章节起点)
428
+ for chapter in chapters:
429
+ lo, hi = date.fromisoformat(chapter["start"]), date.fromisoformat(chapter["end"])
430
+ in_range = [c for c in commits if lo <= c.authored_at.date() <= hi]
431
+ if in_range:
432
+ push(min(in_range, key=lambda c: c.authored_at), "chapter_start", chapter["title"])
433
+
434
+ events.sort(key=lambda e: e["date"])
435
+ return events
@@ -0,0 +1,81 @@
1
+ """全貌指标与提交类型分布。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import Counter
6
+
7
+ from ..clean import normalize_author_key
8
+ from ..models import Commit
9
+ from ._util import pct
10
+
11
+ __all__ = ["build"]
12
+
13
+
14
+ def build(commits: list[Commit]) -> dict:
15
+ if not commits:
16
+ return {
17
+ "commits": 0,
18
+ "commits_code": 0,
19
+ "merges": 0,
20
+ "insertions": 0,
21
+ "deletions": 0,
22
+ "net": 0,
23
+ "bulk_commits": 0,
24
+ "bulk_insertions": 0,
25
+ "bulk_deletions": 0,
26
+ "bulk_files": 0,
27
+ "files_touched": 0,
28
+ "span_days": 0,
29
+ "active_days": 0,
30
+ "authors": 0,
31
+ "avg_commits_per_active_day": 0.0,
32
+ "first_commit_at": None,
33
+ "last_commit_at": None,
34
+ "by_kind": {},
35
+ "author_commits": [],
36
+ }
37
+
38
+ ordered = sorted(commits, key=lambda c: c.authored_at)
39
+ first, last = ordered[0].authored_at, ordered[-1].authored_at
40
+
41
+ active_days = {c.authored_at.date() for c in commits}
42
+ files: set[str] = set()
43
+ for commit in commits:
44
+ files.update(change.path for change in commit.changes)
45
+
46
+ author_keys = {normalize_author_key(c.author, c.email) for c in commits}
47
+ author_counts = Counter(normalize_author_key(c.author, c.email) for c in commits)
48
+ kinds = Counter(c.kind for c in commits)
49
+ insertions = sum(c.insertions for c in commits)
50
+ deletions = sum(c.deletions for c in commits)
51
+ span_days = (last.date() - first.date()).days + 1
52
+
53
+ bulk_commits = sum(1 for c in commits if c.is_bulk)
54
+ bulk_files = sum(len(c.dropped) for c in commits)
55
+ bulk_insertions = sum(d.insertions for c in commits for d in c.dropped)
56
+ bulk_deletions = sum(d.deletions for c in commits for d in c.dropped)
57
+
58
+ return {
59
+ "commits": len(commits),
60
+ "commits_code": sum(1 for c in commits if c.is_code_commit),
61
+ "merges": sum(1 for c in commits if c.is_merge),
62
+ "insertions": insertions,
63
+ "deletions": deletions,
64
+ "net": insertions - deletions,
65
+ "bulk_commits": bulk_commits,
66
+ "bulk_insertions": bulk_insertions,
67
+ "bulk_deletions": bulk_deletions,
68
+ "bulk_files": bulk_files,
69
+ "files_touched": len(files),
70
+ "span_days": span_days,
71
+ "active_days": len(active_days),
72
+ "authors": len(author_keys),
73
+ "avg_commits_per_active_day": round(len(commits) / max(1, len(active_days)), 2),
74
+ "first_commit_at": first.isoformat(),
75
+ "last_commit_at": last.isoformat(),
76
+ "by_kind": {
77
+ kind: {"count": count, "share": pct(count, len(commits))}
78
+ for kind, count in kinds.most_common()
79
+ },
80
+ "author_commits": [count for _, count in author_counts.most_common()],
81
+ }