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,150 @@
1
+ """文件「修罗场」评分。
2
+
3
+ 原始 PRD 的口径是「变更频次 + 伴随 fix/revert 比例」。用下来有问题:
4
+ `utils.py` 会被顶到第一名,因为它被改得最多 —— 但改得多不等于危险。
5
+
6
+ 这里换成三因子:
7
+ freq 变更频次(log 归一化,避免超大文件通吃)
8
+ brittle 该文件的提交里 fix/revert 的占比(易碎度)
9
+ silo 只有一个人碰过 = 知识孤岛,交接时最疼
10
+ score = 0.45*freq + 0.30*brittle + 0.25*silo
11
+
12
+ 三个分项都保留在输出里,报告可以直接告诉用户「它为什么上榜」。
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from collections import defaultdict
18
+
19
+ from ..clean import file_category, normalize_author_key
20
+ from ..models import Commit
21
+ from ._util import log_norm, pct, round2
22
+
23
+ __all__ = ["build"]
24
+
25
+ _FIX_KINDS = frozenset({"fix", "revert"})
26
+
27
+ # 文档和配置改得再多也不是「危险代码」。降权让它们在榜上靠后,但不至于消失。
28
+ _CATEGORY_WEIGHT = {"code": 1.0, "config": 0.65, "doc": 0.55, "other": 0.8}
29
+
30
+
31
+ def build(commits: list[Commit], *, top_files: int = 15, top_dirs: int = 8) -> dict:
32
+ if not commits:
33
+ return {"files": [], "dirs": [], "threshold": 0}
34
+
35
+ files: dict[str, dict] = defaultdict(
36
+ lambda: {
37
+ "changes": 0,
38
+ "insertions": 0,
39
+ "deletions": 0,
40
+ "fix_touches": 0,
41
+ "max_single_churn": 0,
42
+ "authors": set(),
43
+ }
44
+ )
45
+
46
+ for commit in commits:
47
+ author = normalize_author_key(commit.author, commit.email)
48
+ is_fix = commit.kind in _FIX_KINDS
49
+ for change in commit.changes:
50
+ entry = files[change.path]
51
+ entry["changes"] += 1
52
+ entry["insertions"] += change.insertions
53
+ entry["deletions"] += change.deletions
54
+ entry["max_single_churn"] = max(entry["max_single_churn"], change.churn)
55
+ entry["authors"].add(author)
56
+ if is_fix:
57
+ entry["fix_touches"] += 1
58
+
59
+ max_changes = max((e["changes"] for e in files.values()), default=1)
60
+ churn_values = sorted(
61
+ (e["insertions"] + e["deletions"] for e in files.values()), reverse=True
62
+ )
63
+ # 单次波动阈值取 90 分位,且不低于 50 行,避免小仓库全员「volatile」
64
+ volatile_threshold = max(50, churn_values[len(churn_values) // 10] if churn_values else 50)
65
+
66
+ rows = []
67
+ for path, entry in files.items():
68
+ changes = entry["changes"]
69
+ fix_ratio = entry["fix_touches"] / changes
70
+ authors = len(entry["authors"])
71
+ silo = 1.0 / authors
72
+ category = file_category(path)
73
+
74
+ freq_score = log_norm(changes, max_changes)
75
+ brittle_score = fix_ratio
76
+ # 孤岛风险必须乘上频次:一个只改过两次的单人文件不是风险,是没人碰
77
+ silo_score = (1.0 if authors == 1 else silo) * freq_score
78
+
79
+ raw = (0.50 * freq_score + 0.30 * brittle_score + 0.20 * silo_score) * 100
80
+ score = raw * _CATEGORY_WEIGHT.get(category, 0.8)
81
+
82
+ tags = []
83
+ if freq_score >= 0.75:
84
+ tags.append("hot")
85
+ if fix_ratio >= 0.35 and changes >= 3 and category == "code":
86
+ tags.append("brittle")
87
+ if authors == 1 and changes >= 5:
88
+ tags.append("silo")
89
+ if entry["max_single_churn"] >= volatile_threshold:
90
+ tags.append("volatile")
91
+
92
+ rows.append(
93
+ {
94
+ "path": path,
95
+ "category": category,
96
+ "changes": changes,
97
+ "insertions": entry["insertions"],
98
+ "deletions": entry["deletions"],
99
+ "churn": entry["insertions"] + entry["deletions"],
100
+ "fix_touches": entry["fix_touches"],
101
+ "fix_ratio": round2(fix_ratio),
102
+ "authors": authors,
103
+ "max_single_churn": entry["max_single_churn"],
104
+ "score": round2(score),
105
+ "tags": tags,
106
+ }
107
+ )
108
+
109
+ rows.sort(key=lambda r: (-r["score"], -r["changes"]))
110
+ top = rows[:top_files]
111
+
112
+ return {
113
+ "files": top,
114
+ "dirs": _aggregate_dirs(rows, top_dirs),
115
+ "threshold": volatile_threshold,
116
+ "counted_files": len(rows),
117
+ "top_score": top[0]["score"] if top else 0,
118
+ "empty": not rows,
119
+ }
120
+
121
+
122
+ def _aggregate_dirs(rows: list[dict], limit: int) -> list[dict]:
123
+ """按顶层模块聚合。报告里给「哪个模块最乱」,比列 15 个文件名更有洞察。"""
124
+ dirs: dict[str, dict] = defaultdict(
125
+ lambda: {"changes": 0, "churn": 0, "files": 0, "fix_touches": 0, "score": 0.0}
126
+ )
127
+ for row in rows:
128
+ parts = row["path"].split("/")
129
+ name = parts[0] if len(parts) > 1 else "(root)"
130
+ entry = dirs[name]
131
+ entry["changes"] += row["changes"]
132
+ entry["churn"] += row["churn"]
133
+ entry["files"] += 1
134
+ entry["fix_touches"] += row["fix_touches"]
135
+ entry["score"] = max(entry["score"], row["score"])
136
+
137
+ total_churn = sum(entry["churn"] for entry in dirs.values()) or 1
138
+ result = [
139
+ {
140
+ "name": name,
141
+ "changes": entry["changes"],
142
+ "churn": entry["churn"],
143
+ "files": entry["files"],
144
+ "share": pct(entry["churn"], total_churn),
145
+ "score": round2(entry["score"]),
146
+ }
147
+ for name, entry in dirs.items()
148
+ ]
149
+ result.sort(key=lambda r: (-r["churn"], -r["changes"]))
150
+ return result[:limit]
@@ -0,0 +1,100 @@
1
+ """贡献者画像。
2
+
3
+ 身份归一一律以邮箱为准。真实仓库里同一个人常有多个 name(中文名 / 英文名 /
4
+ 机器名),用 name 合并会把一个人拆成三个,也可能把两个人并成一个。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections import Counter, defaultdict
10
+
11
+ from ..clean import normalize_author_key
12
+ from ..models import Commit
13
+ from ._util import pct, round2
14
+
15
+ __all__ = ["build"]
16
+
17
+
18
+ def build(commits: list[Commit], *, top: int = 12) -> dict:
19
+ """注意:这里不做脱敏。脱敏只有一个入口(redact.redact_report),
20
+ 否则会出现两套别名互相对不上的情况。"""
21
+
22
+ if not commits:
23
+ return {"rows": [], "total_commits": 0, "empty": True}
24
+
25
+ stats: dict[str, dict] = defaultdict(
26
+ lambda: {
27
+ "names": Counter(),
28
+ "emails": Counter(),
29
+ "commits": 0,
30
+ "insertions": 0,
31
+ "deletions": 0,
32
+ "days": set(),
33
+ "night": 0,
34
+ "weekend": 0,
35
+ "kinds": Counter(),
36
+ "first": None,
37
+ "last": None,
38
+ }
39
+ )
40
+
41
+ for commit in commits:
42
+ key = normalize_author_key(commit.author, commit.email)
43
+ entry = stats[key]
44
+ entry["names"][commit.author] += 1
45
+ entry["emails"][commit.email.lower()] += 1
46
+ entry["commits"] += 1
47
+ entry["insertions"] += commit.insertions
48
+ entry["deletions"] += commit.deletions
49
+ entry["days"].add(commit.authored_at.date())
50
+ entry["kinds"][commit.kind] += 1
51
+ moment = commit.authored_at
52
+ if moment.hour < 6:
53
+ entry["night"] += 1
54
+ if moment.weekday() >= 5:
55
+ entry["weekend"] += 1
56
+ if entry["first"] is None or moment < entry["first"]:
57
+ entry["first"] = moment
58
+ if entry["last"] is None or moment > entry["last"]:
59
+ entry["last"] = moment
60
+
61
+ total = len(commits)
62
+ rows = []
63
+ for key, entry in stats.items():
64
+ name = entry["names"].most_common(1)[0][0]
65
+ email = entry["emails"].most_common(1)[0][0]
66
+ dominant = entry["kinds"].most_common(1)[0][0] if entry["kinds"] else "other"
67
+ rows.append(
68
+ {
69
+ "key": key,
70
+ "name": name,
71
+ "email": email,
72
+ "commits": entry["commits"],
73
+ "share": pct(entry["commits"], total),
74
+ "insertions": entry["insertions"],
75
+ "deletions": entry["deletions"],
76
+ "net": entry["insertions"] - entry["deletions"],
77
+ "active_days": len(entry["days"]),
78
+ "first_commit_at": entry["first"].isoformat() if entry["first"] else None,
79
+ "last_commit_at": entry["last"].isoformat() if entry["last"] else None,
80
+ "night_share": pct(entry["night"], entry["commits"]),
81
+ "weekend_share": pct(entry["weekend"], entry["commits"]),
82
+ "dominant_kind": dominant,
83
+ "avg_commits_per_active_day": round2(
84
+ entry["commits"] / max(1, len(entry["days"]))
85
+ ),
86
+ }
87
+ )
88
+
89
+ rows.sort(key=lambda r: (-r["commits"], -r["net"]))
90
+ top_rows = rows[:top]
91
+
92
+ return {
93
+ "rows": top_rows,
94
+ "total_commits": total,
95
+ "count": len(rows),
96
+ "single_author": len(rows) == 1,
97
+ "concentration": round2(top_rows[0]["share"]) if top_rows else 0.0,
98
+ "rest_commits": total - sum(r["commits"] for r in top_rows),
99
+ "empty": False,
100
+ }
@@ -0,0 +1,213 @@
1
+ """考古彩蛋与收尾金句。
2
+
3
+ 全部由规则生成 —— 这不是妥协,是设计要求:
4
+ `--no-ai` 模式下报告也必须「有梗」,否则工具的价值就塌了一半。
5
+ LLM 上线后只负责在同样的事实上换个说法,事实本身不接受编造。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from collections import Counter
12
+ from datetime import date
13
+
14
+ from ..clean import normalize_author_key
15
+ from ..models import Commit
16
+ from ..i18n import t
17
+ from ._util import pct
18
+
19
+ __all__ = ["build_facts", "build_quote"]
20
+
21
+ _FINAL_WORDS = re.compile(
22
+ r"\b(final|finally|last|end|really final|for real)\b|最终|最后一次|终于|真的最后|收尾",
23
+ re.IGNORECASE,
24
+ )
25
+
26
+
27
+ def _fmt_int(value: int) -> str:
28
+ return f"{value:,}"
29
+
30
+
31
+ def build_facts(
32
+ commits: list[Commit],
33
+ *,
34
+ lang: str = "zh",
35
+ limit: int = 6,
36
+ author_label: str | None = None,
37
+ ) -> list[dict]:
38
+ if not commits:
39
+ return []
40
+
41
+ ordered = sorted(commits, key=lambda c: c.authored_at)
42
+ facts: list[dict] = []
43
+ total_insertions = sum(c.insertions for c in commits)
44
+ total_deletions = sum(c.deletions for c in commits)
45
+
46
+ def add(fact_id: str, detail: str, value: str) -> None:
47
+ facts.append(
48
+ {
49
+ "id": fact_id,
50
+ "title": t(f"fact.{fact_id}.title", lang),
51
+ "detail": detail,
52
+ "value": value,
53
+ }
54
+ )
55
+
56
+ # 原点
57
+ first = ordered[0]
58
+ add(
59
+ "origin",
60
+ t(
61
+ "fact.origin.detail",
62
+ lang,
63
+ date=first.authored_at.date().isoformat(),
64
+ author=author_label or first.author,
65
+ subject=_clip(first.subject, 48),
66
+ ),
67
+ first.authored_at.date().isoformat(),
68
+ )
69
+
70
+ # 最深的夜:取「最晚的凌晨」而不是「最早的钟点」,0:15 比 5:59 更像熬通宵
71
+ night = [c for c in commits if c.authored_at.hour < 6]
72
+ if night:
73
+ deepest = max(night, key=lambda c: (24 - c.authored_at.hour) % 24)
74
+ add(
75
+ "deepest_night",
76
+ t(
77
+ "fact.deepest_night.detail",
78
+ lang,
79
+ date=deepest.authored_at.date().isoformat(),
80
+ time=deepest.authored_at.strftime("%H:%M"),
81
+ author=author_label or deepest.author,
82
+ subject=_clip(deepest.subject, 40),
83
+ ),
84
+ deepest.authored_at.strftime("%H:%M"),
85
+ )
86
+
87
+ # 最长连续作战
88
+ days = sorted({c.authored_at.date() for c in commits})
89
+ streak, best = 1, (days[0], days[0], 1)
90
+ for prev, cur in zip(days, days[1:]):
91
+ if (cur - prev).days == 1:
92
+ streak += 1
93
+ else:
94
+ streak = 1
95
+ if streak > best[2]:
96
+ best = (cur.fromordinal(cur.toordinal() - streak + 1), cur, streak)
97
+ if best[2] >= 3:
98
+ add(
99
+ "longest_streak",
100
+ t(
101
+ "fact.longest_streak.detail",
102
+ lang,
103
+ days=best[2],
104
+ start=best[0].isoformat(),
105
+ end=best[1].isoformat(),
106
+ ),
107
+ f"{best[2]}d",
108
+ )
109
+
110
+ # 单条最大提交
111
+ biggest = max(commits, key=lambda c: c.churn)
112
+ if biggest.churn > 0:
113
+ add(
114
+ "biggest_commit",
115
+ t(
116
+ "fact.biggest_commit.detail",
117
+ lang,
118
+ short_sha=biggest.short_sha,
119
+ lines=_fmt_int(biggest.churn),
120
+ subject=_clip(biggest.subject, 48),
121
+ ),
122
+ f"{_fmt_int(biggest.churn)} lines",
123
+ )
124
+
125
+ # 最疯狂的一天
126
+ per_day = Counter(c.authored_at.date() for c in commits)
127
+ busiest_day, busiest_count = per_day.most_common(1)[0]
128
+ if busiest_count >= 4:
129
+ add(
130
+ "busiest_day",
131
+ t("fact.busiest_day.detail", lang, date=busiest_day.isoformat(), commits=busiest_count),
132
+ f"{busiest_count}",
133
+ )
134
+
135
+ # final 陷阱
136
+ final_hits = [c for c in commits if _FINAL_WORDS.search(c.subject)]
137
+ if len(final_hits) >= 2:
138
+ add(
139
+ "final_loop",
140
+ t("fact.final_loop.detail", lang, count=len(final_hits)),
141
+ f"{len(final_hits)}",
142
+ )
143
+
144
+ # 最长的沉默
145
+ gaps = [
146
+ ((b - a).days, a, b)
147
+ for a, b in zip(days, days[1:])
148
+ ]
149
+ if gaps:
150
+ gap_days, gap_start, gap_end = max(gaps)
151
+ if gap_days >= 14:
152
+ add(
153
+ "silence",
154
+ t(
155
+ "fact.silence.detail",
156
+ lang,
157
+ start=gap_start.isoformat(),
158
+ end=gap_end.isoformat(),
159
+ days=gap_days,
160
+ ),
161
+ f"{gap_days}d",
162
+ )
163
+
164
+ # 深夜在场者
165
+ per_author = Counter()
166
+ per_author_night = Counter()
167
+ for commit in commits:
168
+ key = normalize_author_key(commit.author, commit.email)
169
+ per_author[key] += 1
170
+ if commit.authored_at.hour < 6:
171
+ per_author_night[key] += 1
172
+ if per_author_night:
173
+ key, count = per_author_night.most_common(1)[0]
174
+ if count >= 3 and count / max(1, per_author[key]) >= 0.2:
175
+ name = author_label or next(
176
+ c.author for c in commits if normalize_author_key(c.author, c.email) == key
177
+ )
178
+ add(
179
+ "night_owl",
180
+ t(
181
+ "fact.night_owl.detail",
182
+ lang,
183
+ author=name,
184
+ share=f"{pct(count, per_author[key]):.0f}%",
185
+ count=count,
186
+ ),
187
+ f"{pct(count, per_author[key]):.0f}%",
188
+ )
189
+
190
+ return facts[:limit]
191
+
192
+
193
+ def build_quote(commits: list[Commit], *, lang: str = "zh", tone: str = "tech") -> str:
194
+ if not commits:
195
+ return ""
196
+ ordered = sorted(commits, key=lambda c: c.authored_at)
197
+ days = (ordered[-1].authored_at.date() - ordered[0].authored_at.date()).days + 1
198
+ insertions = sum(c.insertions for c in commits)
199
+ deletions = sum(c.deletions for c in commits)
200
+ key = "quote.roast" if tone == "roast" else "quote.tech"
201
+ return t(
202
+ key,
203
+ lang,
204
+ commits=_fmt_int(len(commits)),
205
+ lines=_fmt_int(insertions + deletions),
206
+ days=days,
207
+ insertions=_fmt_int(insertions),
208
+ deletions=_fmt_int(deletions),
209
+ )
210
+
211
+
212
+ def _clip(text: str, limit: int) -> str:
213
+ return text if len(text) <= limit else text[: limit - 1] + "…"
@@ -0,0 +1,135 @@
1
+ """语言与模块构成,以及占比随时间的漂移。
2
+
3
+ 「语言」在这里指文件扩展名映射出的类别,不是 LOC 精确统计 —— 报告讲的是
4
+ 演进趋势,不是代码行审计。用增删行数当权重比数文件更贴近真实投入。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections import defaultdict
10
+
11
+ from ..models import Commit
12
+ from ._util import month_key, pct
13
+
14
+ __all__ = ["build"]
15
+
16
+ _EXT_LANG = {
17
+ ".py": "Python",
18
+ ".pyi": "Python",
19
+ ".ipynb": "Jupyter",
20
+ ".java": "Java",
21
+ ".kt": "Kotlin",
22
+ ".scala": "Scala",
23
+ ".go": "Go",
24
+ ".rs": "Rust",
25
+ ".c": "C",
26
+ ".h": "C",
27
+ ".cc": "C++",
28
+ ".cpp": "C++",
29
+ ".hpp": "C++",
30
+ ".cs": "C#",
31
+ ".rb": "Ruby",
32
+ ".php": "PHP",
33
+ ".swift": "Swift",
34
+ ".m": "Objective-C",
35
+ ".js": "JavaScript",
36
+ ".jsx": "JavaScript",
37
+ ".mjs": "JavaScript",
38
+ ".ts": "TypeScript",
39
+ ".tsx": "TypeScript",
40
+ ".vue": "Vue",
41
+ ".svelte": "Svelte",
42
+ ".html": "HTML",
43
+ ".htm": "HTML",
44
+ ".css": "CSS",
45
+ ".scss": "CSS",
46
+ ".less": "CSS",
47
+ ".sh": "Shell",
48
+ ".bash": "Shell",
49
+ ".ps1": "PowerShell",
50
+ ".sql": "SQL",
51
+ ".md": "Markdown",
52
+ ".rst": "reStructuredText",
53
+ ".tex": "TeX",
54
+ ".json": "JSON",
55
+ ".yaml": "YAML",
56
+ ".yml": "YAML",
57
+ ".toml": "TOML",
58
+ ".proto": "Protobuf",
59
+ ".tf": "Terraform",
60
+ ".dockerfile": "Docker",
61
+ }
62
+
63
+ # 这些不算「代码」,但也不该丢,单列一个类别让报告能说明构成
64
+ _DOC_LANGS = {"Markdown", "reStructuredText", "TeX"}
65
+ _CONFIG_LANGS = {"JSON", "YAML", "TOML"}
66
+
67
+
68
+ def _language_of(path: str) -> str:
69
+ name = path.rsplit("/", 1)[-1]
70
+ if name.lower() in ("dockerfile", "makefile", "jenkinsfile"):
71
+ return {"dockerfile": "Docker"}.get(name.lower(), "Makefile")
72
+ dot = name.rfind(".")
73
+ if dot <= 0:
74
+ return "Other"
75
+ return _EXT_LANG.get(name[dot:].lower(), "Other")
76
+
77
+
78
+ def build(commits: list[Commit], *, top_langs: int = 6) -> dict:
79
+ if not commits:
80
+ return {"rows": [], "trend": {"keys": [], "series": []}, "empty": True}
81
+
82
+ churn: dict[str, int] = defaultdict(int)
83
+ files: dict[str, set[str]] = defaultdict(set)
84
+ by_month: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int))
85
+
86
+ for commit in commits:
87
+ month = month_key(commit.authored_at.date())
88
+ for change in commit.changes:
89
+ lang = _language_of(change.path)
90
+ churn[lang] += change.churn
91
+ files[lang].add(change.path)
92
+ by_month[month][lang] += change.churn
93
+
94
+ total = sum(churn.values()) or 1
95
+ items = [
96
+ {
97
+ "lang": lang,
98
+ "churn": value,
99
+ "files": len(files[lang]),
100
+ "share": pct(value, total),
101
+ "category": _category(lang),
102
+ }
103
+ for lang, value in churn.items()
104
+ ]
105
+ items.sort(key=lambda r: -r["churn"])
106
+ top = items[:top_langs]
107
+
108
+ keys = sorted(by_month)
109
+ series = []
110
+ for lang in [item["lang"] for item in top]:
111
+ values = []
112
+ for month in keys:
113
+ month_total = sum(by_month[month].values()) or 1
114
+ values.append(pct(by_month[month].get(lang, 0), month_total))
115
+ series.append({"lang": lang, "values": values})
116
+
117
+ return {
118
+ "rows": top,
119
+ "rest": {
120
+ "churn": sum(item["churn"] for item in items[top_langs:]),
121
+ "share": pct(sum(item["churn"] for item in items[top_langs:]), total),
122
+ },
123
+ "trend": {"keys": keys, "series": series},
124
+ "empty": False,
125
+ }
126
+
127
+
128
+ def _category(lang: str) -> str:
129
+ if lang in _DOC_LANGS:
130
+ return "doc"
131
+ if lang in _CONFIG_LANGS:
132
+ return "config"
133
+ if lang in ("Other",):
134
+ return "other"
135
+ return "code"