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/__init__.py +6 -0
- chronicle/analyze.py +325 -0
- chronicle/clean.py +331 -0
- chronicle/cli.py +306 -0
- chronicle/config.py +132 -0
- chronicle/features/__init__.py +23 -0
- chronicle/features/_util.py +90 -0
- chronicle/features/churn.py +150 -0
- chronicle/features/contributors.py +100 -0
- chronicle/features/fun_facts.py +213 -0
- chronicle/features/languages.py +135 -0
- chronicle/features/milestones.py +435 -0
- chronicle/features/overview.py +81 -0
- chronicle/features/profile.py +382 -0
- chronicle/features/temporal.py +132 -0
- chronicle/gitio/__init__.py +5 -0
- chronicle/gitio/parse.py +135 -0
- chronicle/gitio/runner.py +120 -0
- chronicle/i18n.py +530 -0
- chronicle/identity.py +58 -0
- chronicle/models.py +80 -0
- chronicle/narrate/__init__.py +7 -0
- chronicle/narrate/client.py +124 -0
- chronicle/narrate/enhance.py +137 -0
- chronicle/narrate/prompt.py +232 -0
- chronicle/narrate/schema.py +133 -0
- chronicle/redact.py +301 -0
- chronicle/render/__init__.py +140 -0
- chronicle/render/charts.py +518 -0
- chronicle/render/templates/_style.css.j2 +80 -0
- chronicle/render/templates/author.html.j2 +318 -0
- chronicle/render/templates/report.html.j2 +407 -0
- gitannals-0.1.0.dist-info/METADATA +251 -0
- gitannals-0.1.0.dist-info/RECORD +37 -0
- gitannals-0.1.0.dist-info/WHEEL +4 -0
- gitannals-0.1.0.dist-info/entry_points.txt +2 -0
- gitannals-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
"""个人开发者画像。
|
|
2
|
+
|
|
3
|
+
和项目报告共用同一个 Git 遍历结果,只是换一个切面看:把「项目经历了什么」
|
|
4
|
+
换成「这个人在这个项目里是什么样」。
|
|
5
|
+
|
|
6
|
+
所有判断都是规则,且每条规则都能用报告里的数字反查 —— 画像最怕的是
|
|
7
|
+
「看起来很懂你,但其实在编」。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from collections import Counter, defaultdict
|
|
13
|
+
from collections.abc import Callable
|
|
14
|
+
from datetime import date
|
|
15
|
+
|
|
16
|
+
from ..clean import file_category
|
|
17
|
+
from ..i18n import t
|
|
18
|
+
from ..identity import KeyResolver, build_resolver
|
|
19
|
+
from ..models import Commit
|
|
20
|
+
from ._util import pct, round2
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"AuthorLookupError",
|
|
24
|
+
"resolve_aliases",
|
|
25
|
+
"resolve_author",
|
|
26
|
+
"build_persona",
|
|
27
|
+
"build_peers",
|
|
28
|
+
"chapter_participation",
|
|
29
|
+
"author_quote",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class AuthorLookupError(ValueError):
|
|
34
|
+
"""找不到人,或者匹配到多个。带候选列表,方便命令行直接打印。"""
|
|
35
|
+
|
|
36
|
+
def __init__(self, message: str, candidates: list[str] | None = None) -> None:
|
|
37
|
+
super().__init__(message)
|
|
38
|
+
self.candidates = candidates or []
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _index(commits: list[Commit], resolver: KeyResolver | None = None) -> dict[str, dict]:
|
|
42
|
+
resolver = resolver or build_resolver()
|
|
43
|
+
table: dict[str, dict] = {}
|
|
44
|
+
for commit in commits:
|
|
45
|
+
key = resolver.key(commit)
|
|
46
|
+
entry = table.setdefault(
|
|
47
|
+
key, {"names": Counter(), "emails": Counter(), "commits": 0}
|
|
48
|
+
)
|
|
49
|
+
entry["names"][commit.author] += 1
|
|
50
|
+
entry["emails"][commit.email.lower()] += 1
|
|
51
|
+
entry["commits"] += 1
|
|
52
|
+
return table
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def resolve_aliases(
|
|
56
|
+
query: str | None, aliases: dict[str, list[str]] | None
|
|
57
|
+
) -> tuple[str, dict[str, list[str]]]:
|
|
58
|
+
"""把 `--author a@x,b@y` 这种写法展开成别名表,返回 (首个查询词, 合并后的别名表)。
|
|
59
|
+
|
|
60
|
+
抽出来的原因:画像本身和「同路人」必须用同一份合并规则,否则那个人会
|
|
61
|
+
把自己算成自己的同事。
|
|
62
|
+
"""
|
|
63
|
+
parts = [part.strip() for part in (query or "").split(",") if part.strip()]
|
|
64
|
+
merged = dict(aliases or {})
|
|
65
|
+
if len(parts) > 1:
|
|
66
|
+
merged["__cli__"] = parts
|
|
67
|
+
return (parts[0] if parts else ""), merged
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def resolve_author(
|
|
71
|
+
commits: list[Commit],
|
|
72
|
+
query: str,
|
|
73
|
+
*,
|
|
74
|
+
aliases: dict[str, list[str]] | None = None,
|
|
75
|
+
lang: str = "zh",
|
|
76
|
+
) -> tuple[str, str, str, list[Commit]]:
|
|
77
|
+
"""按邮箱 / 姓名 / 邮箱前缀找人,返回 (key, 显示名, 邮箱, 该人的提交)。
|
|
78
|
+
|
|
79
|
+
query 用逗号分隔多个身份时,视为同一个人的多个邮箱,直接合并。
|
|
80
|
+
"""
|
|
81
|
+
parts = [part.strip() for part in (query or "").split(",") if part.strip()]
|
|
82
|
+
merged = dict(aliases or {})
|
|
83
|
+
if len(parts) > 1:
|
|
84
|
+
merged["__cli__"] = parts
|
|
85
|
+
|
|
86
|
+
resolver = build_resolver(merged)
|
|
87
|
+
table = _index(commits, resolver)
|
|
88
|
+
if not table:
|
|
89
|
+
raise AuthorLookupError(t("ui.err.no_commits", lang))
|
|
90
|
+
|
|
91
|
+
needle = (parts[0] if parts else "").lower()
|
|
92
|
+
if not needle:
|
|
93
|
+
raise AuthorLookupError(t("ui.err.need_author", lang))
|
|
94
|
+
|
|
95
|
+
key: str | None = None
|
|
96
|
+
if needle in table:
|
|
97
|
+
key = needle
|
|
98
|
+
else:
|
|
99
|
+
by_name = [k for k, e in table.items() if any(needle in n.lower() for n in e["names"])]
|
|
100
|
+
by_email = [k for k in table if needle in k]
|
|
101
|
+
matches = sorted(set(by_name) | set(by_email))
|
|
102
|
+
if len(matches) == 1:
|
|
103
|
+
key = matches[0]
|
|
104
|
+
elif len(matches) > 1:
|
|
105
|
+
raise AuthorLookupError(
|
|
106
|
+
t("ui.err.ambiguous", lang, q=query, n=len(matches)),
|
|
107
|
+
[_label(table[k]) for k in matches],
|
|
108
|
+
)
|
|
109
|
+
else:
|
|
110
|
+
raise AuthorLookupError(
|
|
111
|
+
t("ui.err.not_found", lang, q=query),
|
|
112
|
+
[_label(table[k]) for k in table],
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
entry = table[key]
|
|
116
|
+
name = entry["names"].most_common(1)[0][0]
|
|
117
|
+
email = entry["emails"].most_common(1)[0][0]
|
|
118
|
+
subset = [c for c in commits if resolver.key(c) == key]
|
|
119
|
+
return key, name, email, subset
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _label(entry: dict) -> str:
|
|
123
|
+
email = entry["emails"].most_common(1)[0][0]
|
|
124
|
+
name = entry["names"].most_common(1)[0][0]
|
|
125
|
+
return f"{name} <{email}>"
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _streak(days: list[date]) -> int:
|
|
129
|
+
best = current = 1
|
|
130
|
+
for previous, day in zip(days, days[1:]):
|
|
131
|
+
current = current + 1 if (day - previous).days == 1 else 1
|
|
132
|
+
best = max(best, current)
|
|
133
|
+
return best if days else 0
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def build_persona(
|
|
137
|
+
subset: list[Commit],
|
|
138
|
+
all_commits: list[Commit],
|
|
139
|
+
*,
|
|
140
|
+
key: str,
|
|
141
|
+
name: str,
|
|
142
|
+
email: str,
|
|
143
|
+
lang: str = "zh",
|
|
144
|
+
repo_authors: int = 1,
|
|
145
|
+
) -> dict:
|
|
146
|
+
if not subset:
|
|
147
|
+
raise AuthorLookupError(t("ui.err.no_person_commits", lang))
|
|
148
|
+
|
|
149
|
+
ordered = sorted(subset, key=lambda c: c.authored_at)
|
|
150
|
+
first, last = ordered[0].authored_at, ordered[-1].authored_at
|
|
151
|
+
days = sorted({c.authored_at.date() for c in subset})
|
|
152
|
+
span_days = (last.date() - first.date()).days + 1
|
|
153
|
+
|
|
154
|
+
insertions = sum(c.insertions for c in subset)
|
|
155
|
+
deletions = sum(c.deletions for c in subset)
|
|
156
|
+
kinds = Counter(c.kind for c in subset)
|
|
157
|
+
total = len(all_commits)
|
|
158
|
+
|
|
159
|
+
night = sum(1 for c in subset if c.authored_at.hour < 6)
|
|
160
|
+
weekend = sum(1 for c in subset if c.authored_at.weekday() >= 5)
|
|
161
|
+
hour_counts = Counter(c.authored_at.hour for c in subset)
|
|
162
|
+
peak_hour = hour_counts.most_common(1)[0][0] if hour_counts else 0
|
|
163
|
+
|
|
164
|
+
per_day: dict[date, int] = Counter(c.authored_at.date() for c in subset)
|
|
165
|
+
busiest_day, busiest_count = per_day.most_common(1)[0]
|
|
166
|
+
|
|
167
|
+
gaps = [(b - a).days for a, b in zip(days, days[1:])]
|
|
168
|
+
longest_gap = max(gaps) if gaps else 0
|
|
169
|
+
|
|
170
|
+
footprint = _footprint(subset)
|
|
171
|
+
avg_churn = (insertions + deletions) / max(1, len(subset))
|
|
172
|
+
|
|
173
|
+
persona = {
|
|
174
|
+
"key": key,
|
|
175
|
+
"name": name,
|
|
176
|
+
"email": email,
|
|
177
|
+
"commits": len(subset),
|
|
178
|
+
"share": pct(len(subset), total),
|
|
179
|
+
"insertions": insertions,
|
|
180
|
+
"deletions": deletions,
|
|
181
|
+
"net": insertions - deletions,
|
|
182
|
+
"active_days": len(days),
|
|
183
|
+
"span_days": span_days,
|
|
184
|
+
"span_start": first.date().isoformat(),
|
|
185
|
+
"span_end": last.date().isoformat(),
|
|
186
|
+
"first_commit_at": first.isoformat(),
|
|
187
|
+
"last_commit_at": last.isoformat(),
|
|
188
|
+
"avg_commits_per_active_day": round2(len(subset) / max(1, len(days))),
|
|
189
|
+
"avg_churn_per_commit": round2(avg_churn),
|
|
190
|
+
"night_ratio": pct(night, len(subset)),
|
|
191
|
+
"weekend_ratio": pct(weekend, len(subset)),
|
|
192
|
+
"peak_hour": peak_hour,
|
|
193
|
+
"streak_days": _streak(days),
|
|
194
|
+
"longest_gap_days": longest_gap,
|
|
195
|
+
"busiest_day": busiest_day.isoformat(),
|
|
196
|
+
"busiest_day_commits": busiest_count,
|
|
197
|
+
"kind_mix": [
|
|
198
|
+
{"kind": kind, "count": count, "share": pct(count, len(subset))}
|
|
199
|
+
for kind, count in kinds.most_common()
|
|
200
|
+
],
|
|
201
|
+
"dominant_kind": kinds.most_common(1)[0][0] if kinds else "other",
|
|
202
|
+
"top_dirs": footprint["dirs"],
|
|
203
|
+
"top_files": footprint["files"],
|
|
204
|
+
"repo_authors": repo_authors,
|
|
205
|
+
"repo_commits": total,
|
|
206
|
+
"repo_span_days": (
|
|
207
|
+
(max(c.authored_at for c in all_commits).date()
|
|
208
|
+
- min(c.authored_at for c in all_commits).date()).days + 1
|
|
209
|
+
),
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
persona["tags"] = _derive_tags(persona, lang)
|
|
213
|
+
persona["verdict"] = _verdict(persona, lang)
|
|
214
|
+
return persona
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _footprint(commits: list[Commit], *, limit: int = 5) -> dict:
|
|
218
|
+
dirs: Counter[str] = Counter()
|
|
219
|
+
files: Counter[str] = Counter()
|
|
220
|
+
for commit in commits:
|
|
221
|
+
for change in commit.changes:
|
|
222
|
+
parts = change.path.split("/")
|
|
223
|
+
dirs[parts[0] if len(parts) > 1 else "(root)"] += change.churn
|
|
224
|
+
files[change.path] += change.churn
|
|
225
|
+
return {
|
|
226
|
+
"dirs": [{"name": name, "churn": value} for name, value in dirs.most_common(limit)],
|
|
227
|
+
"files": [
|
|
228
|
+
{"path": path, "churn": value, "category": file_category(path)}
|
|
229
|
+
for path, value in files.most_common(limit)
|
|
230
|
+
],
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
# 标签规则:id, 判定, 权重。权重只用于排序,不做展示。
|
|
235
|
+
_TAG_RULES: tuple[tuple[str, Callable[[dict], bool], int], ...] = (
|
|
236
|
+
("night_owl", lambda p: p["night_ratio"] >= 15, 9),
|
|
237
|
+
("weekend_warrior", lambda p: p["weekend_ratio"] >= 18, 8),
|
|
238
|
+
("sprinter", lambda p: p["streak_days"] >= 5, 7),
|
|
239
|
+
("firefighter", lambda p: _kind_share(p, "fix", "revert") >= 28, 9),
|
|
240
|
+
("refactorer", lambda p: _kind_share(p, "refactor") >= 18, 8),
|
|
241
|
+
("documenter", lambda p: _kind_share(p, "docs") >= 22, 6),
|
|
242
|
+
("big_bang", lambda p: p["avg_churn_per_commit"] >= 400, 6),
|
|
243
|
+
("micro", lambda p: p["avg_churn_per_commit"] <= 60 and p["commits"] >= 15, 6),
|
|
244
|
+
("anchor", lambda p: p["share"] >= 40, 10),
|
|
245
|
+
("lone_wolf", lambda p: p["share"] >= 70 and p["repo_authors"] > 1, 7),
|
|
246
|
+
("ghost", lambda p: p["active_days"] / max(1, p["span_days"]) < 0.15, 5),
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _kind_share(persona: dict, *kinds: str) -> float:
|
|
251
|
+
return sum(
|
|
252
|
+
item["share"] for item in persona["kind_mix"] if item["kind"] in kinds
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _derive_tags(persona: dict, lang: str, limit: int = 3) -> list[dict]:
|
|
257
|
+
tags: list[dict] = []
|
|
258
|
+
probe = persona
|
|
259
|
+
for tag_id, rule, weight in _TAG_RULES:
|
|
260
|
+
try:
|
|
261
|
+
if rule(probe):
|
|
262
|
+
tags.append({"id": tag_id, "label": t(f"persona.tag.{tag_id}", lang), "weight": weight})
|
|
263
|
+
except (KeyError, ZeroDivisionError):
|
|
264
|
+
continue
|
|
265
|
+
tags.sort(key=lambda item: -item["weight"])
|
|
266
|
+
return [{"id": item["id"], "label": item["label"]} for item in tags[:limit]]
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _verdict(persona: dict, lang: str) -> str:
|
|
270
|
+
tag = persona["tags"][0]["id"] if persona["tags"] else "default"
|
|
271
|
+
key = f"persona.verdict.{tag}"
|
|
272
|
+
fallback = "persona.verdict.default"
|
|
273
|
+
text = t(key, lang, **{
|
|
274
|
+
"name": persona["name"],
|
|
275
|
+
"commits": persona["commits"],
|
|
276
|
+
"share": persona["share"],
|
|
277
|
+
"night": persona["night_ratio"],
|
|
278
|
+
"weekend": persona["weekend_ratio"],
|
|
279
|
+
"streak": persona["streak_days"],
|
|
280
|
+
"days": persona["span_days"],
|
|
281
|
+
"churn": f"{int(persona['avg_churn_per_commit'])}",
|
|
282
|
+
})
|
|
283
|
+
if text == key:
|
|
284
|
+
text = t(fallback, lang, name=persona["name"], commits=persona["commits"],
|
|
285
|
+
share=persona["share"], days=persona["span_days"])
|
|
286
|
+
return text
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def build_peers(
|
|
290
|
+
all_commits: list[Commit],
|
|
291
|
+
key: str,
|
|
292
|
+
*,
|
|
293
|
+
limit: int = 5,
|
|
294
|
+
aliases: dict[str, list[str]] | None = None,
|
|
295
|
+
) -> list[dict]:
|
|
296
|
+
"""同路人:按「共同动过的文件数」衡量协作密度。"""
|
|
297
|
+
resolver = build_resolver(aliases)
|
|
298
|
+
table = _index(all_commits, resolver)
|
|
299
|
+
mine: set[str] = set()
|
|
300
|
+
for commit in all_commits:
|
|
301
|
+
if resolver.key(commit) == key:
|
|
302
|
+
mine.update(change.path for change in commit.changes)
|
|
303
|
+
if not mine:
|
|
304
|
+
return []
|
|
305
|
+
|
|
306
|
+
overlap: dict[str, set[str]] = defaultdict(set)
|
|
307
|
+
for commit in all_commits:
|
|
308
|
+
other = resolver.key(commit)
|
|
309
|
+
if other == key:
|
|
310
|
+
continue
|
|
311
|
+
overlap[other].update(change.path for change in commit.changes)
|
|
312
|
+
|
|
313
|
+
rows = []
|
|
314
|
+
for other, files in overlap.items():
|
|
315
|
+
shared = mine & files
|
|
316
|
+
if not shared:
|
|
317
|
+
continue
|
|
318
|
+
entry = table.get(other) or {"names": Counter(), "emails": Counter(), "commits": 0}
|
|
319
|
+
email = entry["emails"].most_common(1)[0][0]
|
|
320
|
+
name = entry["names"].most_common(1)[0][0]
|
|
321
|
+
rows.append(
|
|
322
|
+
{
|
|
323
|
+
"name": name,
|
|
324
|
+
"email": email,
|
|
325
|
+
"commits": entry["commits"],
|
|
326
|
+
"shared_files": len(shared),
|
|
327
|
+
"overlap": pct(len(shared), len(mine)),
|
|
328
|
+
}
|
|
329
|
+
)
|
|
330
|
+
rows.sort(key=lambda r: (-r["shared_files"], -r["commits"]))
|
|
331
|
+
return rows[:limit]
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def chapter_participation(
|
|
335
|
+
chapters: list[dict], subset: list[Commit], *, lang: str
|
|
336
|
+
) -> list[dict]:
|
|
337
|
+
"""把项目章节映射到这个人身上:他参与了哪几段,各占多少。"""
|
|
338
|
+
rows = []
|
|
339
|
+
for chapter in chapters:
|
|
340
|
+
lo, hi = date.fromisoformat(chapter["start"]), date.fromisoformat(chapter["end"])
|
|
341
|
+
mine = [c for c in subset if lo <= c.authored_at.date() <= hi]
|
|
342
|
+
if not mine:
|
|
343
|
+
rows.append(
|
|
344
|
+
{
|
|
345
|
+
"id": chapter["id"],
|
|
346
|
+
"title": chapter["title"],
|
|
347
|
+
"start": chapter["start"],
|
|
348
|
+
"end": chapter["end"],
|
|
349
|
+
"commits": 0,
|
|
350
|
+
"share": 0.0,
|
|
351
|
+
"chapter_commits": chapter["commits"],
|
|
352
|
+
"absent": True,
|
|
353
|
+
}
|
|
354
|
+
)
|
|
355
|
+
continue
|
|
356
|
+
rows.append(
|
|
357
|
+
{
|
|
358
|
+
"id": chapter["id"],
|
|
359
|
+
"title": chapter["title"],
|
|
360
|
+
"start": chapter["start"],
|
|
361
|
+
"end": chapter["end"],
|
|
362
|
+
"commits": len(mine),
|
|
363
|
+
"share": pct(len(mine), chapter["commits"]),
|
|
364
|
+
"chapter_commits": chapter["commits"],
|
|
365
|
+
"absent": False,
|
|
366
|
+
}
|
|
367
|
+
)
|
|
368
|
+
return rows
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def author_quote(persona: dict, *, lang: str = "zh", tone: str = "tech") -> str:
|
|
372
|
+
key = "persona.quote.roast" if tone == "roast" else "persona.quote.tech"
|
|
373
|
+
return t(
|
|
374
|
+
key,
|
|
375
|
+
lang,
|
|
376
|
+
name=persona["name"],
|
|
377
|
+
commits=persona["commits"],
|
|
378
|
+
share=persona["share"],
|
|
379
|
+
days=persona["span_days"],
|
|
380
|
+
insertions=f"{persona['insertions']:,}",
|
|
381
|
+
deletions=f"{persona['deletions']:,}",
|
|
382
|
+
)
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""时间维度:活跃度序列 + 开发作息热力图。
|
|
2
|
+
|
|
3
|
+
两条硬性要求:
|
|
4
|
+
1. 时间序列必须**补齐空桶**。缺周的折线图会把「停了三个月」画成「平滑过渡」,
|
|
5
|
+
那是最容易骗到自己的失真。
|
|
6
|
+
2. 作息用作者本地时区(%aI 自带偏移),不要换算 UTC —— 深夜提交是人的行为,
|
|
7
|
+
不是服务器的行为。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from collections import Counter, defaultdict
|
|
13
|
+
from datetime import date
|
|
14
|
+
|
|
15
|
+
from ..i18n import weekdays
|
|
16
|
+
from ..models import Commit
|
|
17
|
+
from ._util import (
|
|
18
|
+
iter_month_keys,
|
|
19
|
+
iter_week_keys,
|
|
20
|
+
month_key,
|
|
21
|
+
pct,
|
|
22
|
+
week_bounds,
|
|
23
|
+
week_key,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
__all__ = ["build_timeline", "build_rhythm"]
|
|
27
|
+
|
|
28
|
+
# 周数超过这个值就换成按月聚合,否则横轴密到没法看
|
|
29
|
+
_MAX_WEEKS = 130
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def build_timeline(commits: list[Commit]) -> dict:
|
|
33
|
+
if not commits:
|
|
34
|
+
return {"granularity": "week", "points": [], "totals": {"commits": 0}}
|
|
35
|
+
|
|
36
|
+
ordered = sorted(commits, key=lambda c: c.authored_at)
|
|
37
|
+
first_day = ordered[0].authored_at.date()
|
|
38
|
+
last_day = ordered[-1].authored_at.date()
|
|
39
|
+
|
|
40
|
+
week_keys = iter_week_keys(first_day, last_day)
|
|
41
|
+
granularity = "week" if len(week_keys) <= _MAX_WEEKS else "month"
|
|
42
|
+
keys = week_keys if granularity == "week" else iter_month_keys(first_day, last_day)
|
|
43
|
+
|
|
44
|
+
buckets: dict[str, dict[str, int]] = {
|
|
45
|
+
key: {"commits": 0, "insertions": 0, "deletions": 0} for key in keys
|
|
46
|
+
}
|
|
47
|
+
authors: dict[str, set[str]] = defaultdict(set)
|
|
48
|
+
|
|
49
|
+
for commit in ordered:
|
|
50
|
+
day = commit.authored_at.date()
|
|
51
|
+
key = week_key(day) if granularity == "week" else month_key(day)
|
|
52
|
+
bucket = buckets.get(key)
|
|
53
|
+
if bucket is None:
|
|
54
|
+
continue
|
|
55
|
+
bucket["commits"] += 1
|
|
56
|
+
bucket["insertions"] += commit.insertions
|
|
57
|
+
bucket["deletions"] += commit.deletions
|
|
58
|
+
authors[key].add(commit.email.lower())
|
|
59
|
+
|
|
60
|
+
points = []
|
|
61
|
+
for key in keys:
|
|
62
|
+
bucket = buckets[key]
|
|
63
|
+
start, end = _bounds(key, granularity)
|
|
64
|
+
points.append(
|
|
65
|
+
{
|
|
66
|
+
"key": key,
|
|
67
|
+
"label": key if granularity == "week" else key,
|
|
68
|
+
"start": start.isoformat(),
|
|
69
|
+
"end": end.isoformat(),
|
|
70
|
+
"commits": bucket["commits"],
|
|
71
|
+
"insertions": bucket["insertions"],
|
|
72
|
+
"deletions": bucket["deletions"],
|
|
73
|
+
"churn": bucket["insertions"] + bucket["deletions"],
|
|
74
|
+
"authors": len(authors[key]),
|
|
75
|
+
}
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
return {
|
|
79
|
+
"granularity": granularity,
|
|
80
|
+
"points": points,
|
|
81
|
+
"totals": {
|
|
82
|
+
"commits": sum(p["commits"] for p in points),
|
|
83
|
+
"insertions": sum(p["insertions"] for p in points),
|
|
84
|
+
"deletions": sum(p["deletions"] for p in points),
|
|
85
|
+
},
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _bounds(key: str, granularity: str) -> tuple[date, date]:
|
|
90
|
+
if granularity == "week":
|
|
91
|
+
year, week = key.split("-W")
|
|
92
|
+
monday = date.fromisocalendar(int(year), int(week), 1)
|
|
93
|
+
return monday, date.fromordinal(monday.toordinal() + 6)
|
|
94
|
+
year, month = (int(part) for part in key.split("-"))
|
|
95
|
+
start = date(year, month, 1)
|
|
96
|
+
end = date(year + (month == 12), 1 if month == 12 else month + 1, 1)
|
|
97
|
+
return start, date.fromordinal(end.toordinal() - 1)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def build_rhythm(commits: list[Commit], *, lang: str = "zh") -> dict:
|
|
101
|
+
labels = weekdays(lang)
|
|
102
|
+
matrix = [[0] * 24 for _ in range(7)]
|
|
103
|
+
for commit in commits:
|
|
104
|
+
moment = commit.authored_at
|
|
105
|
+
matrix[moment.weekday()][moment.hour] += 1
|
|
106
|
+
|
|
107
|
+
total = len(commits)
|
|
108
|
+
hourly = [sum(matrix[dow][hour] for dow in range(7)) for hour in range(24)]
|
|
109
|
+
weekday = [sum(matrix[dow]) for dow in range(7)]
|
|
110
|
+
|
|
111
|
+
peak_dow = max(range(7), key=lambda d: weekday[d]) if total else 0
|
|
112
|
+
peak_hour = max(range(24), key=lambda h: hourly[h]) if total else 0
|
|
113
|
+
|
|
114
|
+
night = sum(hourly[0:6])
|
|
115
|
+
weekend = weekday[5] + weekday[6]
|
|
116
|
+
|
|
117
|
+
return {
|
|
118
|
+
"matrix": matrix,
|
|
119
|
+
"hourly": hourly,
|
|
120
|
+
"weekday": weekday,
|
|
121
|
+
"total": total,
|
|
122
|
+
"peak": {
|
|
123
|
+
"dow": peak_dow,
|
|
124
|
+
"hour": peak_hour,
|
|
125
|
+
"count": matrix[peak_dow][peak_hour],
|
|
126
|
+
"label": f"{labels[peak_dow]} {peak_hour:02d}:00",
|
|
127
|
+
},
|
|
128
|
+
"night_ratio": pct(night, total),
|
|
129
|
+
"weekend_ratio": pct(weekend, total),
|
|
130
|
+
"weekday_labels": list(labels),
|
|
131
|
+
"max_cell": max((max(row) for row in matrix), default=0),
|
|
132
|
+
}
|
chronicle/gitio/parse.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""`git log --numstat` 的单次遍历解析器。
|
|
2
|
+
|
|
3
|
+
为什么不是逐 commit 调 `git show --numstat`:
|
|
4
|
+
后者是 O(n) 个子进程,一万条提交就要几千次进程创建,慢两个数量级。
|
|
5
|
+
这里一次 `git log` 走完整段历史,边读边解析。
|
|
6
|
+
|
|
7
|
+
格式用不可见控制符做分隔,避免 commit message 里的任意字符撞分隔符:
|
|
8
|
+
\\x1e (RS) 记录开始 \\x1f (FS) 字段分隔
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from collections.abc import Iterator
|
|
14
|
+
from datetime import datetime
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from ..models import Commit, FileChange
|
|
18
|
+
from .runner import GitError, stream
|
|
19
|
+
|
|
20
|
+
__all__ = ["iter_raw_commits", "normalize_renamed_path"]
|
|
21
|
+
|
|
22
|
+
_RS = "\x1e"
|
|
23
|
+
_FS = "\x1f"
|
|
24
|
+
# 注意:%s 是单行 subject,不含换行,因此可以安全地放在同一行格式串里。
|
|
25
|
+
# 正文(%b)含换行,会破坏按行解析,v1 不取。
|
|
26
|
+
_HEADER = _RS + _FS.join(["%H", "%P", "%an", "%ae", "%aI", "%cI", "%s"])
|
|
27
|
+
_FIELD_COUNT = 7
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def normalize_renamed_path(path: str) -> str:
|
|
31
|
+
"""把 numstat 里的重命名写法收敛成新路径。
|
|
32
|
+
|
|
33
|
+
`src/{old => new}/x.py` -> `src/new/x.py`
|
|
34
|
+
`a.py => b.py` -> `b.py`
|
|
35
|
+
"""
|
|
36
|
+
if "=>" not in path:
|
|
37
|
+
return path
|
|
38
|
+
if "{" in path and "}" in path:
|
|
39
|
+
head, rest = path.split("{", 1)
|
|
40
|
+
middle, tail = rest.split("}", 1)
|
|
41
|
+
new_part = middle.split("=>", 1)[1].strip()
|
|
42
|
+
return f"{head}{new_part}{tail}".replace("//", "/")
|
|
43
|
+
return path.split("=>", 1)[1].strip()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _parse_numstat_line(line: str) -> FileChange | None:
|
|
47
|
+
parts = line.split("\t", 2)
|
|
48
|
+
if len(parts) != 3:
|
|
49
|
+
return None
|
|
50
|
+
raw_ins, raw_del, path = parts
|
|
51
|
+
path = normalize_renamed_path(path.strip())
|
|
52
|
+
if not path:
|
|
53
|
+
return None
|
|
54
|
+
binary = raw_ins == "-" or raw_del == "-"
|
|
55
|
+
insertions = 0 if binary else int(raw_ins)
|
|
56
|
+
deletions = 0 if binary else int(raw_del)
|
|
57
|
+
return FileChange(path=path, insertions=insertions, deletions=deletions, binary=binary)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def iter_raw_commits(
|
|
61
|
+
repo: Path,
|
|
62
|
+
*,
|
|
63
|
+
since: str | None = None,
|
|
64
|
+
until: str | None = None,
|
|
65
|
+
all_branches: bool = False,
|
|
66
|
+
follow_renames: bool = False,
|
|
67
|
+
) -> Iterator[Commit]:
|
|
68
|
+
"""按 git 默认顺序(新到旧)产出提交,changes 尚未做噪音过滤。"""
|
|
69
|
+
args = ["log", "--numstat", f"--format={_HEADER}"]
|
|
70
|
+
# 默认关闭重命名检测:它是日志遍历里最贵的一步,只在需要时开。
|
|
71
|
+
args.append("-M" if follow_renames else "--no-renames")
|
|
72
|
+
if since:
|
|
73
|
+
args.append(f"--since={since}")
|
|
74
|
+
if until:
|
|
75
|
+
args.append(f"--until={until}")
|
|
76
|
+
if all_branches:
|
|
77
|
+
args.append("--all")
|
|
78
|
+
|
|
79
|
+
current: dict[str, object] | None = None
|
|
80
|
+
changes: list[FileChange] = []
|
|
81
|
+
|
|
82
|
+
for line in stream(repo, args):
|
|
83
|
+
if line.startswith(_RS):
|
|
84
|
+
if current is not None:
|
|
85
|
+
yield _build(current, changes)
|
|
86
|
+
current = _parse_header(line)
|
|
87
|
+
changes = []
|
|
88
|
+
continue
|
|
89
|
+
if not line.strip():
|
|
90
|
+
continue
|
|
91
|
+
if current is None:
|
|
92
|
+
continue
|
|
93
|
+
change = _parse_numstat_line(line)
|
|
94
|
+
if change is not None:
|
|
95
|
+
changes.append(change)
|
|
96
|
+
|
|
97
|
+
if current is not None:
|
|
98
|
+
yield _build(current, changes)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _parse_header(line: str) -> dict[str, object]:
|
|
102
|
+
fields = line[1:].split(_FS)
|
|
103
|
+
if len(fields) < _FIELD_COUNT:
|
|
104
|
+
fields += [""] * (_FIELD_COUNT - len(fields))
|
|
105
|
+
sha, parents, author, email, authored, committed, subject = fields[:_FIELD_COUNT]
|
|
106
|
+
return {
|
|
107
|
+
"sha": sha,
|
|
108
|
+
"parents": tuple(p for p in parents.split() if p),
|
|
109
|
+
"author": author,
|
|
110
|
+
"email": email,
|
|
111
|
+
"authored_at": _parse_dt(authored),
|
|
112
|
+
"committed_at": _parse_dt(committed),
|
|
113
|
+
"subject": subject,
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _parse_dt(value: str) -> datetime:
|
|
118
|
+
"""%aI / %cI 带本地时区偏移,fromisoformat 可直接吃。"""
|
|
119
|
+
try:
|
|
120
|
+
return datetime.fromisoformat(value)
|
|
121
|
+
except ValueError as exc:
|
|
122
|
+
raise GitError(f"无法解析提交时间:{value!r}") from exc
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _build(header: dict[str, object], changes: list[FileChange]) -> Commit:
|
|
126
|
+
return Commit(
|
|
127
|
+
sha=str(header["sha"]),
|
|
128
|
+
parents=header["parents"], # type: ignore[arg-type]
|
|
129
|
+
author=str(header["author"]),
|
|
130
|
+
email=str(header["email"]),
|
|
131
|
+
authored_at=header["authored_at"], # type: ignore[arg-type]
|
|
132
|
+
committed_at=header["committed_at"], # type: ignore[arg-type]
|
|
133
|
+
subject=str(header["subject"]),
|
|
134
|
+
changes=changes,
|
|
135
|
+
)
|