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,133 @@
|
|
|
1
|
+
"""LLM 输出的结构与边界校验。
|
|
2
|
+
|
|
3
|
+
模型返回的 JSON 不能直接信。这里做三件事:
|
|
4
|
+
1. 结构必须对(id 不能编、字段类型必须对);
|
|
5
|
+
2. 长度要有边界(否则一段 800 字的旁白会把版面撑爆);
|
|
6
|
+
3. 只接受「我们认得的东西」,多余字段一律丢弃。
|
|
7
|
+
|
|
8
|
+
校验失败不是致命错误 —— 调用方会带着失败原因重试一次,再不行就回落规则叙事。
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import re
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
__all__ = ["NarrativeError", "validate"]
|
|
17
|
+
|
|
18
|
+
_CONTROL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f]")
|
|
19
|
+
|
|
20
|
+
_LIMITS = {
|
|
21
|
+
"zh": {
|
|
22
|
+
"title": (2, 24), "narrative": (20, 420),
|
|
23
|
+
"note": (6, 160), "comment": (2, 120), "quote": (4, 120),
|
|
24
|
+
},
|
|
25
|
+
"en": {
|
|
26
|
+
"title": (2, 40), "narrative": (20, 700),
|
|
27
|
+
"note": (6, 320), "comment": (2, 200), "quote": (4, 200),
|
|
28
|
+
},
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class NarrativeError(ValueError):
|
|
33
|
+
"""输出不合格。消息会被原样塞回给模型用于自我修正。"""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _text(value: Any, field: str, low: int, high: int) -> str:
|
|
37
|
+
if not isinstance(value, str):
|
|
38
|
+
raise NarrativeError(f"{field} 必须是字符串,收到 {type(value).__name__}")
|
|
39
|
+
cleaned = _CONTROL.sub("", value).strip()
|
|
40
|
+
if not (low <= len(cleaned) <= high):
|
|
41
|
+
raise NarrativeError(f"{field} 长度必须在 {low}-{high} 之间,实际 {len(cleaned)}")
|
|
42
|
+
return cleaned
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def validate(
|
|
46
|
+
data: dict[str, Any],
|
|
47
|
+
*,
|
|
48
|
+
chapter_ids: list[str],
|
|
49
|
+
fact_ids: list[str],
|
|
50
|
+
lang: str = "zh",
|
|
51
|
+
mode: str = "project",
|
|
52
|
+
) -> dict[str, Any]:
|
|
53
|
+
limits = _LIMITS.get(lang, _LIMITS["zh"])
|
|
54
|
+
allowed_chapters = set(chapter_ids)
|
|
55
|
+
allowed_facts = set(fact_ids)
|
|
56
|
+
|
|
57
|
+
phases_out: list[dict[str, str]] = []
|
|
58
|
+
if mode == "author":
|
|
59
|
+
raw_phases = data.get("phases")
|
|
60
|
+
if raw_phases is not None:
|
|
61
|
+
if not isinstance(raw_phases, list):
|
|
62
|
+
raise NarrativeError("phases 必须是数组")
|
|
63
|
+
seen_phases: set[str] = set()
|
|
64
|
+
for index, item in enumerate(raw_phases):
|
|
65
|
+
if not isinstance(item, dict):
|
|
66
|
+
raise NarrativeError(f"phases[{index}] 必须是对象")
|
|
67
|
+
pid = item.get("id")
|
|
68
|
+
if pid not in allowed_chapters:
|
|
69
|
+
raise NarrativeError(f"phases[{index}].id={pid!r} 不在允许列表")
|
|
70
|
+
if pid in seen_phases:
|
|
71
|
+
raise NarrativeError(f"phases 里 {pid} 重复出现")
|
|
72
|
+
seen_phases.add(pid)
|
|
73
|
+
phases_out.append(
|
|
74
|
+
{"id": pid, "note": _text(item.get("note"), f"phases[{pid}].note", *limits["note"])}
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
chapters_out: list[dict[str, str]] = []
|
|
78
|
+
raw_chapters = data.get("chapters")
|
|
79
|
+
if raw_chapters is not None:
|
|
80
|
+
if not isinstance(raw_chapters, list):
|
|
81
|
+
raise NarrativeError("chapters 必须是数组")
|
|
82
|
+
seen: set[str] = set()
|
|
83
|
+
for index, item in enumerate(raw_chapters):
|
|
84
|
+
if not isinstance(item, dict):
|
|
85
|
+
raise NarrativeError(f"chapters[{index}] 必须是对象")
|
|
86
|
+
cid = item.get("id")
|
|
87
|
+
if cid not in allowed_chapters:
|
|
88
|
+
raise NarrativeError(f"chapters[{index}].id={cid!r} 不在允许列表 {sorted(allowed_chapters)}")
|
|
89
|
+
if cid in seen:
|
|
90
|
+
raise NarrativeError(f"chapters 里 {cid} 重复出现")
|
|
91
|
+
seen.add(cid)
|
|
92
|
+
chapters_out.append(
|
|
93
|
+
{
|
|
94
|
+
"id": cid,
|
|
95
|
+
"title": _text(item.get("title"), f"chapters[{cid}].title", *limits["title"]),
|
|
96
|
+
"narrative": _text(
|
|
97
|
+
item.get("narrative"), f"chapters[{cid}].narrative", *limits["narrative"]
|
|
98
|
+
),
|
|
99
|
+
}
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
facts_out: list[dict[str, str]] = []
|
|
103
|
+
raw_facts = data.get("fun_facts")
|
|
104
|
+
if raw_facts is not None:
|
|
105
|
+
if not isinstance(raw_facts, list):
|
|
106
|
+
raise NarrativeError("fun_facts 必须是数组")
|
|
107
|
+
seen_facts: set[str] = set()
|
|
108
|
+
for index, item in enumerate(raw_facts):
|
|
109
|
+
if not isinstance(item, dict):
|
|
110
|
+
raise NarrativeError(f"fun_facts[{index}] 必须是对象")
|
|
111
|
+
fid = item.get("id")
|
|
112
|
+
if fid not in allowed_facts:
|
|
113
|
+
raise NarrativeError(f"fun_facts[{index}].id={fid!r} 不在允许列表")
|
|
114
|
+
if fid in seen_facts:
|
|
115
|
+
continue
|
|
116
|
+
seen_facts.add(fid)
|
|
117
|
+
facts_out.append(
|
|
118
|
+
{"id": fid, "comment": _text(item.get("comment"), f"fun_facts[{fid}]", *limits["comment"])}
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
quote = None
|
|
122
|
+
if data.get("quote") is not None:
|
|
123
|
+
quote = _text(data.get("quote"), "quote", *limits["quote"])
|
|
124
|
+
|
|
125
|
+
if not chapters_out and not phases_out and not facts_out and not quote:
|
|
126
|
+
raise NarrativeError("返回里没有任何可用字段(全空)")
|
|
127
|
+
|
|
128
|
+
return {
|
|
129
|
+
"chapters": chapters_out,
|
|
130
|
+
"phases": phases_out,
|
|
131
|
+
"fun_facts": facts_out,
|
|
132
|
+
"quote": quote,
|
|
133
|
+
}
|
chronicle/redact.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
"""脱敏。
|
|
2
|
+
|
|
3
|
+
`--anon` 的承诺是「这份报告可以安全地发出去」。承诺要能兑现只有一条路:
|
|
4
|
+
**所有对外可见的字符串都必须从这里过一遍。**
|
|
5
|
+
|
|
6
|
+
覆盖四类:
|
|
7
|
+
|
|
8
|
+
人 作者名 → 开发者 A / B / C;邮箱 → dev-a@redacted
|
|
9
|
+
仓库 仓库名 → repo-<hash>;绝对路径与 remote → 置空
|
|
10
|
+
文件 路径逐段哈希,保留通用目录名与扩展名(`src/p3f9a1/p2b8c4.py`)
|
|
11
|
+
内容 commit subject 整体替换为类型标签,内容一个字都不留
|
|
12
|
+
|
|
13
|
+
入口只有一个:`analyze()` 在报告成形之后、交给 LLM 和渲染之前调用一次。
|
|
14
|
+
测试 `test_redaction` 会拿真实的姓名、邮箱、仓库名、标题去搜产物,命中即失败 ——
|
|
15
|
+
这条测试就是这份承诺的执行机制。
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import hashlib
|
|
21
|
+
import re
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from .i18n import t
|
|
25
|
+
from .models import Commit
|
|
26
|
+
|
|
27
|
+
__all__ = ["Redactor", "redact_report", "GENERIC_SEGMENTS"]
|
|
28
|
+
|
|
29
|
+
# 这些目录名不带身份信息,保留原样,否则路径会变成一串乱码,报告失去可读性
|
|
30
|
+
GENERIC_SEGMENTS = frozenset(
|
|
31
|
+
{
|
|
32
|
+
"src", "lib", "libs", "app", "apps", "pkg", "packages", "internal", "cmd",
|
|
33
|
+
"test", "tests", "spec", "specs", "doc", "docs", "example", "examples",
|
|
34
|
+
"config", "configs", "conf", "settings", "script", "scripts", "bin", "tools",
|
|
35
|
+
"assets", "static", "public", "web", "frontend", "backend", "server", "client",
|
|
36
|
+
"api", "core", "common", "shared", "utils", "util", "helpers", "helper",
|
|
37
|
+
"model", "models", "view", "views", "component", "components", "page", "pages",
|
|
38
|
+
"db", "migrations", "schema", "types", "hooks", "store", "services",
|
|
39
|
+
"main", "index", "__init__", "module", "modules", "plugin", "plugins",
|
|
40
|
+
"eval", "bench", "benchmark", "experiments", "notebooks", "paper", "papers",
|
|
41
|
+
"data", "dataset", "datasets", "output", "outputs", "results",
|
|
42
|
+
"main", "root", "tmp", "temp", "var", "etc", "opt", "usr", "home",
|
|
43
|
+
}
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
_QUOTED = re.compile(r"「([^」]{2,200})」|\"([^\"]{2,200})\"")
|
|
47
|
+
# 兜底:任何还长得像邮箱的东西(包括 `x***@corp.com` 这种半遮的)一律抹掉域名
|
|
48
|
+
_EMAILISH = re.compile(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _hash(token: str, size: int = 6) -> str:
|
|
52
|
+
return hashlib.sha1(token.encode("utf-8")).hexdigest()[:size]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class Redactor:
|
|
56
|
+
def __init__(
|
|
57
|
+
self,
|
|
58
|
+
commits: list[Commit],
|
|
59
|
+
*,
|
|
60
|
+
repo_name: str = "",
|
|
61
|
+
remote_url: str | None = None,
|
|
62
|
+
lang: str = "zh",
|
|
63
|
+
primary_email: str | None = None,
|
|
64
|
+
) -> None:
|
|
65
|
+
self.lang = lang
|
|
66
|
+
self._name_map: dict[str, str] = {}
|
|
67
|
+
self._email_map: dict[str, str] = {}
|
|
68
|
+
self._segment_map: dict[str, str] = {}
|
|
69
|
+
self._subjects: set[str] = set()
|
|
70
|
+
|
|
71
|
+
self.repo_name_source = repo_name
|
|
72
|
+
self.repo_alias = f"repo-{_hash(repo_name)}" if repo_name else "repository"
|
|
73
|
+
self.remote_url = remote_url
|
|
74
|
+
self._build_identity(commits, primary_email)
|
|
75
|
+
self._build_subjects(commits)
|
|
76
|
+
self._build_replacer()
|
|
77
|
+
|
|
78
|
+
# ---------------------------------------------------------------- 构建
|
|
79
|
+
|
|
80
|
+
def _build_identity(self, commits: list[Commit], primary_email: str | None = None) -> None:
|
|
81
|
+
"""按「首次出现时间」发字母,保证同一个仓库每次跑出来别名一致。
|
|
82
|
+
|
|
83
|
+
个人画像里被分析的那个人优先拿 A —— 报告的主角叫「开发者 B」很别扭。
|
|
84
|
+
"""
|
|
85
|
+
ordered = sorted(commits, key=lambda c: c.authored_at)
|
|
86
|
+
if primary_email:
|
|
87
|
+
target = primary_email.strip().lower()
|
|
88
|
+
ordered.sort(key=lambda c: (c.email or "").strip().lower() != target)
|
|
89
|
+
for commit in ordered:
|
|
90
|
+
email = (commit.email or "").strip().lower()
|
|
91
|
+
name = (commit.author or "").strip()
|
|
92
|
+
if email and email not in self._email_map:
|
|
93
|
+
index = len(self._email_map)
|
|
94
|
+
self._email_map[email] = f"dev-{_letters(index)}@redacted"
|
|
95
|
+
if name and name not in self._name_map:
|
|
96
|
+
alias = self._email_map.get(email)
|
|
97
|
+
if alias:
|
|
98
|
+
dev = alias.split("@")[0].replace("dev-", "").upper()
|
|
99
|
+
self._name_map[name] = self._person_label(dev)
|
|
100
|
+
else:
|
|
101
|
+
self._name_map[name] = self._person_label(_letters(len(self._name_map)))
|
|
102
|
+
|
|
103
|
+
def _person_label(self, letter: str) -> str:
|
|
104
|
+
return f"开发者 {letter}" if self.lang == "zh" else f"Author {letter}"
|
|
105
|
+
|
|
106
|
+
def _build_subjects(self, commits: list[Commit]) -> None:
|
|
107
|
+
raw = {c.subject.strip() for c in commits if c.subject.strip()}
|
|
108
|
+
self._subjects = raw
|
|
109
|
+
# 彩蛋里的标题被 _clip 截断过,带省略号,必须按前缀认
|
|
110
|
+
self._subject_prefixes = {item[:47] for item in raw if len(item) > 4}
|
|
111
|
+
|
|
112
|
+
def _build_replacer(self) -> None:
|
|
113
|
+
tokens: set[str] = set(self._name_map) | set(self._email_map)
|
|
114
|
+
if self.repo_name_source:
|
|
115
|
+
tokens.add(self.repo_name_source)
|
|
116
|
+
# 邮箱前缀也单独替换,避免 prose 里只出现 `teng2002823` 这类片段
|
|
117
|
+
for email in list(self._email_map):
|
|
118
|
+
local = email.split("@")[0]
|
|
119
|
+
if len(local) >= 4:
|
|
120
|
+
tokens.add(local)
|
|
121
|
+
ordered = sorted(tokens, key=len, reverse=True)
|
|
122
|
+
self._regex = (
|
|
123
|
+
re.compile("|".join(re.escape(token) for token in ordered)) if ordered else None
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
# ---------------------------------------------------------------- 单值
|
|
127
|
+
|
|
128
|
+
def person(self, value: str) -> str:
|
|
129
|
+
value = (value or "").strip()
|
|
130
|
+
return self._name_map.get(value, self._email_map.get(value.lower(), value))
|
|
131
|
+
|
|
132
|
+
def email(self, value: str) -> str:
|
|
133
|
+
value = (value or "").strip().lower()
|
|
134
|
+
return self._email_map.get(value, f"dev-{_hash(value, 4)}@redacted")
|
|
135
|
+
|
|
136
|
+
def segment(self, token: str) -> str:
|
|
137
|
+
"""路径里的单段。通用目录名原样保留,其余按哈希替换但保持稳定。"""
|
|
138
|
+
if not token or token in GENERIC_SEGMENTS or token == "(root)":
|
|
139
|
+
return token
|
|
140
|
+
return self._segment_map.setdefault(token, f"p{_hash(token, 5)}")
|
|
141
|
+
|
|
142
|
+
def path(self, value: str) -> str:
|
|
143
|
+
if not value:
|
|
144
|
+
return value
|
|
145
|
+
parts = value.split("/")
|
|
146
|
+
out = []
|
|
147
|
+
for index, part in enumerate(parts):
|
|
148
|
+
is_last = index == len(parts) - 1
|
|
149
|
+
if is_last and "." in part.lstrip("."):
|
|
150
|
+
stem, _, ext = part.rpartition(".")
|
|
151
|
+
stem = self.segment(stem)
|
|
152
|
+
out.append(f"{stem}.{ext}")
|
|
153
|
+
else:
|
|
154
|
+
out.append(self.segment(part))
|
|
155
|
+
return "/".join(out)
|
|
156
|
+
|
|
157
|
+
def branch(self, value: str) -> str:
|
|
158
|
+
"""分支名同样是内部信息:`feat/customer-x-migration` 一个名字就够泄密了。"""
|
|
159
|
+
keep = {
|
|
160
|
+
"main", "master", "develop", "dev", "release", "feat", "feature",
|
|
161
|
+
"fix", "bugfix", "hotfix", "chore", "docs", "test", "tests", "exp",
|
|
162
|
+
}
|
|
163
|
+
parts = [part for part in (value or "").split("/") if part]
|
|
164
|
+
if not parts:
|
|
165
|
+
return value
|
|
166
|
+
out = []
|
|
167
|
+
for index, part in enumerate(parts):
|
|
168
|
+
if index == 0 and part.lower() in keep:
|
|
169
|
+
out.append(part)
|
|
170
|
+
else:
|
|
171
|
+
out.append(self.segment(part))
|
|
172
|
+
return "/".join(out)
|
|
173
|
+
|
|
174
|
+
def subject(self, kind: str) -> str:
|
|
175
|
+
label = t(f"kind.{kind}", self.lang)
|
|
176
|
+
if label == f"kind.{kind}":
|
|
177
|
+
label = kind
|
|
178
|
+
return f"【已脱敏·{label}】" if self.lang == "zh" else f"[redacted:{label}]"
|
|
179
|
+
|
|
180
|
+
def text(self, value: str) -> str:
|
|
181
|
+
"""对一段散文做替换:人名、邮箱、仓库名,以及被引号括起来的原始标题。"""
|
|
182
|
+
if not value:
|
|
183
|
+
return value
|
|
184
|
+
|
|
185
|
+
def _swap(match: re.Match) -> str:
|
|
186
|
+
inner = (match.group(1) or match.group(2) or "").strip()
|
|
187
|
+
body = inner.rstrip("…").strip()
|
|
188
|
+
if body and (body in self._subjects or body in self._subject_prefixes):
|
|
189
|
+
# 外面已经有引号了,这里只放标记,别套两层括号
|
|
190
|
+
return "「已脱敏」" if self.lang == "zh" else '"[redacted]"'
|
|
191
|
+
return match.group(0)
|
|
192
|
+
|
|
193
|
+
value = _QUOTED.sub(_swap, value)
|
|
194
|
+
value = _EMAILISH.sub(lambda m: self.email(m.group(0)), value)
|
|
195
|
+
if self._regex is not None:
|
|
196
|
+
value = self._regex.sub(lambda m: self._lookup(m.group(0)), value)
|
|
197
|
+
for raw, alias in self._segment_map.items():
|
|
198
|
+
if raw in value:
|
|
199
|
+
value = value.replace(raw, alias)
|
|
200
|
+
return value
|
|
201
|
+
|
|
202
|
+
def _lookup(self, token: str) -> str:
|
|
203
|
+
if token in self._name_map:
|
|
204
|
+
return self._name_map[token]
|
|
205
|
+
lowered = token.lower()
|
|
206
|
+
if lowered in self._email_map:
|
|
207
|
+
return self._email_map[lowered]
|
|
208
|
+
if token == self.repo_name_source:
|
|
209
|
+
return self.repo_alias
|
|
210
|
+
for email, alias in self._email_map.items():
|
|
211
|
+
if lowered == email.split("@")[0]:
|
|
212
|
+
return alias
|
|
213
|
+
return token
|
|
214
|
+
|
|
215
|
+
# ---------------------------------------------------------------- 整棵树
|
|
216
|
+
|
|
217
|
+
def apply(self, report: dict[str, Any]) -> dict[str, Any]:
|
|
218
|
+
return _walk(report, self)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _letters(index: int) -> str:
|
|
222
|
+
if index < 26:
|
|
223
|
+
return chr(ord("A") + index)
|
|
224
|
+
return f"{_letters(index // 26 - 1)}{_letters(index % 26)}"
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
_PATH_KEYS = {"path"}
|
|
228
|
+
_SUBJECT_KEYS = {"subject"}
|
|
229
|
+
_NAME_KEYS = {"author"}
|
|
230
|
+
_EMAIL_KEYS = {"email", "key"}
|
|
231
|
+
_SKIP_KEYS = {"lang", "tool", "version", "schema_version", "generated_at", "python"}
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _walk(node: Any, redactor: Redactor, key: str = "") -> Any:
|
|
235
|
+
if isinstance(node, dict):
|
|
236
|
+
return {k: _walk(v, redactor, k) for k, v in node.items()}
|
|
237
|
+
if isinstance(node, list):
|
|
238
|
+
return [_walk(item, redactor, key) for item in node]
|
|
239
|
+
if not isinstance(node, str):
|
|
240
|
+
return node
|
|
241
|
+
|
|
242
|
+
if key in _SKIP_KEYS:
|
|
243
|
+
return node
|
|
244
|
+
if key in _SUBJECT_KEYS:
|
|
245
|
+
return redactor.subject("other")
|
|
246
|
+
if key in _PATH_KEYS:
|
|
247
|
+
return redactor.path(node)
|
|
248
|
+
if key in _NAME_KEYS:
|
|
249
|
+
return redactor.person(node)
|
|
250
|
+
if key in _EMAIL_KEYS:
|
|
251
|
+
return redactor.email(node)
|
|
252
|
+
return redactor.text(node)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def redact_report(
|
|
256
|
+
report: dict[str, Any],
|
|
257
|
+
commits: list[Commit],
|
|
258
|
+
*,
|
|
259
|
+
primary_email: str | None = None,
|
|
260
|
+
) -> dict[str, Any]:
|
|
261
|
+
"""唯一入口。analyze() 在报告成形后调用一次。"""
|
|
262
|
+
meta = report.get("meta") or {}
|
|
263
|
+
repo = meta.get("repo") or {}
|
|
264
|
+
redactor = Redactor(
|
|
265
|
+
commits,
|
|
266
|
+
repo_name=repo.get("name") or "",
|
|
267
|
+
remote_url=repo.get("remote"),
|
|
268
|
+
lang=meta.get("lang", "zh"),
|
|
269
|
+
primary_email=primary_email,
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
# 结构化字段先处理掉,避免被通用文本替换改得不成形状
|
|
273
|
+
for chapter in report.get("chapters") or []:
|
|
274
|
+
if chapter.get("top_dirs"):
|
|
275
|
+
chapter["top_dirs"] = [redactor.segment(name) for name in chapter["top_dirs"]]
|
|
276
|
+
|
|
277
|
+
for row in (report.get("churn") or {}).get("dirs", []):
|
|
278
|
+
row["name"] = redactor.segment(row.get("name", ""))
|
|
279
|
+
|
|
280
|
+
persona = report.get("persona") or {}
|
|
281
|
+
for item in persona.get("top_dirs") or []:
|
|
282
|
+
item["name"] = redactor.segment(item.get("name", ""))
|
|
283
|
+
|
|
284
|
+
for event in report.get("milestones") or []:
|
|
285
|
+
if event.get("subject"):
|
|
286
|
+
event["subject"] = redactor.subject(event.get("kind", "other"))
|
|
287
|
+
|
|
288
|
+
report = _walk(report, redactor)
|
|
289
|
+
|
|
290
|
+
# _walk 返回的是新树,这里必须重新取,否则改的是旧引用
|
|
291
|
+
meta = report.get("meta") or {}
|
|
292
|
+
repo = meta.get("repo") or {}
|
|
293
|
+
if repo:
|
|
294
|
+
# 绝对路径会带出系统用户名,remote 会带出组织,分支名会带出业务
|
|
295
|
+
repo["name"] = redactor.repo_alias
|
|
296
|
+
repo["root"] = "[redacted]"
|
|
297
|
+
repo["remote"] = None
|
|
298
|
+
if repo.get("branch"):
|
|
299
|
+
repo["branch"] = redactor.branch(repo["branch"])
|
|
300
|
+
meta["anon"] = True
|
|
301
|
+
return report
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""单文件 HTML 报告渲染。
|
|
2
|
+
|
|
3
|
+
产物要求:双击能开、断网能看、发给别人不丢图。
|
|
4
|
+
所以样式、图表、数据全部内联,不引任何外链资源。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from functools import partial
|
|
11
|
+
from importlib.resources import files
|
|
12
|
+
|
|
13
|
+
from jinja2 import Environment, FileSystemLoader, select_autoescape
|
|
14
|
+
from markupsafe import Markup
|
|
15
|
+
|
|
16
|
+
from ..i18n import t
|
|
17
|
+
from . import charts
|
|
18
|
+
|
|
19
|
+
__all__ = ["build_html"]
|
|
20
|
+
|
|
21
|
+
def _kind_labels(lang: str) -> dict[str, str]:
|
|
22
|
+
"""提交类型的显示名。词条只存在 i18n 里,脱敏层和渲染层共用一份。"""
|
|
23
|
+
from ..clean import KINDS
|
|
24
|
+
|
|
25
|
+
return {kind: t(f"kind.{kind}", lang) for kind in KINDS}
|
|
26
|
+
|
|
27
|
+
_TAG_LABELS = {
|
|
28
|
+
"zh": {
|
|
29
|
+
"hot": "高频",
|
|
30
|
+
"brittle": "易碎",
|
|
31
|
+
"silo": "单人维护",
|
|
32
|
+
"volatile": "大起大落",
|
|
33
|
+
},
|
|
34
|
+
"en": {
|
|
35
|
+
"hot": "hot",
|
|
36
|
+
"brittle": "brittle",
|
|
37
|
+
"silo": "silo",
|
|
38
|
+
"volatile": "volatile",
|
|
39
|
+
},
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _environment() -> Environment:
|
|
44
|
+
template_dir = files("chronicle.render") / "templates"
|
|
45
|
+
env = Environment(
|
|
46
|
+
loader=FileSystemLoader(str(template_dir)),
|
|
47
|
+
autoescape=select_autoescape(default=True, default_for_string=True),
|
|
48
|
+
trim_blocks=True,
|
|
49
|
+
lstrip_blocks=True,
|
|
50
|
+
)
|
|
51
|
+
env.filters["num"] = lambda value: f"{int(value):,}"
|
|
52
|
+
# 0 前面不要挂加减号,「−0」看起来像 bug
|
|
53
|
+
env.filters["signnum"] = lambda value, sign: f"{sign}{int(value):,}" if value else "0"
|
|
54
|
+
return env
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def build_html(report: dict) -> str:
|
|
58
|
+
"""按视角派发到不同模板。两个模板共用同一份 CSS 令牌。"""
|
|
59
|
+
if report.get("view") == "author":
|
|
60
|
+
return _author_html(report)
|
|
61
|
+
return _project_html(report)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _project_html(report: dict) -> str:
|
|
65
|
+
env = _environment()
|
|
66
|
+
template = env.get_template("report.html.j2")
|
|
67
|
+
|
|
68
|
+
meta = report["meta"]
|
|
69
|
+
lang = meta.get("lang", "zh")
|
|
70
|
+
overview = report["overview"]
|
|
71
|
+
timeline = report["timeline"]
|
|
72
|
+
points = timeline.get("points") or []
|
|
73
|
+
chapters = report.get("chapters") or []
|
|
74
|
+
milestones = report.get("milestones") or []
|
|
75
|
+
|
|
76
|
+
return template.render(
|
|
77
|
+
meta=meta,
|
|
78
|
+
overview=overview,
|
|
79
|
+
timeline=timeline,
|
|
80
|
+
rhythm=report["rhythm"],
|
|
81
|
+
churn=report["churn"],
|
|
82
|
+
languages=report["languages"],
|
|
83
|
+
contributors=report["contributors"],
|
|
84
|
+
chapters=chapters,
|
|
85
|
+
milestones=milestones,
|
|
86
|
+
fun_facts=report.get("fun_facts") or [],
|
|
87
|
+
quote=report.get("quote") or "",
|
|
88
|
+
warnings=report.get("warnings") or [],
|
|
89
|
+
events_by_chapter=_group_events(milestones, chapters),
|
|
90
|
+
tag_label=_TAG_LABELS.get(lang, _TAG_LABELS["zh"]),
|
|
91
|
+
svg_timeline=Markup(charts.svg_timeline(points, lang=lang)),
|
|
92
|
+
svg_commit_bars=Markup(charts.svg_commit_bars(points, lang=lang)),
|
|
93
|
+
svg_heatmap=Markup(charts.svg_heatmap(report["rhythm"], lang=lang)),
|
|
94
|
+
svg_share_card=Markup(charts.svg_share_card(report)),
|
|
95
|
+
t=partial(t, lang=lang),
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _author_html(report: dict) -> str:
|
|
100
|
+
env = _environment()
|
|
101
|
+
template = env.get_template("author.html.j2")
|
|
102
|
+
|
|
103
|
+
meta = report["meta"]
|
|
104
|
+
lang = meta.get("lang", "zh")
|
|
105
|
+
points = (report.get("timeline") or {}).get("points") or []
|
|
106
|
+
|
|
107
|
+
return template.render(
|
|
108
|
+
meta=meta,
|
|
109
|
+
persona=report.get("persona") or {},
|
|
110
|
+
quote=report.get("quote") or "",
|
|
111
|
+
chapters=report.get("chapters") or [],
|
|
112
|
+
peers=report.get("peers") or [],
|
|
113
|
+
fun_facts=report.get("fun_facts") or [],
|
|
114
|
+
warnings=report.get("warnings") or [],
|
|
115
|
+
kind_label=_kind_labels(lang),
|
|
116
|
+
svg_heatmap=Markup(charts.svg_heatmap(report["rhythm"], lang=lang)),
|
|
117
|
+
svg_commit_bars=Markup(charts.svg_commit_bars(points, lang=lang)),
|
|
118
|
+
svg_share_card=Markup(charts.svg_share_card_author(report)),
|
|
119
|
+
t=partial(t, lang=lang),
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _group_events(events: list[dict], chapters: list[dict]) -> dict[str, list[dict]]:
|
|
124
|
+
"""把里程碑分配到所属章节。落在章节边界外的丢掉,不硬塞。"""
|
|
125
|
+
grouped: dict[str, list[dict]] = {}
|
|
126
|
+
for event in events:
|
|
127
|
+
for chapter in chapters:
|
|
128
|
+
if chapter["start"] <= event["date"] <= chapter["end"]:
|
|
129
|
+
grouped.setdefault(chapter["id"], []).append(event)
|
|
130
|
+
break
|
|
131
|
+
return grouped
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def dump_json(report: dict, path) -> None:
|
|
135
|
+
"""中间态导出。ensure_ascii=False 让中文可读,方便直接人肉检查。"""
|
|
136
|
+
from pathlib import Path
|
|
137
|
+
|
|
138
|
+
target = Path(path)
|
|
139
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
140
|
+
target.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|