dsh-commit-journal 0.3.0 → 0.6.0

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.
package/lib/index.js CHANGED
@@ -13,12 +13,17 @@ import isoWeek from "dayjs/plugin/isoWeek.js";
13
13
  import { createServer } from "http";
14
14
  // src/core/types.ts
15
15
  const DEFAULT_UI_PORT = 39282;
16
+ const DEFAULT_REPORT_GROUP_BY = "repo";
16
17
  // src/core/settings.ts
17
18
  const defaults = {
18
19
  exportsPath: "",
19
20
  syncIntervalMinutes: 30,
20
21
  syncLookbackDays: 90,
21
- uiPort: DEFAULT_UI_PORT
22
+ uiPort: DEFAULT_UI_PORT,
23
+ reportExcludeMerge: true,
24
+ reportExcludeTypes: [],
25
+ reportExcludeAuthors: [],
26
+ reportGroupBy: DEFAULT_REPORT_GROUP_BY
22
27
  };
23
28
  function load$1() {
24
29
  const path = settingsPath();
@@ -35,6 +40,10 @@ function load$1() {
35
40
  function save$1(settings) {
36
41
  writeFileSync(settingsPath(), JSON.stringify(settings, null, 2), "utf8");
37
42
  }
43
+ function normalizeStringList(value) {
44
+ if (!Array.isArray(value)) return [];
45
+ return value.map((v) => String(v).trim()).filter(Boolean);
46
+ }
38
47
  function updateSettings(patch) {
39
48
  const next = {
40
49
  ...load$1(),
@@ -43,9 +52,17 @@ function updateSettings(patch) {
43
52
  if (next.syncIntervalMinutes < 5) next.syncIntervalMinutes = 5;
44
53
  if (next.syncLookbackDays < 1) next.syncLookbackDays = 1;
45
54
  if (next.uiPort < 1024 || next.uiPort > 65535) next.uiPort = DEFAULT_UI_PORT;
55
+ if (patch.reportExcludeMerge !== void 0) next.reportExcludeMerge = Boolean(patch.reportExcludeMerge);
56
+ if (patch.reportExcludeTypes !== void 0) next.reportExcludeTypes = normalizeStringList(patch.reportExcludeTypes);
57
+ if (patch.reportExcludeAuthors !== void 0) next.reportExcludeAuthors = normalizeStringList(patch.reportExcludeAuthors);
58
+ if (patch.reportGroupBy !== void 0) next.reportGroupBy = normalizeGroupBy(patch.reportGroupBy);
46
59
  save$1(next);
47
60
  return next;
48
61
  }
62
+ function normalizeGroupBy(value) {
63
+ if (value === "day" || value === "flat" || value === "repo" || value === "ticket") return value;
64
+ return DEFAULT_REPORT_GROUP_BY;
65
+ }
49
66
  function getExportsPathSetting() {
50
67
  return (load$1().exportsPath || "").trim();
51
68
  }
@@ -58,10 +75,27 @@ function getSyncLookbackDays() {
58
75
  function getUiPort() {
59
76
  return load$1().uiPort || 39282;
60
77
  }
78
+ function getReportExcludeMerge() {
79
+ const v = load$1().reportExcludeMerge;
80
+ return v === void 0 ? true : Boolean(v);
81
+ }
82
+ function getReportExcludeTypes() {
83
+ return normalizeStringList(load$1().reportExcludeTypes);
84
+ }
85
+ function getReportExcludeAuthors() {
86
+ return normalizeStringList(load$1().reportExcludeAuthors);
87
+ }
88
+ function getReportGroupBy() {
89
+ return normalizeGroupBy(load$1().reportGroupBy);
90
+ }
61
91
  function describeSettings() {
62
92
  const s = load$1();
63
93
  return {
64
94
  ...s,
95
+ reportExcludeMerge: getReportExcludeMerge(),
96
+ reportExcludeTypes: getReportExcludeTypes(),
97
+ reportExcludeAuthors: getReportExcludeAuthors(),
98
+ reportGroupBy: getReportGroupBy(),
65
99
  resolvedExportsPath: s.exportsPath?.trim() || defaultExportsDir(),
66
100
  defaultExportsPath: defaultExportsDir()
67
101
  };
@@ -121,6 +155,51 @@ function commitTitleLine(commit) {
121
155
  const full = commitFullText(commit);
122
156
  return full.split("\n").find((l) => l.trim())?.trim() || full;
123
157
  }
158
+ // src/core/commitStats.ts
159
+ /**
160
+ * 汇总有增删行数据的提交
161
+ */
162
+ function sumCommitDiffStats(commits) {
163
+ let additions = 0;
164
+ let deletions = 0;
165
+ let filesChanged = 0;
166
+ let withStats = 0;
167
+ let withFiles = 0;
168
+ for (const c of commits) {
169
+ if (c.additions == null && c.deletions == null) continue;
170
+ withStats++;
171
+ additions += c.additions ?? 0;
172
+ deletions += c.deletions ?? 0;
173
+ if (c.filesChanged != null) {
174
+ withFiles++;
175
+ filesChanged += c.filesChanged;
176
+ }
177
+ }
178
+ return {
179
+ additions,
180
+ deletions,
181
+ filesChanged: withFiles ? filesChanged : 0,
182
+ withStats
183
+ };
184
+ }
185
+ /**
186
+ * 单条提交的 `+a −d` / `· n files` 文案;无数据返回空串
187
+ */
188
+ function formatCommitDiffStats(c) {
189
+ if (c.additions == null && c.deletions == null) return "";
190
+ let s = `+${c.additions ?? 0} −${c.deletions ?? 0}`;
191
+ if (c.filesChanged != null) s += ` · ${c.filesChanged} files`;
192
+ return s;
193
+ }
194
+ /**
195
+ * 区间合计文案(仅当至少一条有 stats)
196
+ */
197
+ function formatDiffStatsSum(sum) {
198
+ if (!sum.withStats) return "";
199
+ let s = `+${sum.additions} / −${sum.deletions}`;
200
+ if (sum.filesChanged > 0) s += ` · ${sum.filesChanged} files`;
201
+ return s;
202
+ }
124
203
  // src/core/repoDisplay.ts
125
204
  function shortRepoPath(pathWithNamespace, organizationId) {
126
205
  const raw = (pathWithNamespace || "").trim();
@@ -300,6 +379,12 @@ const db = {
300
379
  else data.syncState.push(state);
301
380
  save(data);
302
381
  },
382
+ getCommit(accountId, sha) {
383
+ return load().commits.find((c) => c.accountId === accountId && c.sha === sha);
384
+ },
385
+ listCommitsMissingStats(accountId, limit = 80) {
386
+ return load().commits.filter((c) => c.accountId === accountId && c.additions == null && c.deletions == null).sort((a, b) => b.committedAt.localeCompare(a.committedAt)).slice(0, Math.max(0, limit)).map((c) => ({ ...c }));
387
+ },
303
388
  insertCommits(commits) {
304
389
  if (commits.length === 0) return 0;
305
390
  const data = load();
@@ -318,16 +403,22 @@ const db = {
318
403
  const prev = data.commits[idx];
319
404
  const nextMsg = (c.message || "").trim();
320
405
  const prevMsg = (prev.message || "").trim();
321
- if (nextMsg && nextMsg.length > prevMsg.length) {
322
- data.commits[idx] = {
323
- ...prev,
324
- title: c.title || prev.title,
325
- message: nextMsg,
326
- webUrl: c.webUrl || prev.webUrl,
327
- syncedAt: c.syncedAt || prev.syncedAt
328
- };
329
- updated++;
330
- }
406
+ const msgUpgrade = Boolean(nextMsg && nextMsg.length > prevMsg.length);
407
+ const statsUpgrade = prev.additions == null && prev.deletions == null && (c.additions != null || c.deletions != null || c.filesChanged != null);
408
+ if (!msgUpgrade && !statsUpgrade) continue;
409
+ data.commits[idx] = {
410
+ ...prev,
411
+ title: msgUpgrade ? c.title || prev.title : prev.title,
412
+ message: msgUpgrade ? nextMsg : prev.message,
413
+ webUrl: c.webUrl || prev.webUrl,
414
+ syncedAt: c.syncedAt || prev.syncedAt,
415
+ ...statsUpgrade ? {
416
+ additions: c.additions,
417
+ deletions: c.deletions,
418
+ filesChanged: c.filesChanged
419
+ } : {}
420
+ };
421
+ updated++;
331
422
  }
332
423
  if (inserted > 0 || updated > 0) save(data);
333
424
  return inserted;
@@ -369,18 +460,59 @@ const db = {
369
460
  yearSet.add(at.year());
370
461
  if (at.isBefore(from, "day") || at.isAfter(to, "day")) continue;
371
462
  const key = at.format("YYYY-MM-DD");
372
- byDay.set(key, (byDay.get(key) ?? 0) + 1);
463
+ let bucket = byDay.get(key);
464
+ if (!bucket) {
465
+ bucket = {
466
+ count: 0,
467
+ additions: 0,
468
+ deletions: 0,
469
+ filesChanged: 0,
470
+ withStats: 0,
471
+ withFiles: 0
472
+ };
473
+ byDay.set(key, bucket);
474
+ }
475
+ bucket.count++;
476
+ if (c.additions != null || c.deletions != null) {
477
+ bucket.withStats++;
478
+ bucket.additions += c.additions ?? 0;
479
+ bucket.deletions += c.deletions ?? 0;
480
+ }
481
+ if (c.filesChanged != null) {
482
+ bucket.withFiles++;
483
+ bucket.filesChanged += c.filesChanged;
484
+ }
373
485
  }
374
- const days = Array.from(byDay.entries()).map(([date, count]) => ({
375
- date,
376
- count
377
- })).sort((a, b) => a.date.localeCompare(b.date));
486
+ const days = Array.from(byDay.entries()).map(([date, b]) => {
487
+ const day = {
488
+ date,
489
+ count: b.count
490
+ };
491
+ if (b.withStats > 0) {
492
+ day.additions = b.additions;
493
+ day.deletions = b.deletions;
494
+ }
495
+ if (b.withFiles > 0) day.filesChanged = b.filesChanged;
496
+ return day;
497
+ }).sort((a, b) => a.date.localeCompare(b.date));
378
498
  let longestStreak = 0;
379
499
  let streak = 0;
380
500
  let maxDayCount = 0;
381
501
  let maxDayDate = null;
502
+ let totalAdditions = 0;
503
+ let totalDeletions = 0;
504
+ let totalFilesChanged = 0;
505
+ let commitsWithStats = 0;
506
+ for (const d of days) {
507
+ if (d.additions != null || d.deletions != null) {
508
+ totalAdditions += d.additions ?? 0;
509
+ totalDeletions += d.deletions ?? 0;
510
+ }
511
+ if (d.filesChanged != null) totalFilesChanged += d.filesChanged;
512
+ }
513
+ for (const b of byDay.values()) commitsWithStats += b.withStats;
382
514
  for (let cur = from, guard = 0; !cur.isAfter(to, "day") && guard < 1e3; guard++) {
383
- const count = byDay.get(cur.format("YYYY-MM-DD")) ?? 0;
515
+ const count = byDay.get(cur.format("YYYY-MM-DD"))?.count ?? 0;
384
516
  if (count > 0) {
385
517
  streak++;
386
518
  if (streak > longestStreak) longestStreak = streak;
@@ -401,7 +533,11 @@ const db = {
401
533
  activeDays: days.length,
402
534
  longestStreak,
403
535
  maxDayCount,
404
- maxDayDate
536
+ maxDayDate,
537
+ totalAdditions,
538
+ totalDeletions,
539
+ totalFilesChanged,
540
+ commitsWithStats
405
541
  }
406
542
  };
407
543
  },
@@ -656,6 +792,37 @@ function validateAccount(account, token) {
656
792
  if (account.edition === "region" && !account.apiBaseUrl) throw new Error("Region 版需填写 API Base URL");
657
793
  }
658
794
  }
795
+ // src/providers/rateLimit.ts
796
+ /**
797
+ * 限流退避与错误文案截断(enrich 补 stats 用)
798
+ */
799
+ function sleep(ms) {
800
+ return new Promise((resolve) => setTimeout(resolve, ms));
801
+ }
802
+ function truncateErr(msg, max = 180) {
803
+ const s = String(msg ?? "");
804
+ return s.length <= max ? s : `${s.slice(0, max)}…`;
805
+ }
806
+ function isRateLimited(err) {
807
+ return /\b429\b|rate.?limit|too many requests/i.test(String(err?.message ?? err));
808
+ }
809
+ /**
810
+ * 遇 429 / rate limit 时指数退避重试
811
+ */
812
+ async function withRateLimitRetry(fn, opts) {
813
+ const retries = Math.max(0, opts?.retries ?? 3);
814
+ let last;
815
+ for (let i = 0; i <= retries; i++) try {
816
+ return await fn();
817
+ } catch (e) {
818
+ last = e;
819
+ if (!isRateLimited(e) || i === retries) throw e;
820
+ const waitMs = 1e3 * 2 ** i;
821
+ opts?.onRetry?.(waitMs);
822
+ await sleep(waitMs);
823
+ }
824
+ throw last;
825
+ }
659
826
  // src/providers/codeup/index.ts
660
827
  function baseUrl(account) {
661
828
  if (account.edition === "region") {
@@ -686,9 +853,10 @@ async function request$2(account, token, path, query, options) {
686
853
  });
687
854
  if (!res.ok) {
688
855
  const body = await res.text().catch(() => "");
856
+ const brief = body.length > 200 ? `${body.slice(0, 200)}…` : body;
689
857
  if (options?.soft) throw new Error(`${res.status} ${body.includes("no permission") ? "Forbidden" : res.statusText}`);
690
- if (res.status === 403 || body.includes("no permission")) throw new Error(`令牌无 API 权限(403)。请到云效「个人设置 → 个人访问令牌」删除后重建,代码管理里至少将「代码仓库」「提交」设为只读;并确认账号选的是中心版还是 Region 版。 原始信息: ${body || res.statusText}`);
691
- throw new Error(`Codeup API ${res.status}: ${body || res.statusText}`);
858
+ if (res.status === 403 || body.includes("no permission")) throw new Error(`令牌无 API 权限(403)。请到云效「个人设置 → 个人访问令牌」删除后重建,代码管理里至少将「代码仓库」「提交」设为只读;并确认账号选的是中心版还是 Region 版。 原始信息: ${brief || res.statusText}`);
859
+ throw new Error(`Codeup API ${res.status}: ${brief || res.statusText}`);
692
860
  }
693
861
  return {
694
862
  data: await res.json(),
@@ -757,6 +925,48 @@ function asRows(data) {
757
925
  if (Array.isArray(data?.list)) return data.list;
758
926
  return [];
759
927
  }
928
+ function unwrapCommit(data) {
929
+ if (!data || typeof data !== "object") return data;
930
+ if (data.result && typeof data.result === "object" && !Array.isArray(data.result)) return data.result;
931
+ return data;
932
+ }
933
+ function parseCommitStats(raw) {
934
+ const stats = raw?.stats || raw?.commitStats || raw?.commit_stats;
935
+ if (!stats || typeof stats !== "object") return {};
936
+ const addRaw = stats.additions ?? stats.addition ?? stats.Additions;
937
+ const delRaw = stats.deletions ?? stats.deletion ?? stats.Deletions;
938
+ const additions = addRaw != null && Number.isFinite(Number(addRaw)) ? Number(addRaw) : void 0;
939
+ const deletions = delRaw != null && Number.isFinite(Number(delRaw)) ? Number(delRaw) : void 0;
940
+ return {
941
+ ...additions != null ? { additions } : {},
942
+ ...deletions != null ? { deletions } : {}
943
+ };
944
+ }
945
+ const STATS_CONCURRENCY$1 = 4;
946
+ /**
947
+ * Codeup 列表不带 stats;仅用 GetCommit 的 stats(不拉 /diff,避免整份 patch)
948
+ */
949
+ async function enrichCodeupCommitStats(account, token, repoId, commits, onWarn) {
950
+ const pending = commits.filter((c) => c.additions == null && c.deletions == null);
951
+ if (!pending.length) return;
952
+ let next = 0;
953
+ const workers = Array.from({ length: Math.min(STATS_CONCURRENCY$1, pending.length) }, async () => {
954
+ while (next < pending.length) {
955
+ const idx = next++;
956
+ const c = pending[idx];
957
+ try {
958
+ const { data } = await withRateLimitRetry(() => request$2(account, token, `/repositories/${repoId}/commits/${encodeURIComponent(c.sha)}`), { onRetry: (waitMs) => onWarn?.(`Codeup 限流,${c.sha.slice(0, 8)} 将在 ${waitMs}ms 后重试`) });
959
+ const fromDetail = parseCommitStats(unwrapCommit(data));
960
+ if (fromDetail.additions != null) c.additions = fromDetail.additions;
961
+ if (fromDetail.deletions != null) c.deletions = fromDetail.deletions;
962
+ if (c.additions == null && c.deletions == null) onWarn?.(`Codeup 提交 ${c.sha.slice(0, 8)} 详情无 stats,未能补全增删行`);
963
+ } catch (e) {
964
+ onWarn?.(`Codeup 提交 ${c.sha.slice(0, 8)} stats 拉取失败: ${truncateErr(e?.message || e)}`);
965
+ }
966
+ }
967
+ });
968
+ await Promise.all(workers);
969
+ }
760
970
  /**
761
971
  * 云效 Codeup VCS 适配器
762
972
  */
@@ -861,6 +1071,7 @@ const codeupProvider = {
861
1071
  const committedDate = String(item.committedDate || item.authoredDate || "");
862
1072
  const ms = Date.parse(committedDate);
863
1073
  if (Number.isFinite(ms) && ms < windowOldestMs) windowOldestMs = ms;
1074
+ const { additions, deletions } = parseCommitStats(item);
864
1075
  all.push({
865
1076
  sha: id,
866
1077
  shortId: String(item.shortId || id.slice(0, 8)),
@@ -870,7 +1081,11 @@ const codeupProvider = {
870
1081
  authorEmail: String(item.authorEmail || ""),
871
1082
  authoredAt: String(item.authoredDate || committedDate || ""),
872
1083
  committedAt: committedDate,
873
- webUrl: String(item.webUrl || "")
1084
+ webUrl: String(item.webUrl || ""),
1085
+ ...additions != null || deletions != null ? {
1086
+ additions,
1087
+ deletions
1088
+ } : {}
874
1089
  });
875
1090
  }
876
1091
  if (added === 0) {
@@ -1041,8 +1256,9 @@ async function request$1(account, token, pathOrUrl, query) {
1041
1256
  });
1042
1257
  if (!res.ok) {
1043
1258
  const body = await res.text().catch(() => "");
1044
- if (res.status === 401 || res.status === 403) throw new Error(`GitHub 令牌无效或权限不足(${res.status})。请确认 PAT 至少具备 repo(私有仓)或 public_repo 只读权限。 原始信息: ${body || res.statusText}`);
1045
- throw new Error(`GitHub API ${res.status}: ${body || res.statusText}`);
1259
+ const brief = body.length > 200 ? `${body.slice(0, 200)}…` : body;
1260
+ if (res.status === 401 || res.status === 403) throw new Error(`GitHub 令牌无效或权限不足(${res.status})。请确认 PAT 至少具备 repo(私有仓)或 public_repo 只读权限。 原始信息: ${brief || res.statusText}`);
1261
+ throw new Error(`GitHub API ${res.status}: ${brief || res.statusText}`);
1046
1262
  }
1047
1263
  return {
1048
1264
  data: await res.json(),
@@ -1086,6 +1302,10 @@ function mapCommit$1(item) {
1086
1302
  const committer = commit.committer || {};
1087
1303
  const authoredAt = String(author.date || committer.date || "");
1088
1304
  const committedAt = String(committer.date || author.date || "");
1305
+ const stats = item.stats;
1306
+ const additions = stats && stats.additions != null && Number.isFinite(Number(stats.additions)) ? Number(stats.additions) : void 0;
1307
+ const deletions = stats && stats.deletions != null && Number.isFinite(Number(stats.deletions)) ? Number(stats.deletions) : void 0;
1308
+ const filesChanged = Array.isArray(item.files) && item.files.length > 0 && item.files.length < 300 ? item.files.length : void 0;
1089
1309
  return {
1090
1310
  sha,
1091
1311
  shortId: sha.slice(0, 8),
@@ -1095,9 +1315,39 @@ function mapCommit$1(item) {
1095
1315
  authorEmail: String(author.email || ""),
1096
1316
  authoredAt,
1097
1317
  committedAt,
1098
- webUrl: String(item.html_url || "")
1318
+ webUrl: String(item.html_url || ""),
1319
+ ...additions != null || deletions != null ? {
1320
+ additions,
1321
+ deletions
1322
+ } : {},
1323
+ ...filesChanged != null ? { filesChanged } : {}
1099
1324
  };
1100
1325
  }
1326
+ const STATS_CONCURRENCY = 4;
1327
+ /**
1328
+ * 为缺 stats 的提交限并发拉取详情(列表接口不含增删行)
1329
+ */
1330
+ async function enrichGithubCommitStats(account, token, repoId, commits, onWarn) {
1331
+ const pending = commits.filter((c) => c.additions == null && c.deletions == null);
1332
+ if (!pending.length) return;
1333
+ let next = 0;
1334
+ const workers = Array.from({ length: Math.min(STATS_CONCURRENCY, pending.length) }, async () => {
1335
+ while (next < pending.length) {
1336
+ const idx = next++;
1337
+ const c = pending[idx];
1338
+ try {
1339
+ const { data } = await withRateLimitRetry(() => request$1(account, token, `/repos/${repoId}/commits/${encodeURIComponent(c.sha)}`), { onRetry: (waitMs) => onWarn?.(`GitHub 限流,${c.sha.slice(0, 8)} 将在 ${waitMs}ms 后重试`) });
1340
+ const mapped = mapCommit$1(data);
1341
+ if (mapped.additions != null) c.additions = mapped.additions;
1342
+ if (mapped.deletions != null) c.deletions = mapped.deletions;
1343
+ if (mapped.filesChanged != null) c.filesChanged = mapped.filesChanged;
1344
+ } catch (e) {
1345
+ onWarn?.(`GitHub 提交 ${c.sha.slice(0, 8)} stats 拉取失败: ${truncateErr(e?.message || e)}`);
1346
+ }
1347
+ }
1348
+ });
1349
+ await Promise.all(workers);
1350
+ }
1101
1351
  async function paginateRepos(account, token, firstPath, query) {
1102
1352
  const all = [];
1103
1353
  let nextUrl = null;
@@ -1282,6 +1532,9 @@ function mapCommit(item) {
1282
1532
  const message = String(item.message || "");
1283
1533
  const title = String(item.title || message.split("\n").find((l) => l.trim()) || "");
1284
1534
  const committedAt = String(item.committed_date || item.authored_date || "");
1535
+ const stats = item.stats;
1536
+ const additions = stats && stats.additions != null && Number.isFinite(Number(stats.additions)) ? Number(stats.additions) : void 0;
1537
+ const deletions = stats && stats.deletions != null && Number.isFinite(Number(stats.deletions)) ? Number(stats.deletions) : void 0;
1285
1538
  return {
1286
1539
  sha: id,
1287
1540
  shortId: String(item.short_id || id.slice(0, 8)),
@@ -1291,7 +1544,11 @@ function mapCommit(item) {
1291
1544
  authorEmail: String(item.author_email || ""),
1292
1545
  authoredAt: String(item.authored_date || committedAt || ""),
1293
1546
  committedAt,
1294
- webUrl: String(item.web_url || "")
1547
+ webUrl: String(item.web_url || ""),
1548
+ ...additions != null || deletions != null ? {
1549
+ additions,
1550
+ deletions
1551
+ } : {}
1295
1552
  };
1296
1553
  }
1297
1554
  function projectsPath(account) {
@@ -1378,7 +1635,8 @@ const gitlabProvider = {
1378
1635
  ref_name: opts.ref,
1379
1636
  since: opts.since,
1380
1637
  page,
1381
- per_page: COMMIT_PER_PAGE
1638
+ per_page: COMMIT_PER_PAGE,
1639
+ with_stats: true
1382
1640
  });
1383
1641
  pages++;
1384
1642
  const rows = Array.isArray(data) ? data : [];
@@ -1640,7 +1898,8 @@ const localGitProvider = {
1640
1898
  opts.ref || "HEAD",
1641
1899
  "--no-merges",
1642
1900
  "--date=iso-strict",
1643
- "--format=%H%x1f%h%x1f%s%x1f%b%x1f%an%x1f%ae%x1f%aI%x1f%cI%x1e"
1901
+ "--format=%H%x1f%h%x1f%s%x1f%b%x1f%an%x1f%ae%x1f%aI%x1f%cI%x1e",
1902
+ "--numstat"
1644
1903
  ];
1645
1904
  if (opts.since) args.push(`--since=${opts.since}`);
1646
1905
  const max = Math.max(1, (opts.maxPages ?? 20) * 100);
@@ -1658,23 +1917,23 @@ const localGitProvider = {
1658
1917
  throw e;
1659
1918
  }
1660
1919
  const commits = [];
1661
- const records = raw.split("").map((s) => s.trim()).filter(Boolean);
1662
- for (const rec of records) {
1663
- const parts = rec.split("");
1664
- if (parts.length < 8) continue;
1665
- const [sha, shortId, title, messageBody, authorName, authorEmail, authoredAt, committedAt] = parts;
1666
- const message = [title, messageBody].filter(Boolean).join("\n").trim();
1667
- commits.push({
1668
- sha,
1669
- shortId: shortId || sha.slice(0, 7),
1670
- title: title || sha.slice(0, 7),
1671
- message: message || title || "",
1672
- authorName: authorName || "",
1673
- authorEmail: authorEmail || "",
1674
- authoredAt: authoredAt || committedAt || (/* @__PURE__ */ new Date()).toISOString(),
1675
- committedAt: committedAt || authoredAt || (/* @__PURE__ */ new Date()).toISOString(),
1676
- webUrl: ""
1677
- });
1920
+ const parts = raw.split("");
1921
+ for (let i = 0; i < parts.length; i++) {
1922
+ const chunk = parts[i];
1923
+ if (i === 0) {
1924
+ const c = parseLocalCommitFields(chunk);
1925
+ if (c) commits.push(c);
1926
+ continue;
1927
+ }
1928
+ const { stats, rest } = parseNumstatPrefix(chunk);
1929
+ if (commits.length > 0) {
1930
+ const prev = commits[commits.length - 1];
1931
+ prev.additions = stats.additions;
1932
+ prev.deletions = stats.deletions;
1933
+ prev.filesChanged = stats.filesChanged;
1934
+ }
1935
+ const c = parseLocalCommitFields(rest);
1936
+ if (c) commits.push(c);
1678
1937
  }
1679
1938
  return {
1680
1939
  commits,
@@ -1683,6 +1942,51 @@ const localGitProvider = {
1683
1942
  };
1684
1943
  }
1685
1944
  };
1945
+ function parseLocalCommitFields(raw) {
1946
+ const text = raw.replace(/^\r?\n+/, "").replace(/\r?\n+$/, "");
1947
+ if (!text.trim()) return null;
1948
+ const parts = text.split("");
1949
+ if (parts.length < 8) return null;
1950
+ const [sha, shortId, title, messageBody, authorName, authorEmail, authoredAt, committedAt] = parts;
1951
+ if (!sha?.trim()) return null;
1952
+ const message = [title, messageBody].filter(Boolean).join("\n").trim();
1953
+ return {
1954
+ sha: sha.trim(),
1955
+ shortId: (shortId || sha.slice(0, 7)).trim(),
1956
+ title: (title || sha.slice(0, 7)).trim(),
1957
+ message: message || title || "",
1958
+ authorName: authorName || "",
1959
+ authorEmail: authorEmail || "",
1960
+ authoredAt: authoredAt || committedAt || (/* @__PURE__ */ new Date()).toISOString(),
1961
+ committedAt: committedAt || authoredAt || (/* @__PURE__ */ new Date()).toISOString(),
1962
+ webUrl: ""
1963
+ };
1964
+ }
1965
+ function parseNumstatPrefix(raw) {
1966
+ const lines = raw.split(/\r?\n/);
1967
+ let i = 0;
1968
+ while (i < lines.length && !lines[i].trim()) i++;
1969
+ let additions = 0;
1970
+ let deletions = 0;
1971
+ let filesChanged = 0;
1972
+ while (i < lines.length) {
1973
+ const m = lines[i].match(/^(\d+|-)\t(\d+|-)\t(.*)$/);
1974
+ if (!m) break;
1975
+ filesChanged++;
1976
+ if (m[1] !== "-") additions += Number(m[1]);
1977
+ if (m[2] !== "-") deletions += Number(m[2]);
1978
+ i++;
1979
+ }
1980
+ while (i < lines.length && !lines[i].trim()) i++;
1981
+ return {
1982
+ stats: {
1983
+ additions,
1984
+ deletions,
1985
+ filesChanged
1986
+ },
1987
+ rest: lines.slice(i).join("\n")
1988
+ };
1989
+ }
1686
1990
  // src/providers/index.ts
1687
1991
  const providers = {
1688
1992
  codeup: codeupProvider,
@@ -1702,6 +2006,15 @@ const timers = /* @__PURE__ */ new Map();
1702
2006
  const syncing = /* @__PURE__ */ new Set();
1703
2007
  const DAY_MS = 864e5;
1704
2008
  const INCREMENTAL_OVERLAP_MS = 2 * DAY_MS;
2009
+ const STATS_BACKFILL_PER_SYNC = 100;
2010
+ async function fillCommitStats(account, token, repoId, commits, onWarn) {
2011
+ const need = commits.filter((c) => c.additions == null && c.deletions == null);
2012
+ if (!need.length) return 0;
2013
+ if (account.provider === "github") await enrichGithubCommitStats(account, token, repoId, need, onWarn);
2014
+ else if (account.provider === "codeup") await enrichCodeupCommitStats(account, token, repoId, need, onWarn);
2015
+ else return 0;
2016
+ return need.filter((c) => c.additions != null || c.deletions != null).length;
2017
+ }
1705
2018
  function toApiTime(iso) {
1706
2019
  const t = Date.parse(iso);
1707
2020
  return (Number.isFinite(t) ? new Date(t) : new Date(iso)).toISOString().replace(/\.\d{3}Z$/, "Z");
@@ -1729,11 +2042,13 @@ function writeDailyExports(accountId, commits) {
1729
2042
  for (const c of list) {
1730
2043
  if (existing.includes(c.sha)) continue;
1731
2044
  const [first, ...rest] = commitFullText(c).split("\n");
1732
- lines.push(`- **[${c.repoName}]** ${first}`);
2045
+ const stats = formatCommitDiffStats(c);
2046
+ lines.push(`- **[${c.repoName}]** ${stats ? `${first}(${stats})` : first}`);
1733
2047
  for (const line of rest) lines.push(` ${line}`);
1734
2048
  lines.push(` - 时间: ${c.committedAt}`);
1735
2049
  lines.push(` - 作者: ${c.authorName} <${c.authorEmail}>`);
1736
2050
  lines.push(` - SHA: \`${c.shortId}\` (${c.sha})`);
2051
+ if (stats) lines.push(` - 变更: ${stats}`);
1737
2052
  if (c.webUrl) lines.push(` - 链接: ${c.webUrl}`);
1738
2053
  lines.push("");
1739
2054
  }
@@ -1753,6 +2068,7 @@ async function syncAccount(accountId, repoIds) {
1753
2068
  let inserted = 0;
1754
2069
  let matched = 0;
1755
2070
  let truncated = 0;
2071
+ let statsFilled = 0;
1756
2072
  try {
1757
2073
  const account = getAccount(accountId);
1758
2074
  if (!account) throw new Error("账号不存在");
@@ -1802,10 +2118,11 @@ async function syncAccount(accountId, repoIds) {
1802
2118
  });
1803
2119
  }
1804
2120
  const now = (/* @__PURE__ */ new Date()).toISOString();
2121
+ const batch = [];
1805
2122
  for (const c of commits) {
1806
2123
  if (!matchAuthor(account, c.authorName, c.authorEmail)) continue;
1807
2124
  matched++;
1808
- newCommits.push({
2125
+ batch.push({
1809
2126
  id: v4(),
1810
2127
  accountId,
1811
2128
  repoId: repo.id,
@@ -1818,9 +2135,25 @@ async function syncAccount(accountId, repoIds) {
1818
2135
  authorEmail: c.authorEmail,
1819
2136
  committedAt: c.committedAt || c.authoredAt,
1820
2137
  webUrl: c.webUrl,
1821
- syncedAt: now
2138
+ syncedAt: now,
2139
+ ...c.additions != null ? { additions: c.additions } : {},
2140
+ ...c.deletions != null ? { deletions: c.deletions } : {},
2141
+ ...c.filesChanged != null ? { filesChanged: c.filesChanged } : {}
1822
2142
  });
1823
2143
  }
2144
+ if ((account.provider === "github" || account.provider === "codeup") && batch.length > 0) {
2145
+ const onWarn = (message) => {
2146
+ db.addSyncLog({
2147
+ id: v4(),
2148
+ accountId,
2149
+ at: (/* @__PURE__ */ new Date()).toISOString(),
2150
+ level: "warn",
2151
+ message: `${shortRepoPath(repo.fullName || repo.name, account.organizationId)}: ${message}`
2152
+ });
2153
+ };
2154
+ statsFilled += await fillCommitStats(account, token, repo.id, batch, onWarn);
2155
+ }
2156
+ newCommits.push(...batch);
1824
2157
  db.setSyncState({
1825
2158
  accountId,
1826
2159
  repoId: repo.id,
@@ -1840,12 +2173,37 @@ async function syncAccount(accountId, repoIds) {
1840
2173
  }
1841
2174
  inserted = db.insertCommits(newCommits);
1842
2175
  writeDailyExports(accountId, newCommits);
2176
+ if (account.provider === "github" || account.provider === "codeup") {
2177
+ const pending = db.listCommitsMissingStats(accountId, STATS_BACKFILL_PER_SYNC);
2178
+ if (pending.length > 0) {
2179
+ const byRepo = /* @__PURE__ */ new Map();
2180
+ for (const c of pending) {
2181
+ if (!byRepo.has(c.repoId)) byRepo.set(c.repoId, []);
2182
+ byRepo.get(c.repoId).push(c);
2183
+ }
2184
+ const onWarn = (message) => {
2185
+ db.addSyncLog({
2186
+ id: v4(),
2187
+ accountId,
2188
+ at: (/* @__PURE__ */ new Date()).toISOString(),
2189
+ level: "warn",
2190
+ message
2191
+ });
2192
+ };
2193
+ for (const [repoId, list] of byRepo) try {
2194
+ statsFilled += await fillCommitStats(account, token, repoId, list, onWarn);
2195
+ } catch (e) {
2196
+ onWarn(`回填 stats 失败(repo ${repoId}): ${e?.message || e}`);
2197
+ }
2198
+ db.insertCommits(pending);
2199
+ }
2200
+ }
1843
2201
  db.addSyncLog({
1844
2202
  id: v4(),
1845
2203
  accountId,
1846
2204
  at: (/* @__PURE__ */ new Date()).toISOString(),
1847
2205
  level: errors.length || truncated ? "warn" : "info",
1848
- message: `同步完成:拉取 ${fetched}(匹配作者 ${matched}),新增 ${inserted}${truncated ? `,${truncated} 个仓库触及分页上限` : ""}${errors.length ? `,失败 ${errors.length}` : ""}`
2206
+ message: `同步完成:拉取 ${fetched}(匹配作者 ${matched}),新增 ${inserted}${statsFilled ? `,补全变更统计 ${statsFilled}` : ""}${truncated ? `,${truncated} 个仓库触及分页上限` : ""}${errors.length ? `,失败 ${errors.length}` : ""}`
1849
2207
  });
1850
2208
  return {
1851
2209
  accountId,
@@ -1992,20 +2350,70 @@ function isWorkday(d, yearDays) {
1992
2350
  const dow = d.day();
1993
2351
  return dow >= 1 && dow <= 5;
1994
2352
  }
1995
- async function countWorkdays(from, to) {
2353
+ async function loadYears(from, to) {
1996
2354
  const years = /* @__PURE__ */ new Set();
1997
2355
  for (let cur = from; !cur.isAfter(to, "day"); cur = cur.add(1, "day")) years.add(cur.year());
1998
2356
  const byYear = /* @__PURE__ */ new Map();
1999
2357
  for (const y of years) byYear.set(y, await fetchYear(y));
2358
+ return byYear;
2359
+ }
2360
+ async function countWorkdays(from, to) {
2361
+ const byYear = await loadYears(from, to);
2000
2362
  let count = 0;
2001
2363
  for (let cur = from; !cur.isAfter(to, "day"); cur = cur.add(1, "day")) if (isWorkday(cur, byYear.get(cur.year()))) count++;
2002
2364
  return count;
2003
2365
  }
2004
- async function resolveStatutoryWorkdays(kind, date) {
2005
- if (kind !== "week" && kind !== "month") return void 0;
2366
+ /**
2367
+ * 列出闭区间内的法定工作日(含调休上班日,不含节假日)
2368
+ */
2369
+ async function listStatutoryWorkdays(from, to) {
2370
+ const byYear = await loadYears(from, to);
2371
+ const days = [];
2372
+ for (let cur = from; !cur.isAfter(to, "day"); cur = cur.add(1, "day")) if (isWorkday(cur, byYear.get(cur.year()))) days.push(cur.format("YYYY-MM-DD"));
2373
+ return days;
2374
+ }
2375
+ /**
2376
+ * 法定工作日 × 本地缓存提交数(按自然日)
2377
+ */
2378
+ async function buildWorkdayAttendance(from, to, commitCountByDay) {
2379
+ return (await listStatutoryWorkdays(from, to)).map((date) => {
2380
+ const commitCount = commitCountByDay.get(date) || 0;
2381
+ return {
2382
+ date,
2383
+ weekday: dayjs(date).day(),
2384
+ commitCount,
2385
+ empty: commitCount === 0
2386
+ };
2387
+ });
2388
+ }
2389
+ function rangeBoundsForKind(kind, date) {
2390
+ if (kind !== "week" && kind !== "month") return null;
2006
2391
  const d = dayjs(date || dayjs().format("YYYY-MM-DD"));
2007
- if (kind === "week") return countWorkdays(d.startOf("isoWeek"), d.endOf("isoWeek"));
2008
- return countWorkdays(d.startOf("month"), d.endOf("month"));
2392
+ if (kind === "week") return {
2393
+ from: d.startOf("isoWeek"),
2394
+ to: d.endOf("isoWeek")
2395
+ };
2396
+ return {
2397
+ from: d.startOf("month"),
2398
+ to: d.endOf("month")
2399
+ };
2400
+ }
2401
+ async function resolveStatutoryWorkdays(kind, date) {
2402
+ const bounds = rangeBoundsForKind(kind, date);
2403
+ if (!bounds) return void 0;
2404
+ return countWorkdays(bounds.from, bounds.to);
2405
+ }
2406
+ /**
2407
+ * 周/月报出勤对照数据;其它 kind 返回 undefined
2408
+ */
2409
+ async function resolveWorkdayAttendance(kind, date, commitCountByDay) {
2410
+ const bounds = rangeBoundsForKind(kind, date);
2411
+ if (!bounds) return void 0;
2412
+ const rows = await buildWorkdayAttendance(bounds.from, bounds.to, commitCountByDay);
2413
+ return {
2414
+ statutoryWorkdays: rows.length,
2415
+ rows
2416
+ };
2009
2417
  }
2010
2418
  // src/core/reportRange.ts
2011
2419
  dayjs.extend(isoWeek);
@@ -2060,68 +2468,403 @@ function rangeFor(kind, date, from, to) {
2060
2468
  kindLabel: "月报"
2061
2469
  };
2062
2470
  }
2471
+ // src/core/commitParse.ts
2472
+ const CONVENTIONAL_HEAD = /^([a-zA-Z]+)(?:\(([^)]*)\))?(?:!)?:\s*(.*)$/;
2473
+ const TICKET_BRACKET = /\[([A-Za-z][A-Za-z0-9_.-]*-\d+)\]/;
2474
+ const TICKET_HASH = /(?:^|[\s:])#(\d+)(?:\b|$)/;
2475
+ const TICKET_BARE = /\b([A-Z][A-Z0-9]+-\d+)\b/;
2476
+ function emptyParsed(summary) {
2477
+ return {
2478
+ type: null,
2479
+ scope: null,
2480
+ ticket: null,
2481
+ summary,
2482
+ bullets: []
2483
+ };
2484
+ }
2485
+ function normalizeTicket(raw) {
2486
+ const t = raw.trim();
2487
+ if (/^\d+$/.test(t)) return `#${t}`;
2488
+ return t.toUpperCase();
2489
+ }
2490
+ function findTicket(text) {
2491
+ const bracket = text.match(TICKET_BRACKET);
2492
+ if (bracket) return normalizeTicket(bracket[1]);
2493
+ const hash = text.match(TICKET_HASH);
2494
+ if (hash) return normalizeTicket(hash[1]);
2495
+ const bare = text.match(TICKET_BARE);
2496
+ if (bare) return normalizeTicket(bare[1]);
2497
+ return null;
2498
+ }
2499
+ function stripLeadingTicket(rest) {
2500
+ const trimmed = rest.trim();
2501
+ const bracket = trimmed.match(/^\[([A-Za-z][A-Za-z0-9_.-]*-\d+)\]\s*(.*)$/);
2502
+ if (bracket) return {
2503
+ ticket: normalizeTicket(bracket[1]),
2504
+ summary: bracket[2].trim()
2505
+ };
2506
+ const hash = trimmed.match(/^#(\d+)\s+(.*)$/);
2507
+ if (hash) return {
2508
+ ticket: normalizeTicket(hash[1]),
2509
+ summary: hash[2].trim()
2510
+ };
2511
+ const bare = trimmed.match(/^([A-Z][A-Z0-9]+-\d+)\s*[::]?\s*(.*)$/);
2512
+ if (bare && bare[2]) return {
2513
+ ticket: normalizeTicket(bare[1]),
2514
+ summary: bare[2].trim()
2515
+ };
2516
+ return {
2517
+ ticket: null,
2518
+ summary: trimmed
2519
+ };
2520
+ }
2521
+ function extractBullets(bodyLines) {
2522
+ const bullets = [];
2523
+ for (const line of bodyLines) {
2524
+ const m = line.match(/^\s*[-*]\s+(.+)$/);
2525
+ if (m) bullets.push(m[1].trim());
2526
+ }
2527
+ return bullets;
2528
+ }
2529
+ /**
2530
+ * 解析 conventional 风格提交;失败则降级为摘要=标题行
2531
+ */
2532
+ function parseConventional(commit) {
2533
+ const title = commitTitleLine(commit);
2534
+ const full = commitFullText(commit);
2535
+ const bullets = extractBullets(full.split(/\r?\n/).slice(1));
2536
+ const head = title.match(CONVENTIONAL_HEAD);
2537
+ if (!head) {
2538
+ const ticket = findTicket(full);
2539
+ return {
2540
+ ...emptyParsed(title),
2541
+ ticket,
2542
+ bullets
2543
+ };
2544
+ }
2545
+ const type = head[1].toLowerCase();
2546
+ const scope = (head[2] || "").trim() || null;
2547
+ const { ticket: titleTicket, summary } = stripLeadingTicket(head[3] || "");
2548
+ return {
2549
+ type,
2550
+ scope,
2551
+ ticket: titleTicket || findTicket(full),
2552
+ summary: summary || title,
2553
+ bullets
2554
+ };
2555
+ }
2556
+ /**
2557
+ * 仅抽 type(过滤用);认不出返回 null
2558
+ */
2559
+ function extractCommitType(commit) {
2560
+ return parseConventional(commit).type;
2561
+ }
2562
+ // src/core/reportFilter.ts
2563
+ const MERGE_TITLE = /^(merge\s+(branch|pull\s+request|remote-tracking)\b|merge\s+[0-9a-f]{7,}\s+into\b)/i;
2564
+ /**
2565
+ * 判断是否为合并类提交(仅看标题行)
2566
+ */
2567
+ function isMergeCommit(commit) {
2568
+ return MERGE_TITLE.test(commitTitleLine(commit));
2569
+ }
2570
+ /**
2571
+ * 报告侧过滤:归组前去掉噪音。默认只排除 merge。
2572
+ */
2573
+ function filterReportCommits(commits, opts = {}) {
2574
+ const excludeMerge = opts.excludeMerge !== false;
2575
+ const excludeTypes = (opts.excludeTypes || []).map((t) => t.trim().toLowerCase()).filter(Boolean);
2576
+ const excludeAuthors = (opts.excludeAuthors || []).map((a) => a.trim().toLowerCase()).filter(Boolean);
2577
+ const typeSet = new Set(excludeTypes);
2578
+ const excluded = {
2579
+ merge: 0,
2580
+ type: 0,
2581
+ author: 0
2582
+ };
2583
+ const kept = [];
2584
+ for (const c of commits) {
2585
+ if (excludeMerge && isMergeCommit(c)) {
2586
+ excluded.merge++;
2587
+ continue;
2588
+ }
2589
+ if (typeSet.size > 0) {
2590
+ const type = extractCommitType(c);
2591
+ if (type && typeSet.has(type)) {
2592
+ excluded.type++;
2593
+ continue;
2594
+ }
2595
+ }
2596
+ if (excludeAuthors.length > 0) {
2597
+ const hay = `${c.authorName} ${c.authorEmail}`.toLowerCase();
2598
+ if (excludeAuthors.some((a) => hay.includes(a))) {
2599
+ excluded.author++;
2600
+ continue;
2601
+ }
2602
+ }
2603
+ kept.push(c);
2604
+ }
2605
+ return {
2606
+ kept,
2607
+ rawCount: commits.length,
2608
+ excluded
2609
+ };
2610
+ }
2611
+ /**
2612
+ * 报告头用的排除说明
2613
+ */
2614
+ function formatExclusionSummary(excluded) {
2615
+ const parts = [];
2616
+ if (excluded.merge) parts.push(`merge ${excluded.merge}`);
2617
+ if (excluded.type) parts.push(`type ${excluded.type}`);
2618
+ if (excluded.author) parts.push(`author ${excluded.author}`);
2619
+ return parts.length ? parts.join(" / ") : "";
2620
+ }
2063
2621
  // src/core/reportMarkdown.ts
2064
- function buildReportHeader(title, accountName, commitCount) {
2065
- return [
2622
+ const WEEKDAY_CN = [
2623
+ "日",
2624
+ "一",
2625
+ "二",
2626
+ "三",
2627
+ "四",
2628
+ "五",
2629
+ "六"
2630
+ ];
2631
+ function buildReportHeader(title, accountName, opts) {
2632
+ const lines = [
2066
2633
  `# ${title}`,
2067
2634
  "",
2068
- `- 账号:${accountName}`,
2069
- `- 提交数:${commitCount}`,
2070
- `- 生成时间:${dayjs().format("YYYY-MM-DD HH:mm:ss")}`,
2071
- ""
2072
- ].join("\n");
2635
+ `- 账号:${accountName}`
2636
+ ];
2637
+ const raw = opts.rawCommitCount;
2638
+ if (raw != null && raw !== opts.commitCount) {
2639
+ const excl = opts.excluded ? formatExclusionSummary(opts.excluded) : "";
2640
+ lines.push(excl ? `- 提交:原始 ${raw} → 纳入 ${opts.commitCount}(排除 ${excl})` : `- 提交:原始 ${raw} → 纳入 ${opts.commitCount}`);
2641
+ } else lines.push(`- 提交数:${opts.commitCount}`);
2642
+ if (opts.commits?.length) {
2643
+ const sumLine = formatDiffStatsSum(sumCommitDiffStats(opts.commits));
2644
+ if (sumLine) lines.push(`- 变更:${sumLine}`);
2645
+ }
2646
+ if (opts.statutoryWorkdays != null) lines.push(`- 法定工作日:${opts.statutoryWorkdays} 天`);
2647
+ lines.push(`- 生成时间:${dayjs().format("YYYY-MM-DD HH:mm:ss")}`, "");
2648
+ return lines.join("\n");
2073
2649
  }
2074
- function buildCommitDetailsMarkdown(commits) {
2650
+ function appendStatsSuffix(text, c) {
2651
+ const stats = formatCommitDiffStats(c);
2652
+ return stats ? `${text}(${stats})` : text;
2653
+ }
2654
+ function pushCommitDetail(lines, c, timeFmt = "MM-DD HH:mm") {
2655
+ const time = dayjs(c.committedAt).format(timeFmt);
2656
+ const [first, ...rest] = commitFullText(c).split("\n");
2657
+ lines.push(`- [${time}] ${appendStatsSuffix(first, c)}`);
2658
+ for (const line of rest) lines.push(` ${line}`);
2659
+ }
2660
+ function groupByRepo(commits) {
2075
2661
  const byRepo = /* @__PURE__ */ new Map();
2076
2662
  for (const c of commits) {
2077
2663
  if (!byRepo.has(c.repoName)) byRepo.set(c.repoName, []);
2078
2664
  byRepo.get(c.repoName).push(c);
2079
2665
  }
2666
+ return Array.from(byRepo.entries()).sort((a, b) => a[0].localeCompare(b[0]));
2667
+ }
2668
+ /**
2669
+ * 按仓库列出完整提交说明
2670
+ */
2671
+ function buildCommitDetailsMarkdown(commits) {
2080
2672
  const lines = [];
2081
- const repos = Array.from(byRepo.entries()).sort((a, b) => a[0].localeCompare(b[0]));
2082
- for (const [repo, list] of repos) {
2083
- lines.push(`### ${repo}`);
2673
+ for (const [repo, list] of groupByRepo(commits)) {
2674
+ lines.push(`### ${repo}`, "");
2675
+ for (const c of list) pushCommitDetail(lines, c);
2084
2676
  lines.push("");
2677
+ }
2678
+ return lines.join("\n").trimEnd();
2679
+ }
2680
+ /**
2681
+ * 按仓库仅列提交首行
2682
+ */
2683
+ function buildCommitSubjectListMarkdown(commits) {
2684
+ const lines = [];
2685
+ for (const [repo, list] of groupByRepo(commits)) {
2686
+ lines.push(`### ${repo}`, "");
2085
2687
  for (const c of list) {
2086
2688
  const time = dayjs(c.committedAt).format("MM-DD HH:mm");
2087
- const [first, ...rest] = commitFullText(c).split("\n");
2088
- lines.push(`- [${time}] ${first}`);
2089
- for (const line of rest) lines.push(` ${line}`);
2689
+ lines.push(`- [${time}] ${appendStatsSuffix(commitTitleLine(c), c)}`);
2090
2690
  }
2091
2691
  lines.push("");
2092
2692
  }
2093
2693
  return lines.join("\n").trimEnd();
2094
2694
  }
2095
- function buildCommitSubjectListMarkdown(commits) {
2096
- const byRepo = /* @__PURE__ */ new Map();
2695
+ /**
2696
+ * 扁平时间线(不按仓库分节)
2697
+ */
2698
+ function buildFlatCommitDetailsMarkdown(commits) {
2699
+ const sorted = [...commits].sort((a, b) => a.committedAt.localeCompare(b.committedAt));
2700
+ const lines = [];
2701
+ for (const c of sorted) {
2702
+ const time = dayjs(c.committedAt).format("MM-DD HH:mm");
2703
+ const [first, ...rest] = commitFullText(c).split("\n");
2704
+ lines.push(`- [${time}] **[${c.repoName}]** ${appendStatsSuffix(first, c)}`);
2705
+ for (const line of rest) lines.push(` ${line}`);
2706
+ }
2707
+ return lines.join("\n").trimEnd();
2708
+ }
2709
+ /**
2710
+ * 按自然日再按仓库
2711
+ */
2712
+ function buildDayThenRepoMarkdown(commits) {
2713
+ const byDay = /* @__PURE__ */ new Map();
2097
2714
  for (const c of commits) {
2098
- if (!byRepo.has(c.repoName)) byRepo.set(c.repoName, []);
2099
- byRepo.get(c.repoName).push(c);
2715
+ const day = dayjs(c.committedAt).format("YYYY-MM-DD");
2716
+ if (!byDay.has(day)) byDay.set(day, []);
2717
+ byDay.get(day).push(c);
2100
2718
  }
2719
+ const days = Array.from(byDay.keys()).sort();
2101
2720
  const lines = [];
2102
- const repos = Array.from(byRepo.entries()).sort((a, b) => a[0].localeCompare(b[0]));
2103
- for (const [repo, list] of repos) {
2104
- lines.push(`### ${repo}`);
2105
- lines.push("");
2106
- for (const c of list) {
2107
- const time = dayjs(c.committedAt).format("MM-DD HH:mm");
2108
- lines.push(`- [${time}] ${commitTitleLine(c)}`);
2721
+ for (const day of days) {
2722
+ const wd = WEEKDAY_CN[dayjs(day).day()];
2723
+ lines.push(`### ${day}(周${wd})`, "");
2724
+ for (const [repo, list] of groupByRepo(byDay.get(day))) {
2725
+ lines.push(`#### ${repo}`, "");
2726
+ for (const c of list) pushCommitDetail(lines, c, "HH:mm");
2727
+ lines.push("");
2728
+ }
2729
+ }
2730
+ return lines.join("\n").trimEnd();
2731
+ }
2732
+ /**
2733
+ * 有 ticket 的并成工作单元;无 ticket 退回按仓库列表
2734
+ */
2735
+ function buildTicketGroupedMarkdown(commits) {
2736
+ const byTicket = /* @__PURE__ */ new Map();
2737
+ const noTicket = [];
2738
+ for (const c of commits) {
2739
+ const parsed = parseConventional(c);
2740
+ if (!parsed.ticket) {
2741
+ noTicket.push(c);
2742
+ continue;
2743
+ }
2744
+ const key = parsed.ticket;
2745
+ let unit = byTicket.get(key);
2746
+ if (!unit) {
2747
+ unit = {
2748
+ ticket: key,
2749
+ commits: [],
2750
+ parsed: []
2751
+ };
2752
+ byTicket.set(key, unit);
2753
+ }
2754
+ unit.commits.push(c);
2755
+ unit.parsed.push(parsed);
2756
+ }
2757
+ const lines = [];
2758
+ const units = Array.from(byTicket.values()).sort((a, b) => a.ticket.localeCompare(b.ticket));
2759
+ if (units.length) {
2760
+ lines.push("### 按工单", "");
2761
+ for (const unit of units) {
2762
+ const types = Array.from(new Set(unit.parsed.map((p) => p.type).filter(Boolean)));
2763
+ const repos = Array.from(new Set(unit.commits.map((c) => c.repoName))).sort();
2764
+ const times = unit.commits.map((c) => c.committedAt).sort();
2765
+ const from = dayjs(times[0]).format("MM-DD");
2766
+ const to = dayjs(times[times.length - 1]).format("MM-DD");
2767
+ const range = from === to ? from : `${from} ~ ${to}`;
2768
+ const titleSummary = unit.parsed.find((p) => p.summary)?.summary || commitTitleLine(unit.commits[0]);
2769
+ lines.push(`#### [${unit.ticket}] ${titleSummary}`);
2770
+ lines.push("");
2771
+ if (types.length) lines.push(`- 类型:${types.join(" / ")}`);
2772
+ lines.push(`- 仓库:${repos.join("、")}`);
2773
+ lines.push(`- 提交:${unit.commits.length} 条(${range})`);
2774
+ const unitStats = formatDiffStatsSum(sumCommitDiffStats(unit.commits));
2775
+ if (unitStats) lines.push(`- 变更:${unitStats}`);
2776
+ lines.push("- 要点:");
2777
+ const seen = /* @__PURE__ */ new Set();
2778
+ for (const p of unit.parsed) {
2779
+ const tip = p.summary || "";
2780
+ if (tip && !seen.has(tip)) {
2781
+ seen.add(tip);
2782
+ lines.push(` - ${tip}`);
2783
+ }
2784
+ for (const b of p.bullets) if (!seen.has(b)) {
2785
+ seen.add(b);
2786
+ lines.push(` - ${b}`);
2787
+ }
2788
+ }
2789
+ lines.push("");
2109
2790
  }
2791
+ }
2792
+ if (noTicket.length) {
2793
+ lines.push("### 无工单(按仓库)", "");
2794
+ lines.push(buildCommitDetailsMarkdown(noTicket));
2110
2795
  lines.push("");
2111
2796
  }
2797
+ if (!units.length && !noTicket.length) return "(无提交)";
2112
2798
  return lines.join("\n").trimEnd();
2113
2799
  }
2800
+ /**
2801
+ * 按 groupBy 生成主体 Markdown
2802
+ */
2803
+ function buildGroupedCommitMarkdown(commits, groupBy) {
2804
+ if (!commits.length) return "(无提交)";
2805
+ if (groupBy === "flat") return buildFlatCommitDetailsMarkdown(commits);
2806
+ if (groupBy === "day") return buildDayThenRepoMarkdown(commits);
2807
+ if (groupBy === "ticket") return buildTicketGroupedMarkdown(commits);
2808
+ return buildCommitDetailsMarkdown(commits);
2809
+ }
2810
+ /**
2811
+ * 法定工作日出勤对照(本地缓存)
2812
+ */
2813
+ function buildAttendanceMarkdown(rows) {
2814
+ if (!rows.length) return "";
2815
+ const lines = ["## 出勤对照(法定工作日)", ""];
2816
+ lines.push("> 按本地已同步缓存统计;无提交不等于当天未工作(可能在其它分支/账号)。");
2817
+ lines.push("");
2818
+ let emptyDays = 0;
2819
+ for (const row of rows) {
2820
+ const wd = WEEKDAY_CN[row.weekday];
2821
+ if (row.empty) {
2822
+ emptyDays++;
2823
+ lines.push(`- ${row.date} 周${wd}:本地缓存无提交`);
2824
+ } else lines.push(`- ${row.date} 周${wd}:有提交(${row.commitCount})`);
2825
+ }
2826
+ lines.push("");
2827
+ lines.push(`共 ${rows.length} 个法定工作日,其中 ${emptyDays} 天本地缓存无提交。`);
2828
+ lines.push("");
2829
+ return lines.join("\n");
2830
+ }
2114
2831
  // src/core/reports.ts
2115
- function buildTemplateMarkdown(title, accountName, commits, statutoryWorkdays) {
2116
- const titleLine = statutoryWorkdays != null ? `${title} · ${commits.length} 条 · 法定工作日:${statutoryWorkdays} 天` : title;
2832
+ function countByLocalDay(commits) {
2833
+ const map = /* @__PURE__ */ new Map();
2834
+ for (const c of commits) {
2835
+ const day = dayjs(c.committedAt).format("YYYY-MM-DD");
2836
+ map.set(day, (map.get(day) || 0) + 1);
2837
+ }
2838
+ return map;
2839
+ }
2840
+ function resolveGroupBy(groupBy) {
2841
+ if (groupBy === "day" || groupBy === "flat" || groupBy === "repo" || groupBy === "ticket") return groupBy;
2842
+ return getReportGroupBy();
2843
+ }
2844
+ function sectionTitleFor(groupBy) {
2845
+ if (groupBy === "day") return "## 按日";
2846
+ if (groupBy === "flat") return "## 提交列表";
2847
+ if (groupBy === "ticket") return "## 工作单元";
2848
+ return "## 按仓库";
2849
+ }
2850
+ function buildTemplateMarkdown(opts) {
2117
2851
  const lines = [];
2118
- lines.push(buildReportHeader(titleLine, accountName, commits.length));
2852
+ lines.push(buildReportHeader(opts.title, opts.accountName, {
2853
+ commitCount: opts.kept.length,
2854
+ rawCommitCount: opts.rawCount,
2855
+ excluded: opts.excluded,
2856
+ statutoryWorkdays: opts.statutoryWorkdays,
2857
+ commits: opts.kept
2858
+ }));
2119
2859
  lines.push("## 工作摘要(草稿)");
2120
2860
  lines.push("");
2121
- lines.push("> 以下按项目列出完整提交说明,可据此改写成汇报用语。");
2861
+ lines.push("> 以下为过滤后的提交材料,可据此改写成汇报用语。");
2862
+ lines.push("");
2863
+ lines.push(sectionTitleFor(opts.groupBy));
2122
2864
  lines.push("");
2123
- lines.push(buildCommitDetailsMarkdown(commits));
2865
+ lines.push(buildGroupedCommitMarkdown(opts.kept, opts.groupBy));
2124
2866
  lines.push("");
2867
+ if (opts.attendanceMarkdown) lines.push(opts.attendanceMarkdown);
2125
2868
  return lines.join("\n");
2126
2869
  }
2127
2870
  async function generateReport(req, exportFile = true) {
@@ -2134,8 +2877,32 @@ async function generateReport(req, exportFile = true) {
2134
2877
  to,
2135
2878
  limit: 5e3
2136
2879
  });
2137
- const statutoryWorkdays = await resolveStatutoryWorkdays(req.kind, req.date);
2138
- const markdown = buildTemplateMarkdown(title, account.name, items, statutoryWorkdays);
2880
+ const filtered = filterReportCommits(items, {
2881
+ excludeMerge: req.excludeMerge !== void 0 ? req.excludeMerge : getReportExcludeMerge(),
2882
+ excludeTypes: getReportExcludeTypes(),
2883
+ excludeAuthors: getReportExcludeAuthors()
2884
+ });
2885
+ const groupBy = resolveGroupBy(req.groupBy);
2886
+ const includeAttendance = req.includeAttendance !== false;
2887
+ let statutoryWorkdays = await resolveStatutoryWorkdays(req.kind, req.date);
2888
+ let attendanceMarkdown;
2889
+ if (includeAttendance && (req.kind === "week" || req.kind === "month")) {
2890
+ const attendance = await resolveWorkdayAttendance(req.kind, req.date, countByLocalDay(items));
2891
+ if (attendance) {
2892
+ statutoryWorkdays = attendance.statutoryWorkdays;
2893
+ attendanceMarkdown = buildAttendanceMarkdown(attendance.rows);
2894
+ }
2895
+ }
2896
+ const markdown = buildTemplateMarkdown({
2897
+ title,
2898
+ accountName: account.name,
2899
+ kept: filtered.kept,
2900
+ rawCount: filtered.rawCount,
2901
+ excluded: filtered.excluded,
2902
+ groupBy,
2903
+ statutoryWorkdays,
2904
+ attendanceMarkdown
2905
+ });
2139
2906
  let filePath;
2140
2907
  if (exportFile) {
2141
2908
  const dir = join(reportsDir(), req.accountId);
@@ -2147,7 +2914,9 @@ async function generateReport(req, exportFile = true) {
2147
2914
  title,
2148
2915
  markdown,
2149
2916
  filePath,
2150
- commitCount: items.length,
2917
+ commitCount: filtered.kept.length,
2918
+ rawCommitCount: filtered.rawCount,
2919
+ excluded: filtered.excluded,
2151
2920
  statutoryWorkdays
2152
2921
  };
2153
2922
  }
@@ -2480,7 +3249,7 @@ function registerTools(ctx) {
2480
3249
  }));
2481
3250
  ctx.tools.register(defineTool({
2482
3251
  name: "get_period_report",
2483
- description: "按日/周/月/自定义区间生成报告 Markdown 材料(含法定工作日天数)。",
3252
+ description: "按日/周/月/自定义区间生成报告 Markdown 材料。默认按仓库分组、排除 merge;周/月含法定工作日出勤对照。groupBy=ticket 时按工单归组(无工单仍按仓库)。",
2484
3253
  parameters: {
2485
3254
  accountId: { type: "string" },
2486
3255
  kind: {
@@ -2500,6 +3269,18 @@ function registerTools(ctx) {
2500
3269
  type: "string",
2501
3270
  description: "custom 结束"
2502
3271
  },
3272
+ groupBy: {
3273
+ type: "string",
3274
+ description: "repo(默认)| day | flat | ticket(可选增强)"
3275
+ },
3276
+ excludeMerge: {
3277
+ type: "boolean",
3278
+ description: "是否排除 merge;省略则用设置(默认 true)"
3279
+ },
3280
+ includeAttendance: {
3281
+ type: "boolean",
3282
+ description: "周/月是否附出勤对照,默认 true"
3283
+ },
2503
3284
  exportFile: {
2504
3285
  type: "boolean",
2505
3286
  description: "是否落盘,默认 true"
@@ -2513,17 +3294,29 @@ function registerTools(ctx) {
2513
3294
  }]
2514
3295
  },
2515
3296
  async execute(args) {
3297
+ const id = resolveAccountId(args.accountId);
3298
+ const groupBy = args.groupBy;
2516
3299
  const result = await generateReport({
2517
- accountId: resolveAccountId(args.accountId),
3300
+ accountId: id,
2518
3301
  kind: args.kind,
2519
3302
  date: args.date,
2520
3303
  from: args.from,
2521
- to: args.to
3304
+ to: args.to,
3305
+ groupBy,
3306
+ excludeMerge: args.excludeMerge,
3307
+ includeAttendance: args.includeAttendance
2522
3308
  }, args.exportFile !== false);
3309
+ const excl = result.excluded;
3310
+ const exclParts = excl ? [
3311
+ excl.merge ? `merge ${excl.merge}` : "",
3312
+ excl.type ? `type ${excl.type}` : "",
3313
+ excl.author ? `author ${excl.author}` : ""
3314
+ ].filter(Boolean) : [];
2523
3315
  return textOut([
2524
3316
  result.markdown,
2525
3317
  "",
2526
3318
  result.filePath ? `已落盘:${result.filePath}` : "",
3319
+ result.rawCommitCount != null && result.rawCommitCount !== result.commitCount ? `提交:原始 ${result.rawCommitCount} → 纳入 ${result.commitCount}` + (exclParts.length ? `(排除 ${exclParts.join(" / ")})` : "") : "",
2527
3320
  result.statutoryWorkdays != null ? `法定工作日:${result.statutoryWorkdays} 天` : ""
2528
3321
  ].filter(Boolean).join("\n"));
2529
3322
  }
@@ -2562,7 +3355,10 @@ function registerTools(ctx) {
2562
3355
  repo: c.repoName,
2563
3356
  title: c.title,
2564
3357
  sha: c.shortId,
2565
- webUrl: c.webUrl
3358
+ webUrl: c.webUrl,
3359
+ additions: c.additions,
3360
+ deletions: c.deletions,
3361
+ filesChanged: c.filesChanged
2566
3362
  }))
2567
3363
  }, null, 2));
2568
3364
  }
@@ -2575,12 +3371,30 @@ function registerTools(ctx) {
2575
3371
  }));
2576
3372
  ctx.tools.register(defineTool({
2577
3373
  name: "update_journal_settings",
2578
- description: "更新本地同步/导出/热力图 UI 端口等设置。",
3374
+ description: "更新本地同步/导出/热力图 UI 端口与报告设置(过滤、默认 groupBy)。",
2579
3375
  parameters: {
2580
3376
  exportsPath: { type: "string" },
2581
3377
  syncIntervalMinutes: { type: "number" },
2582
3378
  syncLookbackDays: { type: "number" },
2583
- uiPort: { type: "number" }
3379
+ uiPort: { type: "number" },
3380
+ reportExcludeMerge: {
3381
+ type: "boolean",
3382
+ description: "报告默认排除 merge,默认 true"
3383
+ },
3384
+ reportExcludeTypes: {
3385
+ type: "array",
3386
+ items: { type: "string" },
3387
+ description: "conventional type 黑名单,如 chore、ci;默认空"
3388
+ },
3389
+ reportExcludeAuthors: {
3390
+ type: "array",
3391
+ items: { type: "string" },
3392
+ description: "作者名/邮箱子串黑名单;默认空"
3393
+ },
3394
+ reportGroupBy: {
3395
+ type: "string",
3396
+ description: "默认分组:repo | day | flat | ticket"
3397
+ }
2584
3398
  },
2585
3399
  output: {
2586
3400
  schema: { type: "string" },
@@ -2918,7 +3732,10 @@ async function handler(req, res) {
2918
3732
  message: c.message,
2919
3733
  authorName: c.authorName,
2920
3734
  sha: c.shortId,
2921
- webUrl: c.webUrl
3735
+ webUrl: c.webUrl,
3736
+ additions: c.additions,
3737
+ deletions: c.deletions,
3738
+ filesChanged: c.filesChanged
2922
3739
  })) });
2923
3740
  return;
2924
3741
  }
@@ -2949,7 +3766,11 @@ async function handler(req, res) {
2949
3766
  exportsPath: body.exportsPath,
2950
3767
  syncIntervalMinutes: body.syncIntervalMinutes,
2951
3768
  syncLookbackDays: body.syncLookbackDays,
2952
- uiPort: body.uiPort
3769
+ uiPort: body.uiPort,
3770
+ reportExcludeMerge: body.reportExcludeMerge,
3771
+ reportExcludeTypes: body.reportExcludeTypes,
3772
+ reportExcludeAuthors: body.reportExcludeAuthors,
3773
+ reportGroupBy: body.reportGroupBy
2953
3774
  });
2954
3775
  sendJson(res, 200, {
2955
3776
  ok: true,