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/stats.py ADDED
@@ -0,0 +1,736 @@
1
+ """Aggregate per-repo commit data into one report."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections import Counter
7
+ from dataclasses import asdict, dataclass, field
8
+ from datetime import date, datetime, timedelta
9
+
10
+ from .keywords import extract_keywords
11
+ from .languages import is_code_language
12
+ from .personas import Persona, build_persona
13
+ from .scanner import Commit, RepoResult
14
+
15
+ WEEKDAY_LABELS = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
16
+
17
+ KNOWN_TYPES: set[str] = {
18
+ "feat", "fix", "docs", "style", "refactor", "perf", "test", "tests",
19
+ "build", "ci", "chore", "revert", "release", "hotfix", "wip", "merge",
20
+ "remove", "add", "update", "improve", "init",
21
+ }
22
+
23
+ ZH_TYPES: dict[str, str] = {
24
+ "修复": "fix", "修正": "fix", "解决": "fix",
25
+ "新增": "feat", "添加": "feat", "增加": "feat", "支持": "feat",
26
+ "更新": "chore", "优化": "perf", "重构": "refactor",
27
+ "文档": "docs", "测试": "test", "构建": "build", "发布": "release",
28
+ "删除": "remove", "移除": "remove", "合并": "merge", "回滚": "revert",
29
+ }
30
+
31
+ _CONV_RE = re.compile(r"^\s*([A-Za-z]+)(?:\([^)]*\))?!?:\s*")
32
+ _ZH_RE = re.compile(r"^\s*([\u4e00-\u9fff]{2})[::]\s*")
33
+
34
+
35
+ @dataclass
36
+ class ReportStats:
37
+ year: int
38
+ root: str
39
+ generated_at: str
40
+ repo_count: int
41
+ new_repos: int
42
+ total_commits: int
43
+ tags_in_year: int
44
+ earliest_dt: datetime | None
45
+ repo_names: list[str]
46
+ commit_count: int
47
+ insertions: int
48
+ deletions: int
49
+ lines_changed: int
50
+ file_count: int
51
+ active_days: int
52
+ longest_streak: int
53
+ current_streak: int
54
+ first_dt: datetime | None
55
+ last_dt: datetime | None
56
+ by_hour: list[int]
57
+ by_weekday: list[int]
58
+ monthly: list[int]
59
+ hour_weekday: list[list[int]]
60
+ size_buckets: list[tuple[str, int]]
61
+ busiest_week: tuple[str, int] | None
62
+ busiest_week_start: str | None
63
+ longest_gap: tuple[int, str, str] | None
64
+ largest_commit: dict | None
65
+ largest_deletion: dict | None
66
+ avg_subject_len: int
67
+ conventional_share: float
68
+ weekend_share: float
69
+ night_share: float
70
+ first_commit: dict | None
71
+ last_commit: dict | None
72
+ sessions: dict
73
+ message_buckets: list[tuple[str, int]]
74
+ language_quarters: list[dict]
75
+ dormant: list[dict]
76
+ avg_files_per_commit: float
77
+ daily: dict[str, int]
78
+ languages: list[tuple[str, int]]
79
+ top_files: list[tuple[str, int]]
80
+ keywords: list[tuple[str, int]]
81
+ commit_types: list[tuple[str, int]]
82
+ repo_commits: list[tuple[str, int]]
83
+ busiest_day: tuple[str, int] | None
84
+ busiest_count: int
85
+ longest_subject: str
86
+ language_count: int
87
+ repo_details: list[dict]
88
+ ticker: list[dict]
89
+ identity_label: str
90
+ filtered_commits: int
91
+ persona: Persona
92
+ warnings: list[str]
93
+ previous: dict | None = None
94
+ top_deleted_files: list[tuple[str, int]] = field(default_factory=list)
95
+ latest_night_commit: dict | None = None
96
+
97
+ def as_dict(self) -> dict:
98
+ data = asdict(self)
99
+ data["first_dt"] = self.first_dt.isoformat() if self.first_dt else None
100
+ data["last_dt"] = self.last_dt.isoformat() if self.last_dt else None
101
+ data["earliest_dt"] = self.earliest_dt.isoformat() if self.earliest_dt else None
102
+ return data
103
+
104
+ @property
105
+ def public_source(self) -> bool:
106
+ """True when stats came from the optional public GitHub mode."""
107
+ return self.root.startswith(("https://github.com/", "http://github.com/"))
108
+
109
+
110
+ def compare_summary(current: ReportStats, previous: ReportStats) -> dict:
111
+ def pct(now: int | float, before: int | float) -> float | None:
112
+ return (now - before) / before if before else None
113
+
114
+ return {
115
+ "year": previous.year,
116
+ # 去年原始值:0 提交时无法做同比,报告据此降级展示
117
+ "previous_commits": previous.commit_count,
118
+ "previous_lines": previous.lines_changed,
119
+ "previous_insertions": previous.insertions,
120
+ "previous_deletions": previous.deletions,
121
+ "previous_active_days": previous.active_days,
122
+ "previous_repos": previous.repo_count,
123
+ "previous_streak": previous.longest_streak,
124
+ "previous_avg_subject_len": previous.avg_subject_len,
125
+ "previous_weekend_share": previous.weekend_share,
126
+ "previous_night_share": previous.night_share,
127
+ "previous_monthly": list(previous.monthly),
128
+ # 今年 - 去年
129
+ "commits": current.commit_count - previous.commit_count,
130
+ "commits_pct": pct(current.commit_count, previous.commit_count),
131
+ "lines": current.lines_changed - previous.lines_changed,
132
+ "lines_pct": pct(current.lines_changed, previous.lines_changed),
133
+ "insertions": current.insertions - previous.insertions,
134
+ "insertions_pct": pct(current.insertions, previous.insertions),
135
+ "deletions": current.deletions - previous.deletions,
136
+ "deletions_pct": pct(current.deletions, previous.deletions),
137
+ "active_days": current.active_days - previous.active_days,
138
+ "active_days_pct": pct(current.active_days, previous.active_days),
139
+ "repos": current.repo_count - previous.repo_count,
140
+ "repos_pct": pct(current.repo_count, previous.repo_count),
141
+ "streak": current.longest_streak - previous.longest_streak,
142
+ "streak_pct": pct(current.longest_streak, previous.longest_streak),
143
+ "avg_subject_len": current.avg_subject_len - previous.avg_subject_len,
144
+ "avg_subject_len_pct": pct(
145
+ current.avg_subject_len, previous.avg_subject_len
146
+ ),
147
+ "weekend_share": current.weekend_share - previous.weekend_share,
148
+ "night_share": current.night_share - previous.night_share,
149
+ }
150
+
151
+
152
+ def fmt_int(n: int) -> str:
153
+ return f"{int(n):,}"
154
+
155
+
156
+ def fmt_human(n: int) -> str:
157
+ n = int(n)
158
+ if abs(n) >= 100_000_000:
159
+ return f"{n / 100_000_000:.1f}亿"
160
+ if abs(n) >= 10_000:
161
+ return f"{n / 10_000:.1f}万"
162
+ return f"{n:,}"
163
+
164
+
165
+ def fmt_pct(value: float) -> str:
166
+ return f"{value * 100:.0f}%"
167
+
168
+
169
+ def fmt_signed_pair(insertions: int, deletions: int) -> str:
170
+ """Keep +additions / -deletions on the same unit scale."""
171
+ if max(insertions, deletions) >= 10_000:
172
+ return f"+{insertions / 10_000:.1f}万 / -{deletions / 10_000:.1f}万"
173
+ return f"+{insertions:,} / -{deletions:,}"
174
+
175
+
176
+ def parse_daily(daily: dict[str, int]) -> dict[date, int]:
177
+ return {date.fromisoformat(k): v for k, v in daily.items()}
178
+
179
+
180
+ def date_window(stats: ReportStats) -> tuple[date, date]:
181
+ """Return the (start, end) date range for heatmaps and lifecycle charts."""
182
+ if stats.first_dt and stats.first_dt.year < stats.year:
183
+ end = max(
184
+ date.today(),
185
+ stats.last_dt.date() if stats.last_dt else date.today(),
186
+ )
187
+ return end - timedelta(days=364), end
188
+ return date(stats.year, 1, 1), date(stats.year, 12, 31)
189
+
190
+
191
+ def _commit_type(subject: str) -> str | None:
192
+ m = _CONV_RE.match(subject)
193
+ if m:
194
+ t = m.group(1).lower()
195
+ # Only real Conventional Commit types. A subject such as
196
+ # "traffic: ..." must not turn into a fake type.
197
+ return t if t in KNOWN_TYPES else None
198
+ m = _ZH_RE.match(subject)
199
+ if m:
200
+ return ZH_TYPES.get(m.group(1))
201
+ return None
202
+
203
+
204
+ def language_breakdown(
205
+ languages: list[tuple[str, int]],
206
+ *,
207
+ limit: int = 8,
208
+ min_share: float = 0.01,
209
+ ) -> tuple[list[tuple[str, int]], int]:
210
+ """Top languages plus an "其他" bucket, dropping invisible slivers."""
211
+ total = sum(v for _, v in languages) or 1
212
+ rows = [(name, n) for name, n in languages if n / total >= min_share][:limit]
213
+ rest = total - sum(n for _, n in rows)
214
+ if rest > 0 and rest / total >= min_share:
215
+ rows.append(("其他", rest))
216
+ return rows, total
217
+
218
+
219
+ def _streaks(active_dates: list[date], year: int) -> tuple[int, int]:
220
+ longest = 0
221
+ run = 0
222
+ prev: date | None = None
223
+ for d in active_dates:
224
+ if prev is not None and (d - prev).days == 1:
225
+ run += 1
226
+ else:
227
+ run = 1
228
+ longest = max(longest, run)
229
+ prev = d
230
+
231
+ current = 0
232
+ today = date.today()
233
+ if year == today.year:
234
+ cursor = today
235
+ if cursor not in set(active_dates):
236
+ cursor -= timedelta(days=1)
237
+ active = set(active_dates)
238
+ while cursor in active:
239
+ current += 1
240
+ cursor -= timedelta(days=1)
241
+ return longest, current
242
+
243
+
244
+ def _is_mine(
245
+ commit: Commit,
246
+ identity: tuple[str, str],
247
+ aliases: list[str] | None = None,
248
+ ) -> bool:
249
+ email, name = identity
250
+ email_l = commit.author_email.strip().lower()
251
+ name_l = commit.author_name.strip().lower()
252
+ for value in [email, name, *(aliases or [])]:
253
+ value = (value or "").strip().lower()
254
+ if value and (email_l == value or name_l == value):
255
+ return True
256
+ return False
257
+
258
+
259
+ def build_stats(
260
+ *,
261
+ year: int,
262
+ root: str,
263
+ repos: list[RepoResult],
264
+ warnings: list[str] | None = None,
265
+ identity: tuple[str, str] | None = None,
266
+ aliases: list[str] | None = None,
267
+ ) -> ReportStats:
268
+ warnings = list(warnings or [])
269
+ aliases = [alias.strip() for alias in (aliases or []) if alias.strip()]
270
+ filtered_commits = 0
271
+ identity_label = ""
272
+ if identity:
273
+ email, name = identity
274
+ identity_label = f"{name} <{email}>" if name and email else (email or name)
275
+ commits: list[Commit] = []
276
+ lang_counter: Counter[str] = Counter()
277
+ file_counter: Counter[str] = Counter()
278
+ deleted_file_counter: Counter[str] = Counter()
279
+ repo_counter: Counter[str] = Counter()
280
+ file_set: set[tuple[str, str]] = set()
281
+
282
+ # Backups and copies of the same repo share commit hashes. Keep the
283
+ # largest copy first and count every hash once, so a "projects" folder
284
+ # full of snapshots does not inflate the report.
285
+ # Copies of the same project (same first commit or same remote) should read
286
+ # as one project. A work/backup folder full of clones then collapses into
287
+ # the biggest copy instead of showing up as several repos.
288
+ parent = list(range(len(repos)))
289
+
290
+ def find(i: int) -> int:
291
+ while parent[i] != i:
292
+ parent[i] = parent[parent[i]]
293
+ i = parent[i]
294
+ return i
295
+
296
+ def union(a: int, b: int) -> None:
297
+ ra, rb = find(a), find(b)
298
+ if ra != rb:
299
+ parent[rb] = ra
300
+
301
+ buckets: dict[str, int] = {}
302
+ for i, repo in enumerate(repos):
303
+ keys: list[str] = []
304
+ if repo.root:
305
+ keys.append("root:" + repo.root)
306
+ remote = (repo.remote or "").strip().lower().removesuffix(".git")
307
+ if remote:
308
+ keys.append("remote:" + remote)
309
+ for key in keys:
310
+ if key in buckets:
311
+ union(i, buckets[key])
312
+ else:
313
+ buckets[key] = i
314
+
315
+ grouped: dict[int, list[RepoResult]] = {}
316
+ for i, repo in enumerate(repos):
317
+ grouped.setdefault(find(i), []).append(repo)
318
+ chosen = [
319
+ max(group, key=lambda r: (len(r.commits), -len(r.name)))
320
+ for group in grouped.values()
321
+ ]
322
+
323
+ ordered = sorted(chosen, key=lambda repo: len(repo.commits), reverse=True)
324
+ selected: list[tuple[RepoResult, list[Commit]]] = []
325
+ seen_hashes: set[str] = set()
326
+ for repo in ordered:
327
+ unique: list[Commit] = []
328
+ for commit in repo.commits:
329
+ if commit.hash in seen_hashes:
330
+ continue
331
+ if identity is not None and not _is_mine(commit, identity, aliases):
332
+ filtered_commits += 1
333
+ continue
334
+ seen_hashes.add(commit.hash)
335
+ unique.append(commit)
336
+ if unique:
337
+ selected.append((repo, unique))
338
+
339
+ # Year-scoped counts stay on the active repos; lifetime numbers use every
340
+ # local repo after copy/backup dedupe, so an old project that was quiet
341
+ # this year still contributes its history.
342
+ new_repos = sum(
343
+ 1 for repo, _ in selected
344
+ if repo.root_dt is not None and repo.root_dt.year == year
345
+ )
346
+ total_commits = sum(repo.total_commits for repo in chosen)
347
+ tags_in_year = sum(repo.tags_in_year for repo in chosen)
348
+ root_dates = [repo.root_dt for repo in chosen if repo.root_dt is not None]
349
+ earliest_dt = min(root_dates) if root_dates else None
350
+
351
+ multi_repo = len(selected) > 1
352
+ repo_line_counter: dict[str, int] = {}
353
+ repo_langs: dict[str, Counter] = {}
354
+ repo_files: dict[str, Counter] = {}
355
+ for repo, unique in selected:
356
+ repo_counter[repo.name] = len(unique)
357
+ commits.extend(unique)
358
+ repo_line_counter[repo.name] = 0
359
+ repo_langs[repo.name] = Counter()
360
+ repo_files[repo.name] = Counter()
361
+ for commit in unique:
362
+ for change in commit.changes:
363
+ lang_counter[change.lang] += change.lines
364
+ repo_langs[repo.name][change.lang] += change.lines
365
+ repo_line_counter[repo.name] += change.lines
366
+ if is_code_language(change.lang):
367
+ display = f"{repo.name}/{change.path}" if multi_repo else change.path
368
+ file_counter[display] += change.lines
369
+ del_lines = getattr(change, "deleted", 0)
370
+ if del_lines > 0:
371
+ deleted_file_counter[display] += del_lines
372
+ repo_files[repo.name][change.path] += change.lines
373
+ file_set.add((repo.name, change.path))
374
+
375
+ repo_details: list[dict] = []
376
+ for repo, unique in selected:
377
+ if not unique:
378
+ continue
379
+ langs_r = repo_langs[repo.name].most_common(3)
380
+ top_file = repo_files[repo.name].most_common(1)
381
+ repo_details.append({
382
+ "name": repo.name,
383
+ "commits": len(unique),
384
+ "lines": repo_line_counter.get(repo.name, 0),
385
+ "added": sum(c.added for c in unique),
386
+ "deleted": sum(c.deleted for c in unique),
387
+ "active_days": len({c.dt.date() for c in unique}),
388
+ "langs": [[lang, n] for lang, n in langs_r],
389
+ "first": min(c.dt for c in unique).strftime("%Y.%m.%d"),
390
+ "last": max(c.dt for c in unique).strftime("%Y.%m.%d"),
391
+ "readme": repo.readme_line,
392
+ "top_file": [top_file[0][0], top_file[0][1]] if top_file else None,
393
+ "remote": repo.remote,
394
+ "recent": [
395
+ {"date": c.dt.strftime("%m.%d"), "subject": c.subject.strip()[:90]}
396
+ for c in sorted(unique, key=lambda c: c.dt, reverse=True)[:3]
397
+ if len(c.subject.strip()) >= 10
398
+ ],
399
+ })
400
+ repo_details.sort(key=lambda d: (-d["commits"], -d["lines"]))
401
+
402
+ ticker: list[dict] = []
403
+ seen_subject: set[str] = set()
404
+ for commit in sorted(commits, key=lambda c: c.dt, reverse=True):
405
+ subject = commit.subject.strip()
406
+ if len(subject) < 10 or subject.lower().startswith("merge"):
407
+ continue
408
+ if subject in seen_subject:
409
+ continue
410
+ seen_subject.add(subject)
411
+ ticker.append({
412
+ "repo": commit.repo,
413
+ "date": commit.dt.strftime("%m.%d"),
414
+ "subject": subject[:100],
415
+ })
416
+ if len(ticker) >= 26:
417
+ break
418
+
419
+ commit_count = len(commits)
420
+ insertions = sum(c.added for c in commits)
421
+ deletions = sum(c.deleted for c in commits)
422
+ lines_changed = insertions + deletions
423
+
424
+ by_hour = [0] * 24
425
+ by_weekday = [0] * 7
426
+ monthly = [0] * 12
427
+ hour_weekday = [[0] * 24 for _ in range(7)]
428
+ size_counter: Counter[str] = Counter()
429
+ week_counter: Counter[tuple[int, int]] = Counter()
430
+ subject_lens: list[int] = []
431
+ daily: Counter[str] = Counter()
432
+ type_counter: Counter[str] = Counter()
433
+ night_commits = 0
434
+ early_commits = 0
435
+ weekend_commits = 0
436
+
437
+ for c in commits:
438
+ by_hour[c.dt.hour] += 1
439
+ by_weekday[c.dt.weekday()] += 1
440
+ monthly[c.dt.month - 1] += 1
441
+ hour_weekday[c.dt.weekday()][c.dt.hour] += 1
442
+ daily[c.dt.date().isoformat()] += 1
443
+ if c.subject:
444
+ subject_lens.append(len(c.subject))
445
+ size = c.added + c.deleted
446
+ if size < 10:
447
+ size_counter["0–10"] += 1
448
+ elif size < 100:
449
+ size_counter["10–100"] += 1
450
+ elif size < 500:
451
+ size_counter["100–500"] += 1
452
+ elif size < 2000:
453
+ size_counter["500–2k"] += 1
454
+ else:
455
+ size_counter["2k+"] += 1
456
+ iso = c.dt.isocalendar()
457
+ week_counter[(iso[0], iso[1])] += 1
458
+ if c.dt.hour >= 22 or c.dt.hour <= 4:
459
+ night_commits += 1
460
+ elif 5 <= c.dt.hour <= 8:
461
+ early_commits += 1
462
+ if c.dt.weekday() >= 5:
463
+ weekend_commits += 1
464
+ t = _commit_type(c.subject)
465
+ if t:
466
+ type_counter[t] += 1
467
+
468
+ active_dates = sorted(date.fromisoformat(k) for k, v in daily.items() if v > 0)
469
+ longest_streak, current_streak = _streaks(active_dates, year)
470
+
471
+ size_order = ["0–10", "10–100", "100–500", "500–2k", "2k+"]
472
+ size_buckets = [(label, size_counter.get(label, 0)) for label in size_order]
473
+
474
+ busiest_week: tuple[str, int] | None = None
475
+ busiest_week_start: str | None = None
476
+ if week_counter:
477
+ (wy, wn), wc = max(week_counter.items(), key=lambda kv: kv[1])
478
+ busiest_week = (f"{wy}-W{wn:02d}", wc)
479
+ try:
480
+ busiest_week_start = date.fromisocalendar(wy, wn, 1).strftime("%Y.%m.%d")
481
+ except ValueError:
482
+ busiest_week_start = None
483
+
484
+ longest_gap: tuple[int, str, str] | None = None
485
+ if len(active_dates) >= 2:
486
+ best_gap = 0
487
+ best_i = 0
488
+ for i in range(1, len(active_dates)):
489
+ gap = (active_dates[i] - active_dates[i - 1]).days
490
+ if gap > best_gap:
491
+ best_gap, best_i = gap, i
492
+ if best_gap > 0:
493
+ longest_gap = (
494
+ best_gap,
495
+ active_dates[best_i - 1].strftime("%Y.%m.%d"),
496
+ active_dates[best_i].strftime("%Y.%m.%d"),
497
+ )
498
+
499
+ largest_commit: dict | None = None
500
+ largest_deletion: dict | None = None
501
+ if commits:
502
+ lc = max(commits, key=lambda c: c.added + c.deleted)
503
+ largest_commit = {
504
+ "lines": lc.added + lc.deleted,
505
+ "repo": lc.repo,
506
+ "date": lc.dt.strftime("%Y.%m.%d"),
507
+ "subject": lc.subject[:80],
508
+ }
509
+ ld = max(commits, key=lambda c: c.deleted)
510
+ if ld.deleted > 0:
511
+ largest_deletion = {
512
+ "lines": ld.deleted,
513
+ "repo": ld.repo,
514
+ "date": ld.dt.strftime("%Y.%m.%d"),
515
+ "subject": ld.subject[:80],
516
+ }
517
+
518
+ avg_subject_len = round(sum(subject_lens) / len(subject_lens)) if subject_lens else 0
519
+ conventional_share = sum(type_counter.values()) / max(commit_count, 1)
520
+ weekend_share = weekend_commits / max(commit_count, 1)
521
+ night_share = night_commits / max(commit_count, 1)
522
+
523
+ busiest: tuple[str, int] | None = None
524
+ busiest_count = 0
525
+ if daily:
526
+ busiest_count = max(daily.values())
527
+ busiest_day = min(k for k, v in daily.items() if v == busiest_count)
528
+ busiest = (busiest_day, busiest_count)
529
+
530
+ first_dt = min((c.dt for c in commits), default=None)
531
+ last_dt = max((c.dt for c in commits), default=None)
532
+ longest_subject = max((c.subject for c in commits), key=len, default="")
533
+
534
+ languages = lang_counter.most_common()
535
+
536
+ sorted_commits = sorted(commits, key=lambda c: c.dt)
537
+ first_commit = None
538
+ last_commit = None
539
+ if sorted_commits:
540
+ fc, lc2 = sorted_commits[0], sorted_commits[-1]
541
+ first_commit = {"date": fc.dt.strftime("%Y.%m.%d %H:%M"), "repo": fc.repo,
542
+ "subject": fc.subject[:80]}
543
+ last_commit = {"date": lc2.dt.strftime("%Y.%m.%d %H:%M"), "repo": lc2.repo,
544
+ "subject": lc2.subject[:80]}
545
+
546
+ latest_night_commit = None
547
+ night_candidates = [
548
+ c for c in commits if c.dt.hour >= 22 or c.dt.hour <= 5
549
+ ]
550
+ if night_candidates:
551
+ nc = max(
552
+ night_candidates,
553
+ key=lambda c: (
554
+ (c.dt.hour + 24 if c.dt.hour <= 5 else c.dt.hour) * 60
555
+ + c.dt.minute,
556
+ c.dt,
557
+ ),
558
+ )
559
+ latest_night_commit = {
560
+ "time": nc.dt.strftime("%H:%M"),
561
+ "date": nc.dt.strftime("%Y.%m.%d"),
562
+ "repo": nc.repo,
563
+ "subject": nc.subject[:80],
564
+ }
565
+
566
+ # A session is a run of commits with no gap longer than 2 hours.
567
+ sessions = {"count": 0, "longest_minutes": 0, "longest_commits": 0,
568
+ "longest_start": "", "longest_end": "", "avg_minutes": 0}
569
+ if sorted_commits:
570
+ groups: list[list[Commit]] = []
571
+ current = [sorted_commits[0]]
572
+ for c in sorted_commits[1:]:
573
+ if (c.dt - current[-1].dt).total_seconds() <= 2 * 3600:
574
+ current.append(c)
575
+ else:
576
+ groups.append(current)
577
+ current = [c]
578
+ groups.append(current)
579
+ durations = [(g[-1].dt - g[0].dt).total_seconds() / 60 for g in groups]
580
+ longest_i = max(range(len(groups)), key=lambda i: durations[i])
581
+ sessions = {
582
+ "count": len(groups),
583
+ "longest_minutes": round(durations[longest_i]),
584
+ "longest_commits": len(groups[longest_i]),
585
+ "longest_start": groups[longest_i][0].dt.strftime("%Y.%m.%d %H:%M"),
586
+ "longest_end": groups[longest_i][-1].dt.strftime("%Y.%m.%d %H:%M"),
587
+ "avg_minutes": round(sum(durations) / len(durations)),
588
+ }
589
+
590
+ message_counter: Counter[str] = Counter()
591
+ for c in commits:
592
+ length = len(c.subject)
593
+ if length < 20:
594
+ message_counter["0–20"] += 1
595
+ elif length < 40:
596
+ message_counter["20–40"] += 1
597
+ elif length < 80:
598
+ message_counter["40–80"] += 1
599
+ elif length < 160:
600
+ message_counter["80–160"] += 1
601
+ else:
602
+ message_counter["160+"] += 1
603
+ message_buckets = [
604
+ (label, message_counter.get(label, 0))
605
+ for label in ["0–20", "20–40", "40–80", "80–160", "160+"]
606
+ ]
607
+
608
+ top_langs = [name for name, _ in languages[:4]]
609
+ quarters: list[Counter[str]] = [Counter() for _ in range(4)]
610
+ for c in commits:
611
+ q = min((c.dt.month - 1) // 3, 3)
612
+ for change in c.changes:
613
+ quarters[q][change.lang] += change.lines
614
+ language_quarters = []
615
+ for i, qc in enumerate(quarters):
616
+ rows = [(name, qc.get(name, 0)) for name in top_langs]
617
+ rest = sum(v for k, v in qc.items() if k not in top_langs)
618
+ rows.append(("其他", rest))
619
+ language_quarters.append({"q": f"Q{i + 1}", "rows": rows})
620
+
621
+ today_date = datetime.now().date()
622
+ # For a past year, measure dormancy from that year's end, not from today.
623
+ if year < today_date.year:
624
+ today_date = date(year, 12, 31)
625
+ dormant: list[dict] = []
626
+ for repo in repo_details:
627
+ try:
628
+ last_d = datetime.strptime(repo["last"], "%Y.%m.%d").date()
629
+ except ValueError:
630
+ continue
631
+ days = (today_date - last_d).days
632
+ if days > 30:
633
+ dormant.append({
634
+ "name": repo["name"], "last": repo["last"], "days": days,
635
+ "commits": repo["commits"],
636
+ })
637
+ dormant.sort(key=lambda d: -d["days"])
638
+
639
+ avg_files_per_commit = (
640
+ round(sum(c.files for c in commits) / max(commit_count, 1), 1)
641
+ if commits else 0.0
642
+ )
643
+ top_files = [
644
+ (path, n) for path, n in file_counter.most_common(12)
645
+ ]
646
+ top_deleted_files = [
647
+ (path, n) for path, n in deleted_file_counter.most_common(12) if n > 0
648
+ ]
649
+ keywords = extract_keywords([c.subject for c in commits], top=14)
650
+ commit_types = type_counter.most_common(8)
651
+ repo_commits = repo_counter.most_common()
652
+
653
+ peak_hour = by_hour.index(max(by_hour)) if any(by_hour) else 0
654
+ typed_commits = sum(type_counter.values())
655
+
656
+ persona = build_persona(
657
+ year=year,
658
+ commits=commit_count,
659
+ repos=len(repo_counter),
660
+ lines=lines_changed,
661
+ insertions=insertions,
662
+ deletions=deletions,
663
+ active_days=len(active_dates),
664
+ longest_streak=longest_streak,
665
+ current_streak=current_streak,
666
+ night_commits=night_commits,
667
+ early_commits=early_commits,
668
+ weekend_commits=weekend_commits,
669
+ peak_hour=peak_hour,
670
+ fix_commits=type_counter.get("fix", 0),
671
+ feat_commits=type_counter.get("feat", 0),
672
+ typed_commits=typed_commits,
673
+ lang_count=len(languages),
674
+ busiest_count=busiest_count,
675
+ )
676
+
677
+ return ReportStats(
678
+ year=year,
679
+ root=root,
680
+ generated_at=datetime.now().strftime("%Y-%m-%d %H:%M"),
681
+ repo_count=len(repo_counter),
682
+ new_repos=new_repos,
683
+ total_commits=total_commits,
684
+ tags_in_year=tags_in_year,
685
+ earliest_dt=earliest_dt,
686
+ repo_names=[name for name, _ in repo_commits],
687
+ commit_count=commit_count,
688
+ insertions=insertions,
689
+ deletions=deletions,
690
+ lines_changed=lines_changed,
691
+ file_count=len(file_set),
692
+ active_days=len(active_dates),
693
+ longest_streak=longest_streak,
694
+ current_streak=current_streak,
695
+ first_dt=first_dt,
696
+ last_dt=last_dt,
697
+ by_hour=by_hour,
698
+ by_weekday=by_weekday,
699
+ monthly=monthly,
700
+ hour_weekday=hour_weekday,
701
+ size_buckets=size_buckets,
702
+ busiest_week=busiest_week,
703
+ busiest_week_start=busiest_week_start,
704
+ longest_gap=longest_gap,
705
+ largest_commit=largest_commit,
706
+ largest_deletion=largest_deletion,
707
+ avg_subject_len=avg_subject_len,
708
+ conventional_share=conventional_share,
709
+ weekend_share=weekend_share,
710
+ night_share=night_share,
711
+ first_commit=first_commit,
712
+ last_commit=last_commit,
713
+ sessions=sessions,
714
+ message_buckets=message_buckets,
715
+ language_quarters=language_quarters,
716
+ dormant=dormant,
717
+ avg_files_per_commit=avg_files_per_commit,
718
+ daily=dict(sorted(daily.items())),
719
+ languages=languages,
720
+ top_files=top_files,
721
+ keywords=keywords,
722
+ commit_types=commit_types,
723
+ repo_commits=repo_commits,
724
+ busiest_day=busiest,
725
+ busiest_count=busiest_count,
726
+ longest_subject=longest_subject,
727
+ language_count=len(languages),
728
+ repo_details=repo_details,
729
+ ticker=ticker,
730
+ identity_label=identity_label,
731
+ filtered_commits=filtered_commits,
732
+ persona=persona,
733
+ warnings=warnings,
734
+ top_deleted_files=top_deleted_files,
735
+ latest_night_commit=latest_night_commit,
736
+ )