dsh-commit-journal 0.0.0-stage → 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/CHANGELOG.md +84 -0
- package/LICENSE +21 -0
- package/README.md +182 -3
- package/client.js +3432 -0
- package/cordis.patch.yml +4 -0
- package/lib/index.d.ts +13 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +3852 -0
- package/lib/index.js.map +1 -0
- package/package.json +95 -6
package/lib/index.js
ADDED
|
@@ -0,0 +1,3852 @@
|
|
|
1
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, unlinkSync, writeFileSync } from "fs";
|
|
2
|
+
import { homedir, hostname } from "os";
|
|
3
|
+
import { basename, delimiter, join, relative, resolve, sep } from "path";
|
|
4
|
+
import { v4 } from "uuid";
|
|
5
|
+
import { createCipheriv, createDecipheriv, createHash, randomBytes, scryptSync } from "crypto";
|
|
6
|
+
import dayjs from "dayjs";
|
|
7
|
+
import http from "node:http";
|
|
8
|
+
import https from "node:https";
|
|
9
|
+
import { execFile } from "child_process";
|
|
10
|
+
import { promisify } from "util";
|
|
11
|
+
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
12
|
+
import isoWeek from "dayjs/plugin/isoWeek.js";
|
|
13
|
+
import { createServer } from "http";
|
|
14
|
+
// src/core/types.ts
|
|
15
|
+
const DEFAULT_UI_PORT = 39282;
|
|
16
|
+
const DEFAULT_REPORT_GROUP_BY = "repo";
|
|
17
|
+
// src/core/settings.ts
|
|
18
|
+
const defaults = {
|
|
19
|
+
exportsPath: "",
|
|
20
|
+
syncIntervalMinutes: 30,
|
|
21
|
+
syncLookbackDays: 90,
|
|
22
|
+
uiPort: DEFAULT_UI_PORT,
|
|
23
|
+
reportExcludeMerge: true,
|
|
24
|
+
reportExcludeTypes: [],
|
|
25
|
+
reportExcludeAuthors: [],
|
|
26
|
+
reportGroupBy: DEFAULT_REPORT_GROUP_BY
|
|
27
|
+
};
|
|
28
|
+
function load$1() {
|
|
29
|
+
const path = settingsPath();
|
|
30
|
+
if (!existsSync(path)) return { ...defaults };
|
|
31
|
+
try {
|
|
32
|
+
return {
|
|
33
|
+
...defaults,
|
|
34
|
+
...JSON.parse(readFileSync(path, "utf8"))
|
|
35
|
+
};
|
|
36
|
+
} catch {
|
|
37
|
+
return { ...defaults };
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
function save$1(settings) {
|
|
41
|
+
writeFileSync(settingsPath(), JSON.stringify(settings, null, 2), "utf8");
|
|
42
|
+
}
|
|
43
|
+
function normalizeStringList(value) {
|
|
44
|
+
if (!Array.isArray(value)) return [];
|
|
45
|
+
return value.map((v) => String(v).trim()).filter(Boolean);
|
|
46
|
+
}
|
|
47
|
+
function updateSettings(patch) {
|
|
48
|
+
const next = {
|
|
49
|
+
...load$1(),
|
|
50
|
+
...patch
|
|
51
|
+
};
|
|
52
|
+
if (next.syncIntervalMinutes < 5) next.syncIntervalMinutes = 5;
|
|
53
|
+
if (next.syncLookbackDays < 1) next.syncLookbackDays = 1;
|
|
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);
|
|
59
|
+
save$1(next);
|
|
60
|
+
return next;
|
|
61
|
+
}
|
|
62
|
+
function normalizeGroupBy(value) {
|
|
63
|
+
if (value === "day" || value === "flat" || value === "repo" || value === "ticket") return value;
|
|
64
|
+
return DEFAULT_REPORT_GROUP_BY;
|
|
65
|
+
}
|
|
66
|
+
function getExportsPathSetting() {
|
|
67
|
+
return (load$1().exportsPath || "").trim();
|
|
68
|
+
}
|
|
69
|
+
function getSyncIntervalMinutes() {
|
|
70
|
+
return load$1().syncIntervalMinutes || 30;
|
|
71
|
+
}
|
|
72
|
+
function getSyncLookbackDays() {
|
|
73
|
+
return load$1().syncLookbackDays || 90;
|
|
74
|
+
}
|
|
75
|
+
function getUiPort() {
|
|
76
|
+
return load$1().uiPort || 39282;
|
|
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
|
+
}
|
|
91
|
+
function describeSettings() {
|
|
92
|
+
const s = load$1();
|
|
93
|
+
return {
|
|
94
|
+
...s,
|
|
95
|
+
reportExcludeMerge: getReportExcludeMerge(),
|
|
96
|
+
reportExcludeTypes: getReportExcludeTypes(),
|
|
97
|
+
reportExcludeAuthors: getReportExcludeAuthors(),
|
|
98
|
+
reportGroupBy: getReportGroupBy(),
|
|
99
|
+
resolvedExportsPath: s.exportsPath?.trim() || defaultExportsDir(),
|
|
100
|
+
defaultExportsPath: defaultExportsDir()
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
// src/core/paths.ts
|
|
104
|
+
function getDataRoot() {
|
|
105
|
+
const root = process.env.DSH_COMMIT_JOURNAL_HOME?.trim() || join(homedir(), ".dsh-commit-journal");
|
|
106
|
+
mkdirSync(root, { recursive: true });
|
|
107
|
+
mkdirSync(join(root, "secrets"), { recursive: true });
|
|
108
|
+
return root;
|
|
109
|
+
}
|
|
110
|
+
function defaultExportsDir() {
|
|
111
|
+
return join(getDataRoot(), "exports");
|
|
112
|
+
}
|
|
113
|
+
function exportsDir() {
|
|
114
|
+
const root = getExportsPathSetting() || defaultExportsDir();
|
|
115
|
+
mkdirSync(root, { recursive: true });
|
|
116
|
+
mkdirSync(join(root, "reports"), { recursive: true });
|
|
117
|
+
return root;
|
|
118
|
+
}
|
|
119
|
+
function reportsDir() {
|
|
120
|
+
const dir = join(exportsDir(), "reports");
|
|
121
|
+
mkdirSync(dir, { recursive: true });
|
|
122
|
+
return dir;
|
|
123
|
+
}
|
|
124
|
+
function accountsPath() {
|
|
125
|
+
return join(getDataRoot(), "accounts.json");
|
|
126
|
+
}
|
|
127
|
+
function settingsPath() {
|
|
128
|
+
return join(getDataRoot(), "settings.json");
|
|
129
|
+
}
|
|
130
|
+
function secretPath(name) {
|
|
131
|
+
return join(getDataRoot(), "secrets", `${name}.bin`);
|
|
132
|
+
}
|
|
133
|
+
function dbPath() {
|
|
134
|
+
return join(getDataRoot(), "data.json");
|
|
135
|
+
}
|
|
136
|
+
function holidayCacheDir() {
|
|
137
|
+
const dir = join(getDataRoot(), "holiday-cache");
|
|
138
|
+
mkdirSync(dir, { recursive: true });
|
|
139
|
+
return dir;
|
|
140
|
+
}
|
|
141
|
+
function ensureDataLayout() {
|
|
142
|
+
getDataRoot();
|
|
143
|
+
if (!existsSync(exportsDir())) mkdirSync(exportsDir(), { recursive: true });
|
|
144
|
+
}
|
|
145
|
+
// src/core/commitText.ts
|
|
146
|
+
function commitFullText(commit) {
|
|
147
|
+
const message = (commit.message || "").trim();
|
|
148
|
+
const title = (commit.title || "").trim();
|
|
149
|
+
if (message) return message;
|
|
150
|
+
return title;
|
|
151
|
+
}
|
|
152
|
+
function commitTitleLine(commit) {
|
|
153
|
+
const title = (commit.title || "").trim();
|
|
154
|
+
if (title) return title.split("\n").find((l) => l.trim())?.trim() || title;
|
|
155
|
+
const full = commitFullText(commit);
|
|
156
|
+
return full.split("\n").find((l) => l.trim())?.trim() || full;
|
|
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
|
+
}
|
|
203
|
+
// src/core/repoDisplay.ts
|
|
204
|
+
function shortRepoPath(pathWithNamespace, organizationId) {
|
|
205
|
+
const raw = (pathWithNamespace || "").trim();
|
|
206
|
+
if (!raw) return "";
|
|
207
|
+
const parts = raw.split("/").filter(Boolean);
|
|
208
|
+
if (parts.length <= 1) return raw;
|
|
209
|
+
if (organizationId && parts[0] === organizationId) return parts.slice(1).join("/");
|
|
210
|
+
if (/^[a-f0-9]{24}$/i.test(parts[0])) return parts.slice(1).join("/") || raw;
|
|
211
|
+
return raw;
|
|
212
|
+
}
|
|
213
|
+
// src/core/vault.ts
|
|
214
|
+
const MAGIC = Buffer.from("DCJ1");
|
|
215
|
+
function machineKey() {
|
|
216
|
+
const material = `${hostname()}|${homedir()}|dsh-commit-journal-v1`;
|
|
217
|
+
return scryptSync(material, "dsh-commit-journal-salt", 32);
|
|
218
|
+
}
|
|
219
|
+
function saveSecret(name, value) {
|
|
220
|
+
const key = machineKey();
|
|
221
|
+
const iv = randomBytes(12);
|
|
222
|
+
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
|
223
|
+
const enc = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
|
|
224
|
+
const tag = cipher.getAuthTag();
|
|
225
|
+
writeFileSync(secretPath(name), Buffer.concat([
|
|
226
|
+
MAGIC,
|
|
227
|
+
iv,
|
|
228
|
+
tag,
|
|
229
|
+
enc
|
|
230
|
+
]));
|
|
231
|
+
}
|
|
232
|
+
function loadSecret(name) {
|
|
233
|
+
const path = secretPath(name);
|
|
234
|
+
if (!existsSync(path)) return null;
|
|
235
|
+
const raw = readFileSync(path);
|
|
236
|
+
try {
|
|
237
|
+
if (raw.length > 4 && raw.subarray(0, 4).equals(MAGIC)) {
|
|
238
|
+
const iv = raw.subarray(4, 16);
|
|
239
|
+
const tag = raw.subarray(16, 32);
|
|
240
|
+
const data = raw.subarray(32);
|
|
241
|
+
const decipher = createDecipheriv("aes-256-gcm", machineKey(), iv);
|
|
242
|
+
decipher.setAuthTag(tag);
|
|
243
|
+
return Buffer.concat([decipher.update(data), decipher.final()]).toString("utf8");
|
|
244
|
+
}
|
|
245
|
+
return raw.toString("utf8");
|
|
246
|
+
} catch {
|
|
247
|
+
return null;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
function deleteSecret(name) {
|
|
251
|
+
const path = secretPath(name);
|
|
252
|
+
if (existsSync(path)) unlinkSync(path);
|
|
253
|
+
}
|
|
254
|
+
function saveToken(accountId, token) {
|
|
255
|
+
saveSecret(accountId, token);
|
|
256
|
+
}
|
|
257
|
+
function loadToken(accountId) {
|
|
258
|
+
return loadSecret(accountId);
|
|
259
|
+
}
|
|
260
|
+
function deleteToken(accountId) {
|
|
261
|
+
deleteSecret(accountId);
|
|
262
|
+
}
|
|
263
|
+
// src/core/db.ts
|
|
264
|
+
const empty = {
|
|
265
|
+
repos: [],
|
|
266
|
+
commits: [],
|
|
267
|
+
syncState: [],
|
|
268
|
+
syncLogs: []
|
|
269
|
+
};
|
|
270
|
+
function migrateCommit(raw) {
|
|
271
|
+
return {
|
|
272
|
+
...raw,
|
|
273
|
+
repoId: String(raw.repoId)
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
function migrateRepo(raw) {
|
|
277
|
+
return {
|
|
278
|
+
accountId: String(raw.accountId),
|
|
279
|
+
id: String(raw.id),
|
|
280
|
+
name: String(raw.name || ""),
|
|
281
|
+
fullName: String(raw.fullName || raw.pathWithNamespace || raw.name || ""),
|
|
282
|
+
webUrl: String(raw.webUrl || ""),
|
|
283
|
+
lastActivityAt: raw.lastActivityAt,
|
|
284
|
+
defaultBranch: raw.defaultBranch,
|
|
285
|
+
accessLevel: raw.accessLevel,
|
|
286
|
+
visibility: raw.visibility,
|
|
287
|
+
starred: raw.starred,
|
|
288
|
+
participating: raw.participating
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
function migrateSyncState(raw) {
|
|
292
|
+
return {
|
|
293
|
+
accountId: String(raw.accountId),
|
|
294
|
+
repoId: String(raw.repoId),
|
|
295
|
+
lastSyncedAt: String(raw.lastSyncedAt || ""),
|
|
296
|
+
lookbackDays: raw.lookbackDays
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
function load() {
|
|
300
|
+
const path = dbPath();
|
|
301
|
+
if (!existsSync(path)) return structuredClone(empty);
|
|
302
|
+
try {
|
|
303
|
+
const raw = JSON.parse(readFileSync(path, "utf8"));
|
|
304
|
+
return {
|
|
305
|
+
repos: (raw.repos || []).map(migrateRepo),
|
|
306
|
+
commits: (raw.commits || []).map(migrateCommit),
|
|
307
|
+
syncState: (raw.syncState || []).map(migrateSyncState),
|
|
308
|
+
syncLogs: raw.syncLogs || []
|
|
309
|
+
};
|
|
310
|
+
} catch {
|
|
311
|
+
return structuredClone(empty);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
function save(data) {
|
|
315
|
+
writeFileSync(dbPath(), JSON.stringify(data, null, 2), "utf8");
|
|
316
|
+
}
|
|
317
|
+
const ACTIVITY_MAX_YEARS = 8;
|
|
318
|
+
function mondayOf(d) {
|
|
319
|
+
return d.subtract((d.day() + 6) % 7, "day");
|
|
320
|
+
}
|
|
321
|
+
function resolveActivityRange(year) {
|
|
322
|
+
const today = dayjs().startOf("day");
|
|
323
|
+
if (year != null && Number.isFinite(year)) {
|
|
324
|
+
const start = dayjs(`${year}-01-01`).startOf("day");
|
|
325
|
+
const end = dayjs(`${year}-12-31`).endOf("day");
|
|
326
|
+
return {
|
|
327
|
+
from: start,
|
|
328
|
+
to: end.isAfter(today) ? today : end
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
return {
|
|
332
|
+
from: mondayOf(today).subtract(52, "week"),
|
|
333
|
+
to: today
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
const db = {
|
|
337
|
+
upsertRepos(accountId, repos) {
|
|
338
|
+
const data = load();
|
|
339
|
+
data.repos = [...data.repos.filter((r) => r.accountId !== accountId), ...repos.map((r) => ({
|
|
340
|
+
...r,
|
|
341
|
+
accountId
|
|
342
|
+
}))];
|
|
343
|
+
save(data);
|
|
344
|
+
},
|
|
345
|
+
listRepos(accountId) {
|
|
346
|
+
return load().repos.filter((r) => r.accountId === accountId);
|
|
347
|
+
},
|
|
348
|
+
listReposWithCommits(accountId) {
|
|
349
|
+
const data = load();
|
|
350
|
+
const nameById = /* @__PURE__ */ new Map();
|
|
351
|
+
for (const c of data.commits) {
|
|
352
|
+
if (c.accountId !== accountId) continue;
|
|
353
|
+
if (!nameById.has(c.repoId)) nameById.set(c.repoId, c.repoName);
|
|
354
|
+
}
|
|
355
|
+
if (nameById.size === 0) return [];
|
|
356
|
+
const byId = new Map(data.repos.filter((r) => r.accountId === accountId).map((r) => [r.id, r]));
|
|
357
|
+
const list = [];
|
|
358
|
+
for (const [id, repoName] of nameById) {
|
|
359
|
+
const existing = byId.get(id);
|
|
360
|
+
if (existing) list.push(existing);
|
|
361
|
+
else list.push({
|
|
362
|
+
accountId,
|
|
363
|
+
id,
|
|
364
|
+
name: repoName,
|
|
365
|
+
fullName: repoName,
|
|
366
|
+
webUrl: ""
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
list.sort((a, b) => (a.fullName || a.name).localeCompare(b.fullName || b.name));
|
|
370
|
+
return list;
|
|
371
|
+
},
|
|
372
|
+
getSyncState(accountId, repoId) {
|
|
373
|
+
return load().syncState.find((s) => s.accountId === accountId && s.repoId === repoId);
|
|
374
|
+
},
|
|
375
|
+
setSyncState(state) {
|
|
376
|
+
const data = load();
|
|
377
|
+
const idx = data.syncState.findIndex((s) => s.accountId === state.accountId && s.repoId === state.repoId);
|
|
378
|
+
if (idx >= 0) data.syncState[idx] = state;
|
|
379
|
+
else data.syncState.push(state);
|
|
380
|
+
save(data);
|
|
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
|
+
},
|
|
388
|
+
insertCommits(commits) {
|
|
389
|
+
if (commits.length === 0) return 0;
|
|
390
|
+
const data = load();
|
|
391
|
+
const index = new Map(data.commits.map((c, i) => [`${c.accountId}:${c.sha}`, i]));
|
|
392
|
+
let inserted = 0;
|
|
393
|
+
let updated = 0;
|
|
394
|
+
for (const c of commits) {
|
|
395
|
+
const key = `${c.accountId}:${c.sha}`;
|
|
396
|
+
const idx = index.get(key);
|
|
397
|
+
if (idx == null) {
|
|
398
|
+
data.commits.push(c);
|
|
399
|
+
index.set(key, data.commits.length - 1);
|
|
400
|
+
inserted++;
|
|
401
|
+
continue;
|
|
402
|
+
}
|
|
403
|
+
const prev = data.commits[idx];
|
|
404
|
+
const nextMsg = (c.message || "").trim();
|
|
405
|
+
const prevMsg = (prev.message || "").trim();
|
|
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++;
|
|
422
|
+
}
|
|
423
|
+
if (inserted > 0 || updated > 0) save(data);
|
|
424
|
+
return inserted;
|
|
425
|
+
},
|
|
426
|
+
queryCommits(opts) {
|
|
427
|
+
let items = load().commits.filter((c) => c.accountId === opts.accountId);
|
|
428
|
+
if (opts.repoId != null) items = items.filter((c) => c.repoId === opts.repoId);
|
|
429
|
+
if (opts.from) {
|
|
430
|
+
const from = opts.from;
|
|
431
|
+
items = items.filter((c) => c.committedAt >= from);
|
|
432
|
+
}
|
|
433
|
+
if (opts.to) {
|
|
434
|
+
const to = opts.to.endsWith("Z") || opts.to.includes("T") ? opts.to : `${opts.to}T23:59:59.999Z`;
|
|
435
|
+
items = items.filter((c) => c.committedAt <= to);
|
|
436
|
+
}
|
|
437
|
+
if (opts.keyword) {
|
|
438
|
+
const kw = opts.keyword.toLowerCase();
|
|
439
|
+
items = items.filter((c) => c.title.toLowerCase().includes(kw) || c.message.toLowerCase().includes(kw) || c.repoName.toLowerCase().includes(kw));
|
|
440
|
+
}
|
|
441
|
+
items.sort((a, b) => b.committedAt.localeCompare(a.committedAt));
|
|
442
|
+
const total = items.length;
|
|
443
|
+
const offset = opts.offset ?? 0;
|
|
444
|
+
const limit = opts.limit ?? 200;
|
|
445
|
+
return {
|
|
446
|
+
items: items.slice(offset, offset + limit),
|
|
447
|
+
total
|
|
448
|
+
};
|
|
449
|
+
},
|
|
450
|
+
getActivity(accountId, year) {
|
|
451
|
+
const data = load();
|
|
452
|
+
const { from, to } = resolveActivityRange(year);
|
|
453
|
+
const today = dayjs().startOf("day");
|
|
454
|
+
const yearSet = /* @__PURE__ */ new Set([today.year()]);
|
|
455
|
+
const byDay = /* @__PURE__ */ new Map();
|
|
456
|
+
for (const c of data.commits) {
|
|
457
|
+
if (c.accountId !== accountId) continue;
|
|
458
|
+
const at = dayjs(c.committedAt);
|
|
459
|
+
if (!at.isValid()) continue;
|
|
460
|
+
yearSet.add(at.year());
|
|
461
|
+
if (at.isBefore(from, "day") || at.isAfter(to, "day")) continue;
|
|
462
|
+
const key = at.format("YYYY-MM-DD");
|
|
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
|
+
}
|
|
485
|
+
}
|
|
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));
|
|
498
|
+
let longestStreak = 0;
|
|
499
|
+
let streak = 0;
|
|
500
|
+
let maxDayCount = 0;
|
|
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;
|
|
514
|
+
for (let cur = from, guard = 0; !cur.isAfter(to, "day") && guard < 1e3; guard++) {
|
|
515
|
+
const count = byDay.get(cur.format("YYYY-MM-DD"))?.count ?? 0;
|
|
516
|
+
if (count > 0) {
|
|
517
|
+
streak++;
|
|
518
|
+
if (streak > longestStreak) longestStreak = streak;
|
|
519
|
+
if (count > maxDayCount) {
|
|
520
|
+
maxDayCount = count;
|
|
521
|
+
maxDayDate = cur.format("YYYY-MM-DD");
|
|
522
|
+
}
|
|
523
|
+
} else streak = 0;
|
|
524
|
+
cur = cur.add(1, "day");
|
|
525
|
+
}
|
|
526
|
+
return {
|
|
527
|
+
years: Array.from(yearSet).sort((a, b) => b - a).slice(0, ACTIVITY_MAX_YEARS),
|
|
528
|
+
from: from.format("YYYY-MM-DD"),
|
|
529
|
+
to: to.format("YYYY-MM-DD"),
|
|
530
|
+
days,
|
|
531
|
+
stats: {
|
|
532
|
+
totalCommits: days.reduce((sum, d) => sum + d.count, 0),
|
|
533
|
+
activeDays: days.length,
|
|
534
|
+
longestStreak,
|
|
535
|
+
maxDayCount,
|
|
536
|
+
maxDayDate,
|
|
537
|
+
totalAdditions,
|
|
538
|
+
totalDeletions,
|
|
539
|
+
totalFilesChanged,
|
|
540
|
+
commitsWithStats
|
|
541
|
+
}
|
|
542
|
+
};
|
|
543
|
+
},
|
|
544
|
+
listDayCommits(accountId, date) {
|
|
545
|
+
const target = dayjs(date);
|
|
546
|
+
if (!target.isValid()) return [];
|
|
547
|
+
const key = target.format("YYYY-MM-DD");
|
|
548
|
+
return load().commits.filter((c) => c.accountId === accountId && dayjs(c.committedAt).format("YYYY-MM-DD") === key).sort((a, b) => b.committedAt.localeCompare(a.committedAt));
|
|
549
|
+
},
|
|
550
|
+
addSyncLog(log) {
|
|
551
|
+
const data = load();
|
|
552
|
+
data.syncLogs.unshift(log);
|
|
553
|
+
data.syncLogs = data.syncLogs.slice(0, 500);
|
|
554
|
+
save(data);
|
|
555
|
+
},
|
|
556
|
+
listSyncLogs(accountId, limit = 20, offset = 0) {
|
|
557
|
+
const all = load().syncLogs.filter((l) => l.accountId === accountId);
|
|
558
|
+
return {
|
|
559
|
+
items: all.slice(offset, offset + limit),
|
|
560
|
+
total: all.length
|
|
561
|
+
};
|
|
562
|
+
},
|
|
563
|
+
clearSyncLogs(accountId) {
|
|
564
|
+
const data = load();
|
|
565
|
+
const before = data.syncLogs.length;
|
|
566
|
+
data.syncLogs = accountId ? data.syncLogs.filter((l) => l.accountId !== accountId) : [];
|
|
567
|
+
const deleted = before - data.syncLogs.length;
|
|
568
|
+
if (deleted > 0) save(data);
|
|
569
|
+
return deleted;
|
|
570
|
+
},
|
|
571
|
+
deleteAccountData(accountId) {
|
|
572
|
+
const data = load();
|
|
573
|
+
data.repos = data.repos.filter((r) => r.accountId !== accountId);
|
|
574
|
+
data.commits = data.commits.filter((c) => c.accountId !== accountId);
|
|
575
|
+
data.syncState = data.syncState.filter((s) => s.accountId !== accountId);
|
|
576
|
+
data.syncLogs = data.syncLogs.filter((l) => l.accountId !== accountId);
|
|
577
|
+
save(data);
|
|
578
|
+
},
|
|
579
|
+
clearCommits(accountId, repoId) {
|
|
580
|
+
const data = load();
|
|
581
|
+
const before = data.commits.length;
|
|
582
|
+
if (repoId != null) {
|
|
583
|
+
data.commits = data.commits.filter((c) => !(c.accountId === accountId && c.repoId === repoId));
|
|
584
|
+
data.syncState = data.syncState.filter((s) => !(s.accountId === accountId && s.repoId === repoId));
|
|
585
|
+
} else {
|
|
586
|
+
data.commits = data.commits.filter((c) => c.accountId !== accountId);
|
|
587
|
+
data.syncState = data.syncState.filter((s) => s.accountId !== accountId);
|
|
588
|
+
}
|
|
589
|
+
const deletedCommits = before - data.commits.length;
|
|
590
|
+
save(data);
|
|
591
|
+
return { deletedCommits };
|
|
592
|
+
}
|
|
593
|
+
};
|
|
594
|
+
// src/core/accounts.ts
|
|
595
|
+
function normalizeRepoIds(ids) {
|
|
596
|
+
return (ids ?? []).map((id) => String(id));
|
|
597
|
+
}
|
|
598
|
+
function normalizeBranches(map) {
|
|
599
|
+
if (!map) return {};
|
|
600
|
+
const out = {};
|
|
601
|
+
for (const [k, v] of Object.entries(map)) out[String(k)] = v;
|
|
602
|
+
return out;
|
|
603
|
+
}
|
|
604
|
+
function normalizeRoots(roots) {
|
|
605
|
+
const seen = /* @__PURE__ */ new Set();
|
|
606
|
+
const out = [];
|
|
607
|
+
for (const raw of roots || []) {
|
|
608
|
+
let trimmed = String(raw || "").trim().replace(/^["']+|["']+$/g, "").trim().replace(/[\\/]+$/, "");
|
|
609
|
+
if (!trimmed) continue;
|
|
610
|
+
let abs = trimmed;
|
|
611
|
+
try {
|
|
612
|
+
abs = resolve(trimmed);
|
|
613
|
+
} catch {
|
|
614
|
+
abs = trimmed;
|
|
615
|
+
}
|
|
616
|
+
const key = abs.toLowerCase();
|
|
617
|
+
if (seen.has(key)) continue;
|
|
618
|
+
seen.add(key);
|
|
619
|
+
out.push(abs);
|
|
620
|
+
}
|
|
621
|
+
return out;
|
|
622
|
+
}
|
|
623
|
+
function normalizeMode(raw) {
|
|
624
|
+
return raw === "local" ? "local" : "remote";
|
|
625
|
+
}
|
|
626
|
+
function migrateAccount(raw) {
|
|
627
|
+
const watched = Array.isArray(raw.watchedRepoIds) ? raw.watchedRepoIds.map((id) => String(id)) : [];
|
|
628
|
+
const mode = normalizeMode(raw.mode);
|
|
629
|
+
return {
|
|
630
|
+
id: String(raw.id),
|
|
631
|
+
name: String(raw.name || ""),
|
|
632
|
+
mode,
|
|
633
|
+
provider: mode === "local" ? "local" : raw.provider || "codeup",
|
|
634
|
+
edition: mode === "remote" ? raw.edition : void 0,
|
|
635
|
+
organizationId: mode === "remote" ? raw.organizationId : void 0,
|
|
636
|
+
apiBaseUrl: mode === "remote" ? raw.apiBaseUrl : void 0,
|
|
637
|
+
insecureSsl: mode === "remote" ? Boolean(raw.insecureSsl) : void 0,
|
|
638
|
+
localRoots: mode === "local" ? normalizeRoots(raw.localRoots) : void 0,
|
|
639
|
+
authorFilters: Array.isArray(raw.authorFilters) ? raw.authorFilters : [],
|
|
640
|
+
defaultBranch: raw.defaultBranch || "master",
|
|
641
|
+
watchedRepoIds: watched,
|
|
642
|
+
repoBranches: normalizeBranches(raw.repoBranches),
|
|
643
|
+
createdAt: raw.createdAt || (/* @__PURE__ */ new Date()).toISOString(),
|
|
644
|
+
updatedAt: raw.updatedAt || (/* @__PURE__ */ new Date()).toISOString()
|
|
645
|
+
};
|
|
646
|
+
}
|
|
647
|
+
function loadStore() {
|
|
648
|
+
const path = accountsPath();
|
|
649
|
+
if (!existsSync(path)) return {
|
|
650
|
+
accounts: [],
|
|
651
|
+
activeAccountId: null
|
|
652
|
+
};
|
|
653
|
+
try {
|
|
654
|
+
const raw = JSON.parse(readFileSync(path, "utf8"));
|
|
655
|
+
return {
|
|
656
|
+
accounts: (raw.accounts || []).map(migrateAccount),
|
|
657
|
+
activeAccountId: raw.activeAccountId ?? null
|
|
658
|
+
};
|
|
659
|
+
} catch {
|
|
660
|
+
return {
|
|
661
|
+
accounts: [],
|
|
662
|
+
activeAccountId: null
|
|
663
|
+
};
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
function saveStore(store) {
|
|
667
|
+
writeFileSync(accountsPath(), JSON.stringify(store, null, 2), "utf8");
|
|
668
|
+
}
|
|
669
|
+
function listAccounts() {
|
|
670
|
+
return loadStore().accounts;
|
|
671
|
+
}
|
|
672
|
+
function getActiveAccountId() {
|
|
673
|
+
return loadStore().activeAccountId;
|
|
674
|
+
}
|
|
675
|
+
function setActiveAccountId(id) {
|
|
676
|
+
const store = loadStore();
|
|
677
|
+
store.activeAccountId = id;
|
|
678
|
+
saveStore(store);
|
|
679
|
+
}
|
|
680
|
+
function getAccount(id) {
|
|
681
|
+
return loadStore().accounts.find((a) => a.id === id);
|
|
682
|
+
}
|
|
683
|
+
function buildAccountFields(input, prev) {
|
|
684
|
+
const mode = normalizeMode(input.mode ?? prev?.mode ?? "remote");
|
|
685
|
+
const provider = input.provider || prev?.provider || "codeup";
|
|
686
|
+
if (mode === "local") return {
|
|
687
|
+
name: (input.name ?? prev?.name ?? "").trim(),
|
|
688
|
+
mode: "local",
|
|
689
|
+
provider: "local",
|
|
690
|
+
localRoots: normalizeRoots(input.localRoots !== void 0 ? input.localRoots : prev?.localRoots),
|
|
691
|
+
insecureSsl: void 0,
|
|
692
|
+
authorFilters: (input.authorFilters !== void 0 ? input.authorFilters : prev?.authorFilters || []).map((s) => s.trim()).filter(Boolean),
|
|
693
|
+
defaultBranch: (input.defaultBranch ?? prev?.defaultBranch)?.trim() || "master",
|
|
694
|
+
watchedRepoIds: input.watchedRepoIds !== void 0 ? normalizeRepoIds(input.watchedRepoIds) : prev?.watchedRepoIds || [],
|
|
695
|
+
repoBranches: input.repoBranches !== void 0 ? normalizeBranches(input.repoBranches) : prev?.repoBranches || {}
|
|
696
|
+
};
|
|
697
|
+
return {
|
|
698
|
+
name: (input.name ?? prev?.name ?? "").trim(),
|
|
699
|
+
mode: "remote",
|
|
700
|
+
provider,
|
|
701
|
+
edition: provider === "codeup" ? input.edition ?? prev?.edition ?? "central" : void 0,
|
|
702
|
+
organizationId: input.organizationId !== void 0 ? input.organizationId.trim() || void 0 : prev?.organizationId,
|
|
703
|
+
apiBaseUrl: input.apiBaseUrl !== void 0 ? input.apiBaseUrl.trim().replace(/\/$/, "") || void 0 : prev?.apiBaseUrl,
|
|
704
|
+
insecureSsl: input.insecureSsl !== void 0 ? Boolean(input.insecureSsl) : Boolean(prev?.insecureSsl),
|
|
705
|
+
authorFilters: (input.authorFilters !== void 0 ? input.authorFilters : prev?.authorFilters || []).map((s) => s.trim()).filter(Boolean),
|
|
706
|
+
defaultBranch: (input.defaultBranch ?? prev?.defaultBranch)?.trim() || "master",
|
|
707
|
+
watchedRepoIds: input.watchedRepoIds !== void 0 ? normalizeRepoIds(input.watchedRepoIds) : prev?.watchedRepoIds || [],
|
|
708
|
+
repoBranches: input.repoBranches !== void 0 ? normalizeBranches(input.repoBranches) : prev?.repoBranches || {}
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
function createAccount(input) {
|
|
712
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
713
|
+
const fields = buildAccountFields(input);
|
|
714
|
+
const account = {
|
|
715
|
+
id: v4(),
|
|
716
|
+
...fields,
|
|
717
|
+
createdAt: now,
|
|
718
|
+
updatedAt: now
|
|
719
|
+
};
|
|
720
|
+
validateAccount(account, input.token || "");
|
|
721
|
+
if (account.mode === "remote") saveToken(account.id, (input.token || "").trim());
|
|
722
|
+
const store = loadStore();
|
|
723
|
+
store.accounts.push(account);
|
|
724
|
+
if (!store.activeAccountId) store.activeAccountId = account.id;
|
|
725
|
+
saveStore(store);
|
|
726
|
+
return account;
|
|
727
|
+
}
|
|
728
|
+
function updateAccount(input) {
|
|
729
|
+
const store = loadStore();
|
|
730
|
+
const idx = store.accounts.findIndex((a) => a.id === input.id);
|
|
731
|
+
if (idx < 0) {
|
|
732
|
+
const mode = normalizeMode(input.mode);
|
|
733
|
+
if (mode === "remote" && !input.token?.trim()) throw new Error("账号不存在,请先 upsert_account 并填写 token");
|
|
734
|
+
if (mode === "local" && !(input.localRoots && input.localRoots.length)) throw new Error("账号不存在,请先 upsert_account 并填写 localRoots");
|
|
735
|
+
return createAccount({
|
|
736
|
+
name: input.name || "未命名账号",
|
|
737
|
+
mode,
|
|
738
|
+
provider: mode === "local" ? "local" : input.provider || "codeup",
|
|
739
|
+
edition: input.edition || "central",
|
|
740
|
+
organizationId: input.organizationId,
|
|
741
|
+
apiBaseUrl: input.apiBaseUrl,
|
|
742
|
+
insecureSsl: input.insecureSsl,
|
|
743
|
+
localRoots: input.localRoots,
|
|
744
|
+
token: input.token,
|
|
745
|
+
authorFilters: input.authorFilters || [],
|
|
746
|
+
defaultBranch: input.defaultBranch,
|
|
747
|
+
watchedRepoIds: input.watchedRepoIds,
|
|
748
|
+
repoBranches: input.repoBranches
|
|
749
|
+
});
|
|
750
|
+
}
|
|
751
|
+
const prev = store.accounts[idx];
|
|
752
|
+
const fields = buildAccountFields(input, prev);
|
|
753
|
+
const next = {
|
|
754
|
+
...prev,
|
|
755
|
+
...fields,
|
|
756
|
+
id: prev.id,
|
|
757
|
+
createdAt: prev.createdAt,
|
|
758
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
759
|
+
};
|
|
760
|
+
validateAccount(next, next.mode === "local" ? "" : input.token ?? loadToken(next.id) ?? "");
|
|
761
|
+
if (next.mode === "remote" && input.token?.trim()) saveToken(next.id, input.token.trim());
|
|
762
|
+
if (next.mode === "local") deleteToken(next.id);
|
|
763
|
+
store.accounts[idx] = next;
|
|
764
|
+
saveStore(store);
|
|
765
|
+
return next;
|
|
766
|
+
}
|
|
767
|
+
function deleteAccount(id) {
|
|
768
|
+
const store = loadStore();
|
|
769
|
+
store.accounts = store.accounts.filter((a) => a.id !== id);
|
|
770
|
+
if (store.activeAccountId === id) store.activeAccountId = store.accounts[0]?.id ?? null;
|
|
771
|
+
saveStore(store);
|
|
772
|
+
deleteToken(id);
|
|
773
|
+
db.deleteAccountData(id);
|
|
774
|
+
}
|
|
775
|
+
function getAccountToken(id) {
|
|
776
|
+
if (getAccount(id)?.mode === "local") return "";
|
|
777
|
+
const token = loadToken(id);
|
|
778
|
+
if (!token) throw new Error("未找到该账号的访问令牌,请重新填写 PAT");
|
|
779
|
+
return token;
|
|
780
|
+
}
|
|
781
|
+
function validateAccount(account, token) {
|
|
782
|
+
if (!account.name) throw new Error("请填写账号名称");
|
|
783
|
+
if (account.mode === "local") {
|
|
784
|
+
if (!account.localRoots || account.localRoots.length === 0) throw new Error("本地模式请至少填写一个扫描根目录");
|
|
785
|
+
const missing = account.localRoots.filter((p) => !existsSync(p));
|
|
786
|
+
if (missing.length === account.localRoots.length) throw new Error(`扫描根目录均不存在:${missing.join(", ")}`);
|
|
787
|
+
return;
|
|
788
|
+
}
|
|
789
|
+
if (!token.trim()) throw new Error("请填写个人访问令牌");
|
|
790
|
+
if (account.provider === "codeup") {
|
|
791
|
+
if (account.edition === "central" && !account.organizationId) throw new Error("中心版需填写 organizationId");
|
|
792
|
+
if (account.edition === "region" && !account.apiBaseUrl) throw new Error("Region 版需填写 API Base URL");
|
|
793
|
+
}
|
|
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
|
+
}
|
|
826
|
+
// src/providers/codeup/index.ts
|
|
827
|
+
function baseUrl(account) {
|
|
828
|
+
if (account.edition === "region") {
|
|
829
|
+
if (!account.apiBaseUrl) throw new Error("缺少 API Base URL");
|
|
830
|
+
return account.apiBaseUrl.replace(/\/$/, "");
|
|
831
|
+
}
|
|
832
|
+
return "https://openapi-rdc.aliyuncs.com";
|
|
833
|
+
}
|
|
834
|
+
function orgPrefix(account) {
|
|
835
|
+
if (account.edition === "central") {
|
|
836
|
+
if (!account.organizationId) throw new Error("缺少 organizationId");
|
|
837
|
+
return `/oapi/v1/codeup/organizations/${account.organizationId}`;
|
|
838
|
+
}
|
|
839
|
+
return "/oapi/v1/codeup";
|
|
840
|
+
}
|
|
841
|
+
async function request$2(account, token, path, query, options) {
|
|
842
|
+
const url = new URL(`${baseUrl(account)}${orgPrefix(account)}${path}`);
|
|
843
|
+
if (query) for (const [k, v] of Object.entries(query)) {
|
|
844
|
+
if (v === void 0 || v === "") continue;
|
|
845
|
+
url.searchParams.set(k, String(v));
|
|
846
|
+
}
|
|
847
|
+
const res = await fetch(url.toString(), {
|
|
848
|
+
method: "GET",
|
|
849
|
+
headers: {
|
|
850
|
+
"Content-Type": "application/json",
|
|
851
|
+
"x-yunxiao-token": token
|
|
852
|
+
}
|
|
853
|
+
});
|
|
854
|
+
if (!res.ok) {
|
|
855
|
+
const body = await res.text().catch(() => "");
|
|
856
|
+
const brief = body.length > 200 ? `${body.slice(0, 200)}…` : body;
|
|
857
|
+
if (options?.soft) throw new Error(`${res.status} ${body.includes("no permission") ? "Forbidden" : 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}`);
|
|
860
|
+
}
|
|
861
|
+
return {
|
|
862
|
+
data: await res.json(),
|
|
863
|
+
headers: res.headers
|
|
864
|
+
};
|
|
865
|
+
}
|
|
866
|
+
function mapRepo$2(item, participating) {
|
|
867
|
+
return {
|
|
868
|
+
id: String(item.id),
|
|
869
|
+
name: String(item.name || ""),
|
|
870
|
+
fullName: String(item.pathWithNamespace || item.path_with_namespace || item.name || ""),
|
|
871
|
+
webUrl: String(item.webUrl || item.web_url || ""),
|
|
872
|
+
lastActivityAt: item.lastActivityAt || item.last_activity_at,
|
|
873
|
+
defaultBranch: item.defaultBranch || item.default_branch,
|
|
874
|
+
accessLevel: item.accessLevel != null ? Number(item.accessLevel) : item.access_level != null ? Number(item.access_level) : void 0,
|
|
875
|
+
visibility: item.visibility != null ? String(item.visibility) : item.visibility_level != null ? Number(item.visibility_level) === 0 ? "private" : "internal" : void 0,
|
|
876
|
+
starred: Boolean(item.starred || item.star),
|
|
877
|
+
participating
|
|
878
|
+
};
|
|
879
|
+
}
|
|
880
|
+
function isParticipatingRepoHeuristic(repo) {
|
|
881
|
+
if (repo.participating) return true;
|
|
882
|
+
if (repo.starred) return true;
|
|
883
|
+
if ((repo.accessLevel ?? 0) >= 20) return true;
|
|
884
|
+
if (repo.visibility === "private") return true;
|
|
885
|
+
return false;
|
|
886
|
+
}
|
|
887
|
+
async function listParticipatingIdsFromUserResources(account, token) {
|
|
888
|
+
const ids = /* @__PURE__ */ new Set();
|
|
889
|
+
let page = 1;
|
|
890
|
+
const perPage = 20;
|
|
891
|
+
while (true) {
|
|
892
|
+
const { data, headers } = await request$2(account, token, "/users/vision/user_resources", {
|
|
893
|
+
page,
|
|
894
|
+
per_page: perPage
|
|
895
|
+
}, { soft: true });
|
|
896
|
+
const rows = Array.isArray(data) ? data : [];
|
|
897
|
+
for (const row of rows) for (const item of row?.repository_infos || row?.repositoryInfos || []) {
|
|
898
|
+
const id = (item?.repository_info || item?.repositoryInfo || item)?.id ?? item?.source_id ?? item?.sourceId;
|
|
899
|
+
if (id != null) ids.add(String(id));
|
|
900
|
+
}
|
|
901
|
+
const totalPages = Number(headers.get("x-total-pages") || 1);
|
|
902
|
+
if (page >= totalPages || rows.length === 0) break;
|
|
903
|
+
page++;
|
|
904
|
+
if (page > 50) break;
|
|
905
|
+
}
|
|
906
|
+
return ids;
|
|
907
|
+
}
|
|
908
|
+
async function enrichParticipatingFlags(account, token, repos) {
|
|
909
|
+
const ids = /* @__PURE__ */ new Set();
|
|
910
|
+
try {
|
|
911
|
+
for (const id of await listParticipatingIdsFromUserResources(account, token)) ids.add(id);
|
|
912
|
+
} catch {}
|
|
913
|
+
if (ids.size > 0) for (const repo of repos) repo.participating = ids.has(repo.id);
|
|
914
|
+
if (repos.filter((r) => r.participating === true).length === 0) for (const repo of repos) repo.participating = isParticipatingRepoHeuristic(repo);
|
|
915
|
+
}
|
|
916
|
+
const MAX_COMMIT_PAGES$2 = 200;
|
|
917
|
+
const MAX_COMMIT_WINDOWS = 20;
|
|
918
|
+
const COMMIT_PER_PAGE$2 = 100;
|
|
919
|
+
function apiTime(ms) {
|
|
920
|
+
return new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
921
|
+
}
|
|
922
|
+
function asRows(data) {
|
|
923
|
+
if (Array.isArray(data)) return data;
|
|
924
|
+
if (Array.isArray(data?.result)) return data.result;
|
|
925
|
+
if (Array.isArray(data?.list)) return data.list;
|
|
926
|
+
return [];
|
|
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
|
+
}
|
|
970
|
+
/**
|
|
971
|
+
* 云效 Codeup VCS 适配器
|
|
972
|
+
*/
|
|
973
|
+
const codeupProvider = {
|
|
974
|
+
id: "codeup",
|
|
975
|
+
async testConnection(account, token) {
|
|
976
|
+
const { data, headers } = await request$2(account, token, "/repositories", {
|
|
977
|
+
page: 1,
|
|
978
|
+
perPage: 1,
|
|
979
|
+
archived: false
|
|
980
|
+
});
|
|
981
|
+
return { repoCount: Number(headers.get("x-total") || data.length || 0) };
|
|
982
|
+
},
|
|
983
|
+
async listRepos(account, token) {
|
|
984
|
+
const all = [];
|
|
985
|
+
let page = 1;
|
|
986
|
+
const perPage = 100;
|
|
987
|
+
while (true) {
|
|
988
|
+
const { data, headers } = await request$2(account, token, "/repositories", {
|
|
989
|
+
page,
|
|
990
|
+
perPage,
|
|
991
|
+
archived: false,
|
|
992
|
+
orderBy: "last_activity_at",
|
|
993
|
+
sort: "desc"
|
|
994
|
+
});
|
|
995
|
+
for (const item of data || []) {
|
|
996
|
+
const mapped = mapRepo$2(item);
|
|
997
|
+
if ((mapped.accessLevel ?? 0) >= 20) mapped.participating = true;
|
|
998
|
+
all.push(mapped);
|
|
999
|
+
}
|
|
1000
|
+
const totalPages = Number(headers.get("x-total-pages") || 1);
|
|
1001
|
+
if (page >= totalPages || !data?.length) break;
|
|
1002
|
+
page++;
|
|
1003
|
+
}
|
|
1004
|
+
await enrichParticipatingFlags(account, token, all);
|
|
1005
|
+
return all;
|
|
1006
|
+
},
|
|
1007
|
+
async listBranches(account, token, repoId, search) {
|
|
1008
|
+
const all = [];
|
|
1009
|
+
let page = 1;
|
|
1010
|
+
const perPage = 100;
|
|
1011
|
+
while (true) {
|
|
1012
|
+
const { data, headers } = await request$2(account, token, `/repositories/${repoId}/branches`, {
|
|
1013
|
+
page,
|
|
1014
|
+
perPage,
|
|
1015
|
+
sort: "name_asc",
|
|
1016
|
+
search: search || void 0
|
|
1017
|
+
});
|
|
1018
|
+
for (const item of data || []) {
|
|
1019
|
+
const name = String(item.name || "");
|
|
1020
|
+
if (!name) continue;
|
|
1021
|
+
all.push({
|
|
1022
|
+
name,
|
|
1023
|
+
defaultBranch: Boolean(item.defaultBranch),
|
|
1024
|
+
protected: Boolean(item.protected)
|
|
1025
|
+
});
|
|
1026
|
+
}
|
|
1027
|
+
const totalPages = Number(headers.get("x-total-pages") || 1);
|
|
1028
|
+
if (page >= totalPages || !data?.length) break;
|
|
1029
|
+
page++;
|
|
1030
|
+
if (page > 20) break;
|
|
1031
|
+
}
|
|
1032
|
+
return all;
|
|
1033
|
+
},
|
|
1034
|
+
async listCommitsSince(account, token, repoId, opts) {
|
|
1035
|
+
const all = [];
|
|
1036
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1037
|
+
const maxPages = Math.max(1, opts.maxPages ?? MAX_COMMIT_PAGES$2);
|
|
1038
|
+
const since = opts.since;
|
|
1039
|
+
const sinceMs = since ? Date.parse(since) : NaN;
|
|
1040
|
+
let pages = 0;
|
|
1041
|
+
let capped = false;
|
|
1042
|
+
let until;
|
|
1043
|
+
for (let window = 0; window < MAX_COMMIT_WINDOWS; window++) {
|
|
1044
|
+
let page = 1;
|
|
1045
|
+
let windowOldestMs = Infinity;
|
|
1046
|
+
let hitBudget = false;
|
|
1047
|
+
while (true) {
|
|
1048
|
+
if (pages >= maxPages) {
|
|
1049
|
+
capped = true;
|
|
1050
|
+
hitBudget = true;
|
|
1051
|
+
break;
|
|
1052
|
+
}
|
|
1053
|
+
const { data } = await request$2(account, token, `/repositories/${repoId}/commits`, {
|
|
1054
|
+
refName: opts.ref,
|
|
1055
|
+
since,
|
|
1056
|
+
until,
|
|
1057
|
+
page,
|
|
1058
|
+
perPage: COMMIT_PER_PAGE$2
|
|
1059
|
+
});
|
|
1060
|
+
pages++;
|
|
1061
|
+
const rows = asRows(data);
|
|
1062
|
+
if (rows.length === 0) break;
|
|
1063
|
+
let added = 0;
|
|
1064
|
+
for (const item of rows) {
|
|
1065
|
+
const id = String(item.id || item.sha || "");
|
|
1066
|
+
if (!id || seen.has(id)) continue;
|
|
1067
|
+
seen.add(id);
|
|
1068
|
+
added++;
|
|
1069
|
+
const message = String(item.message || item.commitMessage || "");
|
|
1070
|
+
const title = String(item.title || message.split("\n").find((l) => l.trim()) || "");
|
|
1071
|
+
const committedDate = String(item.committedDate || item.authoredDate || "");
|
|
1072
|
+
const ms = Date.parse(committedDate);
|
|
1073
|
+
if (Number.isFinite(ms) && ms < windowOldestMs) windowOldestMs = ms;
|
|
1074
|
+
const { additions, deletions } = parseCommitStats(item);
|
|
1075
|
+
all.push({
|
|
1076
|
+
sha: id,
|
|
1077
|
+
shortId: String(item.shortId || id.slice(0, 8)),
|
|
1078
|
+
title,
|
|
1079
|
+
message: message || title,
|
|
1080
|
+
authorName: String(item.authorName || ""),
|
|
1081
|
+
authorEmail: String(item.authorEmail || ""),
|
|
1082
|
+
authoredAt: String(item.authoredDate || committedDate || ""),
|
|
1083
|
+
committedAt: committedDate,
|
|
1084
|
+
webUrl: String(item.webUrl || ""),
|
|
1085
|
+
...additions != null || deletions != null ? {
|
|
1086
|
+
additions,
|
|
1087
|
+
deletions
|
|
1088
|
+
} : {}
|
|
1089
|
+
});
|
|
1090
|
+
}
|
|
1091
|
+
if (added === 0) {
|
|
1092
|
+
capped = true;
|
|
1093
|
+
hitBudget = true;
|
|
1094
|
+
break;
|
|
1095
|
+
}
|
|
1096
|
+
page++;
|
|
1097
|
+
}
|
|
1098
|
+
if (hitBudget) break;
|
|
1099
|
+
if (!Number.isFinite(sinceMs)) break;
|
|
1100
|
+
if (!Number.isFinite(windowOldestMs)) break;
|
|
1101
|
+
if (windowOldestMs <= sinceMs + 1e3) break;
|
|
1102
|
+
until = apiTime(windowOldestMs - 1e3);
|
|
1103
|
+
}
|
|
1104
|
+
return {
|
|
1105
|
+
commits: all,
|
|
1106
|
+
capped,
|
|
1107
|
+
pages
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
};
|
|
1111
|
+
// src/providers/fetch.ts
|
|
1112
|
+
const USER_AGENT = "dsh-commit-journal";
|
|
1113
|
+
function shouldInsecureTls(account) {
|
|
1114
|
+
if (account?.insecureSsl) return true;
|
|
1115
|
+
const env = String(process.env.DSH_COMMIT_JOURNAL_TLS_INSECURE || "").trim();
|
|
1116
|
+
return env === "1" || /^true$/i.test(env);
|
|
1117
|
+
}
|
|
1118
|
+
function formatFetchCause(err) {
|
|
1119
|
+
const e = err;
|
|
1120
|
+
const cause = e?.cause;
|
|
1121
|
+
const code = cause?.code || e?.code;
|
|
1122
|
+
const msg = cause?.message || e?.message || String(err);
|
|
1123
|
+
if (code) return `${code}: ${msg}`;
|
|
1124
|
+
return msg;
|
|
1125
|
+
}
|
|
1126
|
+
function isCertError(err) {
|
|
1127
|
+
const detail = formatFetchCause(err);
|
|
1128
|
+
const code = err?.cause?.code || err?.code || "";
|
|
1129
|
+
return code === "UNABLE_TO_VERIFY_LEAF_SIGNATURE" || code === "CERT_HAS_EXPIRED" || code === "DEPTH_ZERO_SELF_SIGNED_CERT" || code === "SELF_SIGNED_CERT_IN_CHAIN" || /certificate|SSL|TLS|unable to verify/i.test(detail);
|
|
1130
|
+
}
|
|
1131
|
+
function wrapFetchError(url, err) {
|
|
1132
|
+
const detail = formatFetchCause(err);
|
|
1133
|
+
const code = err?.cause?.code || err?.code || "";
|
|
1134
|
+
if (isCertError(err)) return /* @__PURE__ */ new Error(`连接失败(证书校验):${url}\n${detail}\n常见于公司代理 / HTTPS 解密 / 自签证书。可在账号中勾选「跳过 TLS 证书校验」,或设置环境变量 DSH_COMMIT_JOURNAL_TLS_INSECURE=1 后重启 DSH;更稳妥是把公司根证书路径设到 NODE_EXTRA_CA_CERTS。`);
|
|
1135
|
+
if (code === "ENOTFOUND" || code === "EAI_AGAIN") return /* @__PURE__ */ new Error(`连接失败(DNS):${url}\n${detail}`);
|
|
1136
|
+
if (code === "ECONNREFUSED" || code === "ETIMEDOUT" || code === "ECONNRESET") return /* @__PURE__ */ new Error(`连接失败(网络):${url}\n${detail}`);
|
|
1137
|
+
return /* @__PURE__ */ new Error(`连接失败:${url}\n${detail}`);
|
|
1138
|
+
}
|
|
1139
|
+
function headersToObject(headers) {
|
|
1140
|
+
const out = { "User-Agent": USER_AGENT };
|
|
1141
|
+
if (!headers) return out;
|
|
1142
|
+
if (headers instanceof Headers) {
|
|
1143
|
+
headers.forEach((v, k) => {
|
|
1144
|
+
out[k] = v;
|
|
1145
|
+
});
|
|
1146
|
+
return out;
|
|
1147
|
+
}
|
|
1148
|
+
if (Array.isArray(headers)) {
|
|
1149
|
+
for (const [k, v] of headers) out[k] = v;
|
|
1150
|
+
return out;
|
|
1151
|
+
}
|
|
1152
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
1153
|
+
if (v == null) continue;
|
|
1154
|
+
out[k] = String(v);
|
|
1155
|
+
}
|
|
1156
|
+
return out;
|
|
1157
|
+
}
|
|
1158
|
+
function insecureRequest(urlStr, headers) {
|
|
1159
|
+
return new Promise((resolve, reject) => {
|
|
1160
|
+
const u = new URL(urlStr);
|
|
1161
|
+
const req = (u.protocol === "http:" ? http : https).request(u, {
|
|
1162
|
+
method: "GET",
|
|
1163
|
+
headers,
|
|
1164
|
+
rejectUnauthorized: false
|
|
1165
|
+
}, (res) => {
|
|
1166
|
+
const chunks = [];
|
|
1167
|
+
res.on("data", (c) => chunks.push(c));
|
|
1168
|
+
res.on("end", () => {
|
|
1169
|
+
const headerInit = {};
|
|
1170
|
+
for (const [k, v] of Object.entries(res.headers)) {
|
|
1171
|
+
if (v == null) continue;
|
|
1172
|
+
headerInit[k] = Array.isArray(v) ? v.join(", ") : v;
|
|
1173
|
+
}
|
|
1174
|
+
resolve(new Response(Buffer.concat(chunks), {
|
|
1175
|
+
status: res.statusCode || 0,
|
|
1176
|
+
statusText: res.statusMessage || "",
|
|
1177
|
+
headers: headerInit
|
|
1178
|
+
}));
|
|
1179
|
+
});
|
|
1180
|
+
});
|
|
1181
|
+
req.on("error", reject);
|
|
1182
|
+
req.end();
|
|
1183
|
+
});
|
|
1184
|
+
}
|
|
1185
|
+
/**
|
|
1186
|
+
* VCS HTTP GET:统一 User-Agent、证书错误提示;可选跳过 TLS 校验
|
|
1187
|
+
* 公司代理导致证书失败时自动降级重试一次(无需先勾选 insecureSsl)
|
|
1188
|
+
*/
|
|
1189
|
+
async function vcsFetch(url, init) {
|
|
1190
|
+
const headers = headersToObject(init.headers);
|
|
1191
|
+
if (shouldInsecureTls(init.account)) try {
|
|
1192
|
+
return await insecureRequest(url, headers);
|
|
1193
|
+
} catch (err) {
|
|
1194
|
+
throw wrapFetchError(url, err);
|
|
1195
|
+
}
|
|
1196
|
+
try {
|
|
1197
|
+
return await fetch(url, {
|
|
1198
|
+
method: "GET",
|
|
1199
|
+
headers
|
|
1200
|
+
});
|
|
1201
|
+
} catch (err) {
|
|
1202
|
+
if (!isCertError(err)) throw wrapFetchError(url, err);
|
|
1203
|
+
try {
|
|
1204
|
+
return await insecureRequest(url, headers);
|
|
1205
|
+
} catch (err2) {
|
|
1206
|
+
throw wrapFetchError(url, err2);
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
// src/providers/github/index.ts
|
|
1211
|
+
const MAX_COMMIT_PAGES$1 = 200;
|
|
1212
|
+
const COMMIT_PER_PAGE$1 = 100;
|
|
1213
|
+
function parseGithubComLogin(raw) {
|
|
1214
|
+
const m = raw.trim().replace(/\/$/, "").match(/^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/?#]+)/i);
|
|
1215
|
+
if (!m) return void 0;
|
|
1216
|
+
const login = decodeURIComponent(m[1]);
|
|
1217
|
+
if (!login || /^(settings|orgs|marketplace|explore|topics|about|login|signup)$/i.test(login)) return;
|
|
1218
|
+
return login;
|
|
1219
|
+
}
|
|
1220
|
+
function apiBase$1(account) {
|
|
1221
|
+
const raw = (account.apiBaseUrl || "").trim().replace(/\/$/, "");
|
|
1222
|
+
if (!raw) return "https://api.github.com";
|
|
1223
|
+
if (/^(https?:\/\/)?(www\.)?github\.com(\/|$)/i.test(raw)) return "https://api.github.com";
|
|
1224
|
+
if (/api\.github\.com$/i.test(raw)) return "https://api.github.com";
|
|
1225
|
+
if (/\/api\/v3$/i.test(raw)) return raw;
|
|
1226
|
+
return `${raw}/api/v3`;
|
|
1227
|
+
}
|
|
1228
|
+
function ownerLogin(account) {
|
|
1229
|
+
const raw = (account.organizationId || "").trim();
|
|
1230
|
+
if (!raw) return account.apiBaseUrl ? parseGithubComLogin(account.apiBaseUrl) : void 0;
|
|
1231
|
+
const fromUrl = parseGithubComLogin(raw);
|
|
1232
|
+
if (fromUrl) return fromUrl;
|
|
1233
|
+
return raw.replace(/^@/, "");
|
|
1234
|
+
}
|
|
1235
|
+
function parseLinkNext(linkHeader) {
|
|
1236
|
+
if (!linkHeader) return null;
|
|
1237
|
+
for (const part of linkHeader.split(",")) {
|
|
1238
|
+
const m = part.trim().match(/<([^>]+)>\s*;\s*rel="next"/i);
|
|
1239
|
+
if (m) return m[1];
|
|
1240
|
+
}
|
|
1241
|
+
return null;
|
|
1242
|
+
}
|
|
1243
|
+
async function request$1(account, token, pathOrUrl, query) {
|
|
1244
|
+
const url = pathOrUrl.startsWith("http") ? new URL(pathOrUrl) : new URL(`${apiBase$1(account)}${pathOrUrl}`);
|
|
1245
|
+
if (query) for (const [k, v] of Object.entries(query)) {
|
|
1246
|
+
if (v === void 0 || v === "") continue;
|
|
1247
|
+
url.searchParams.set(k, String(v));
|
|
1248
|
+
}
|
|
1249
|
+
const res = await vcsFetch(url.toString(), {
|
|
1250
|
+
account,
|
|
1251
|
+
headers: {
|
|
1252
|
+
Accept: "application/vnd.github+json",
|
|
1253
|
+
Authorization: `Bearer ${token}`,
|
|
1254
|
+
"X-GitHub-Api-Version": "2022-11-28"
|
|
1255
|
+
}
|
|
1256
|
+
});
|
|
1257
|
+
if (!res.ok) {
|
|
1258
|
+
const body = await res.text().catch(() => "");
|
|
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}`);
|
|
1262
|
+
}
|
|
1263
|
+
return {
|
|
1264
|
+
data: await res.json(),
|
|
1265
|
+
headers: res.headers,
|
|
1266
|
+
status: res.status
|
|
1267
|
+
};
|
|
1268
|
+
}
|
|
1269
|
+
async function requestSoft(account, token, path, query) {
|
|
1270
|
+
try {
|
|
1271
|
+
const res = await request$1(account, token, path, query);
|
|
1272
|
+
return {
|
|
1273
|
+
data: res.data,
|
|
1274
|
+
status: res.status
|
|
1275
|
+
};
|
|
1276
|
+
} catch (e) {
|
|
1277
|
+
const msg = String(e?.message || e);
|
|
1278
|
+
if (/\b404\b/.test(msg)) return null;
|
|
1279
|
+
throw e;
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
function mapRepo$1(item) {
|
|
1283
|
+
const fullName = String(item.full_name || `${item.owner?.login || ""}/${item.name || ""}`);
|
|
1284
|
+
return {
|
|
1285
|
+
id: fullName,
|
|
1286
|
+
name: String(item.name || ""),
|
|
1287
|
+
fullName,
|
|
1288
|
+
webUrl: String(item.html_url || ""),
|
|
1289
|
+
lastActivityAt: item.pushed_at || item.updated_at || void 0,
|
|
1290
|
+
defaultBranch: item.default_branch || void 0,
|
|
1291
|
+
visibility: item.private ? "private" : "public",
|
|
1292
|
+
starred: Boolean(item.starred),
|
|
1293
|
+
participating: true
|
|
1294
|
+
};
|
|
1295
|
+
}
|
|
1296
|
+
function mapCommit$1(item) {
|
|
1297
|
+
const sha = String(item.sha || "");
|
|
1298
|
+
const commit = item.commit || {};
|
|
1299
|
+
const message = String(commit.message || "");
|
|
1300
|
+
const title = message.split("\n").find((l) => l.trim()) || "";
|
|
1301
|
+
const author = commit.author || {};
|
|
1302
|
+
const committer = commit.committer || {};
|
|
1303
|
+
const authoredAt = String(author.date || committer.date || "");
|
|
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;
|
|
1309
|
+
return {
|
|
1310
|
+
sha,
|
|
1311
|
+
shortId: sha.slice(0, 8),
|
|
1312
|
+
title,
|
|
1313
|
+
message: message || title,
|
|
1314
|
+
authorName: String(author.name || item.author?.login || ""),
|
|
1315
|
+
authorEmail: String(author.email || ""),
|
|
1316
|
+
authoredAt,
|
|
1317
|
+
committedAt,
|
|
1318
|
+
webUrl: String(item.html_url || ""),
|
|
1319
|
+
...additions != null || deletions != null ? {
|
|
1320
|
+
additions,
|
|
1321
|
+
deletions
|
|
1322
|
+
} : {},
|
|
1323
|
+
...filesChanged != null ? { filesChanged } : {}
|
|
1324
|
+
};
|
|
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
|
+
}
|
|
1351
|
+
async function paginateRepos(account, token, firstPath, query) {
|
|
1352
|
+
const all = [];
|
|
1353
|
+
let nextUrl = null;
|
|
1354
|
+
let page = 1;
|
|
1355
|
+
while (true) {
|
|
1356
|
+
const { data, headers } = nextUrl ? await request$1(account, token, nextUrl) : await request$1(account, token, firstPath, {
|
|
1357
|
+
...query,
|
|
1358
|
+
page,
|
|
1359
|
+
per_page: 100
|
|
1360
|
+
});
|
|
1361
|
+
const rows = Array.isArray(data) ? data : [];
|
|
1362
|
+
for (const item of rows) all.push(mapRepo$1(item));
|
|
1363
|
+
nextUrl = parseLinkNext(headers.get("link"));
|
|
1364
|
+
if (!nextUrl || rows.length === 0) break;
|
|
1365
|
+
page++;
|
|
1366
|
+
if (page > 100) break;
|
|
1367
|
+
}
|
|
1368
|
+
return all;
|
|
1369
|
+
}
|
|
1370
|
+
async function listReposForOwner(account, token, login) {
|
|
1371
|
+
if (await requestSoft(account, token, `/orgs/${encodeURIComponent(login)}`)) return paginateRepos(account, token, `/orgs/${encodeURIComponent(login)}/repos`, {
|
|
1372
|
+
type: "all",
|
|
1373
|
+
sort: "pushed",
|
|
1374
|
+
direction: "desc"
|
|
1375
|
+
});
|
|
1376
|
+
if (!await requestSoft(account, token, `/users/${encodeURIComponent(login)}`)) throw new Error(`GitHub 找不到组织或用户「${login}」。Organization 请填 org login 或个人 login(不要填完整主页 URL 以外的无效路径);也可留空列出令牌可见的全部仓库。`);
|
|
1377
|
+
return paginateRepos(account, token, `/users/${encodeURIComponent(login)}/repos`, {
|
|
1378
|
+
type: "all",
|
|
1379
|
+
sort: "pushed",
|
|
1380
|
+
direction: "desc"
|
|
1381
|
+
});
|
|
1382
|
+
}
|
|
1383
|
+
/**
|
|
1384
|
+
* GitHub / GitHub Enterprise VCS 适配器
|
|
1385
|
+
*/
|
|
1386
|
+
const githubProvider = {
|
|
1387
|
+
id: "github",
|
|
1388
|
+
async testConnection(account, token) {
|
|
1389
|
+
const login = ownerLogin(account);
|
|
1390
|
+
if (login) {
|
|
1391
|
+
if (await requestSoft(account, token, `/orgs/${encodeURIComponent(login)}`)) {
|
|
1392
|
+
const { data } = await request$1(account, token, `/orgs/${encodeURIComponent(login)}/repos`, {
|
|
1393
|
+
per_page: 1,
|
|
1394
|
+
type: "all"
|
|
1395
|
+
});
|
|
1396
|
+
return { repoCount: Array.isArray(data) ? data.length : 0 };
|
|
1397
|
+
}
|
|
1398
|
+
if (!await requestSoft(account, token, `/users/${encodeURIComponent(login)}`)) throw new Error(`GitHub 找不到组织或用户「${login}」`);
|
|
1399
|
+
const { data } = await request$1(account, token, `/users/${encodeURIComponent(login)}/repos`, {
|
|
1400
|
+
per_page: 1,
|
|
1401
|
+
type: "all"
|
|
1402
|
+
});
|
|
1403
|
+
return { repoCount: Array.isArray(data) ? data.length : 0 };
|
|
1404
|
+
}
|
|
1405
|
+
const { data } = await request$1(account, token, "/user/repos", {
|
|
1406
|
+
per_page: 1,
|
|
1407
|
+
affiliation: "owner,collaborator,organization_member"
|
|
1408
|
+
});
|
|
1409
|
+
return { repoCount: Array.isArray(data) ? data.length : 0 };
|
|
1410
|
+
},
|
|
1411
|
+
async listRepos(account, token) {
|
|
1412
|
+
const login = ownerLogin(account);
|
|
1413
|
+
if (login) return listReposForOwner(account, token, login);
|
|
1414
|
+
return paginateRepos(account, token, "/user/repos", {
|
|
1415
|
+
affiliation: "owner,collaborator,organization_member",
|
|
1416
|
+
sort: "pushed",
|
|
1417
|
+
direction: "desc"
|
|
1418
|
+
});
|
|
1419
|
+
},
|
|
1420
|
+
async listBranches(account, token, repoId, search) {
|
|
1421
|
+
const all = [];
|
|
1422
|
+
let nextUrl = null;
|
|
1423
|
+
let page = 1;
|
|
1424
|
+
const path = `/repos/${repoId}/branches`;
|
|
1425
|
+
while (true) {
|
|
1426
|
+
const { data, headers } = nextUrl ? await request$1(account, token, nextUrl) : await request$1(account, token, path, {
|
|
1427
|
+
page,
|
|
1428
|
+
per_page: 100
|
|
1429
|
+
});
|
|
1430
|
+
const rows = Array.isArray(data) ? data : [];
|
|
1431
|
+
for (const item of rows) {
|
|
1432
|
+
const name = String(item.name || "");
|
|
1433
|
+
if (!name) continue;
|
|
1434
|
+
if (search && !name.toLowerCase().includes(search.toLowerCase())) continue;
|
|
1435
|
+
all.push({
|
|
1436
|
+
name,
|
|
1437
|
+
protected: Boolean(item.protected)
|
|
1438
|
+
});
|
|
1439
|
+
}
|
|
1440
|
+
nextUrl = parseLinkNext(headers.get("link"));
|
|
1441
|
+
if (!nextUrl || rows.length === 0) break;
|
|
1442
|
+
page++;
|
|
1443
|
+
if (page > 20) break;
|
|
1444
|
+
}
|
|
1445
|
+
return all;
|
|
1446
|
+
},
|
|
1447
|
+
async listCommitsSince(account, token, repoId, opts) {
|
|
1448
|
+
const all = [];
|
|
1449
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1450
|
+
const maxPages = Math.max(1, opts.maxPages ?? MAX_COMMIT_PAGES$1);
|
|
1451
|
+
let pages = 0;
|
|
1452
|
+
let capped = false;
|
|
1453
|
+
let nextUrl = null;
|
|
1454
|
+
let page = 1;
|
|
1455
|
+
const path = `/repos/${repoId}/commits`;
|
|
1456
|
+
while (true) {
|
|
1457
|
+
if (pages >= maxPages) {
|
|
1458
|
+
capped = true;
|
|
1459
|
+
break;
|
|
1460
|
+
}
|
|
1461
|
+
const { data, headers } = nextUrl ? await request$1(account, token, nextUrl) : await request$1(account, token, path, {
|
|
1462
|
+
sha: opts.ref,
|
|
1463
|
+
since: opts.since,
|
|
1464
|
+
page,
|
|
1465
|
+
per_page: COMMIT_PER_PAGE$1
|
|
1466
|
+
});
|
|
1467
|
+
pages++;
|
|
1468
|
+
const rows = Array.isArray(data) ? data : [];
|
|
1469
|
+
if (rows.length === 0) break;
|
|
1470
|
+
for (const item of rows) {
|
|
1471
|
+
const mapped = mapCommit$1(item);
|
|
1472
|
+
if (!mapped.sha || seen.has(mapped.sha)) continue;
|
|
1473
|
+
seen.add(mapped.sha);
|
|
1474
|
+
all.push(mapped);
|
|
1475
|
+
}
|
|
1476
|
+
nextUrl = parseLinkNext(headers.get("link"));
|
|
1477
|
+
if (!nextUrl) break;
|
|
1478
|
+
}
|
|
1479
|
+
return {
|
|
1480
|
+
commits: all,
|
|
1481
|
+
capped,
|
|
1482
|
+
pages
|
|
1483
|
+
};
|
|
1484
|
+
}
|
|
1485
|
+
};
|
|
1486
|
+
// src/providers/gitlab/index.ts
|
|
1487
|
+
const MAX_COMMIT_PAGES = 200;
|
|
1488
|
+
const COMMIT_PER_PAGE = 100;
|
|
1489
|
+
function apiBase(account) {
|
|
1490
|
+
let base = (account.apiBaseUrl || "https://gitlab.com").replace(/\/$/, "");
|
|
1491
|
+
if (!/\/api\/v4$/i.test(base)) base = `${base}/api/v4`;
|
|
1492
|
+
return base;
|
|
1493
|
+
}
|
|
1494
|
+
async function request(account, token, path, query) {
|
|
1495
|
+
const url = new URL(`${apiBase(account)}${path}`);
|
|
1496
|
+
if (query) for (const [k, v] of Object.entries(query)) {
|
|
1497
|
+
if (v === void 0 || v === "") continue;
|
|
1498
|
+
url.searchParams.set(k, String(v));
|
|
1499
|
+
}
|
|
1500
|
+
const res = await vcsFetch(url.toString(), {
|
|
1501
|
+
account,
|
|
1502
|
+
headers: {
|
|
1503
|
+
"Content-Type": "application/json",
|
|
1504
|
+
"PRIVATE-TOKEN": token
|
|
1505
|
+
}
|
|
1506
|
+
});
|
|
1507
|
+
if (!res.ok) {
|
|
1508
|
+
const body = await res.text().catch(() => "");
|
|
1509
|
+
if (res.status === 401 || res.status === 403) throw new Error(`GitLab 令牌无效或权限不足(${res.status})。请确认 PAT 至少具备 read_api / read_repository。 原始信息: ${body || res.statusText}`);
|
|
1510
|
+
throw new Error(`GitLab API ${res.status}: ${body || res.statusText}`);
|
|
1511
|
+
}
|
|
1512
|
+
return {
|
|
1513
|
+
data: await res.json(),
|
|
1514
|
+
headers: res.headers
|
|
1515
|
+
};
|
|
1516
|
+
}
|
|
1517
|
+
function mapRepo(item) {
|
|
1518
|
+
return {
|
|
1519
|
+
id: String(item.id),
|
|
1520
|
+
name: String(item.name || ""),
|
|
1521
|
+
fullName: String(item.path_with_namespace || item.name || ""),
|
|
1522
|
+
webUrl: String(item.web_url || ""),
|
|
1523
|
+
lastActivityAt: item.last_activity_at || void 0,
|
|
1524
|
+
defaultBranch: item.default_branch || void 0,
|
|
1525
|
+
visibility: item.visibility != null ? String(item.visibility) : void 0,
|
|
1526
|
+
starred: Boolean(item.starred),
|
|
1527
|
+
participating: true
|
|
1528
|
+
};
|
|
1529
|
+
}
|
|
1530
|
+
function mapCommit(item) {
|
|
1531
|
+
const id = String(item.id || item.sha || "");
|
|
1532
|
+
const message = String(item.message || "");
|
|
1533
|
+
const title = String(item.title || message.split("\n").find((l) => l.trim()) || "");
|
|
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;
|
|
1538
|
+
return {
|
|
1539
|
+
sha: id,
|
|
1540
|
+
shortId: String(item.short_id || id.slice(0, 8)),
|
|
1541
|
+
title,
|
|
1542
|
+
message: message || title,
|
|
1543
|
+
authorName: String(item.author_name || ""),
|
|
1544
|
+
authorEmail: String(item.author_email || ""),
|
|
1545
|
+
authoredAt: String(item.authored_date || committedAt || ""),
|
|
1546
|
+
committedAt,
|
|
1547
|
+
webUrl: String(item.web_url || ""),
|
|
1548
|
+
...additions != null || deletions != null ? {
|
|
1549
|
+
additions,
|
|
1550
|
+
deletions
|
|
1551
|
+
} : {}
|
|
1552
|
+
};
|
|
1553
|
+
}
|
|
1554
|
+
function projectsPath(account) {
|
|
1555
|
+
const group = account.organizationId?.trim();
|
|
1556
|
+
if (group) return `/groups/${encodeURIComponent(group)}/projects`;
|
|
1557
|
+
return "/projects";
|
|
1558
|
+
}
|
|
1559
|
+
function projectsQuery(account, page, perPage) {
|
|
1560
|
+
const group = account.organizationId?.trim();
|
|
1561
|
+
const base = {
|
|
1562
|
+
page,
|
|
1563
|
+
per_page: perPage,
|
|
1564
|
+
order_by: "last_activity_at",
|
|
1565
|
+
sort: "desc",
|
|
1566
|
+
archived: false
|
|
1567
|
+
};
|
|
1568
|
+
if (!group) base.membership = true;
|
|
1569
|
+
return base;
|
|
1570
|
+
}
|
|
1571
|
+
/**
|
|
1572
|
+
* GitLab(含自建)VCS 适配器
|
|
1573
|
+
*/
|
|
1574
|
+
const gitlabProvider = {
|
|
1575
|
+
id: "gitlab",
|
|
1576
|
+
async testConnection(account, token) {
|
|
1577
|
+
const { data, headers } = await request(account, token, projectsPath(account), projectsQuery(account, 1, 1));
|
|
1578
|
+
return { repoCount: Number(headers.get("x-total") || (Array.isArray(data) ? data.length : 0)) };
|
|
1579
|
+
},
|
|
1580
|
+
async listRepos(account, token) {
|
|
1581
|
+
const all = [];
|
|
1582
|
+
let page = 1;
|
|
1583
|
+
const perPage = 100;
|
|
1584
|
+
while (true) {
|
|
1585
|
+
const { data, headers } = await request(account, token, projectsPath(account), projectsQuery(account, page, perPage));
|
|
1586
|
+
const rows = Array.isArray(data) ? data : [];
|
|
1587
|
+
for (const item of rows) all.push(mapRepo(item));
|
|
1588
|
+
const totalPages = Number(headers.get("x-total-pages") || 1);
|
|
1589
|
+
if (page >= totalPages || rows.length === 0) break;
|
|
1590
|
+
page++;
|
|
1591
|
+
if (page > 100) break;
|
|
1592
|
+
}
|
|
1593
|
+
return all;
|
|
1594
|
+
},
|
|
1595
|
+
async listBranches(account, token, repoId, search) {
|
|
1596
|
+
const all = [];
|
|
1597
|
+
let page = 1;
|
|
1598
|
+
const perPage = 100;
|
|
1599
|
+
while (true) {
|
|
1600
|
+
const { data, headers } = await request(account, token, `/projects/${encodeURIComponent(repoId)}/repository/branches`, {
|
|
1601
|
+
page,
|
|
1602
|
+
per_page: perPage,
|
|
1603
|
+
search: search || void 0
|
|
1604
|
+
});
|
|
1605
|
+
const rows = Array.isArray(data) ? data : [];
|
|
1606
|
+
for (const item of rows) {
|
|
1607
|
+
const name = String(item.name || "");
|
|
1608
|
+
if (!name) continue;
|
|
1609
|
+
all.push({
|
|
1610
|
+
name,
|
|
1611
|
+
defaultBranch: Boolean(item.default),
|
|
1612
|
+
protected: Boolean(item.protected)
|
|
1613
|
+
});
|
|
1614
|
+
}
|
|
1615
|
+
const totalPages = Number(headers.get("x-total-pages") || 1);
|
|
1616
|
+
if (page >= totalPages || rows.length === 0) break;
|
|
1617
|
+
page++;
|
|
1618
|
+
if (page > 20) break;
|
|
1619
|
+
}
|
|
1620
|
+
return all;
|
|
1621
|
+
},
|
|
1622
|
+
async listCommitsSince(account, token, repoId, opts) {
|
|
1623
|
+
const all = [];
|
|
1624
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1625
|
+
const maxPages = Math.max(1, opts.maxPages ?? MAX_COMMIT_PAGES);
|
|
1626
|
+
let pages = 0;
|
|
1627
|
+
let capped = false;
|
|
1628
|
+
let page = 1;
|
|
1629
|
+
while (true) {
|
|
1630
|
+
if (pages >= maxPages) {
|
|
1631
|
+
capped = true;
|
|
1632
|
+
break;
|
|
1633
|
+
}
|
|
1634
|
+
const { data, headers } = await request(account, token, `/projects/${encodeURIComponent(repoId)}/repository/commits`, {
|
|
1635
|
+
ref_name: opts.ref,
|
|
1636
|
+
since: opts.since,
|
|
1637
|
+
page,
|
|
1638
|
+
per_page: COMMIT_PER_PAGE,
|
|
1639
|
+
with_stats: true
|
|
1640
|
+
});
|
|
1641
|
+
pages++;
|
|
1642
|
+
const rows = Array.isArray(data) ? data : [];
|
|
1643
|
+
if (rows.length === 0) break;
|
|
1644
|
+
for (const item of rows) {
|
|
1645
|
+
const mapped = mapCommit(item);
|
|
1646
|
+
if (!mapped.sha || seen.has(mapped.sha)) continue;
|
|
1647
|
+
seen.add(mapped.sha);
|
|
1648
|
+
all.push(mapped);
|
|
1649
|
+
}
|
|
1650
|
+
const nextPage = headers.get("x-next-page");
|
|
1651
|
+
if (!nextPage) break;
|
|
1652
|
+
page = Number(nextPage);
|
|
1653
|
+
if (!Number.isFinite(page) || page <= 0) break;
|
|
1654
|
+
}
|
|
1655
|
+
return {
|
|
1656
|
+
commits: all,
|
|
1657
|
+
capped,
|
|
1658
|
+
pages
|
|
1659
|
+
};
|
|
1660
|
+
}
|
|
1661
|
+
};
|
|
1662
|
+
// src/providers/local/index.ts
|
|
1663
|
+
const execFileAsync = promisify(execFile);
|
|
1664
|
+
const MAX_DEPTH = 5;
|
|
1665
|
+
const SKIP_DIRS = /* @__PURE__ */ new Set([
|
|
1666
|
+
"node_modules",
|
|
1667
|
+
".git",
|
|
1668
|
+
"dist",
|
|
1669
|
+
"build",
|
|
1670
|
+
".next",
|
|
1671
|
+
"target",
|
|
1672
|
+
".turbo",
|
|
1673
|
+
"coverage",
|
|
1674
|
+
".cache"
|
|
1675
|
+
]);
|
|
1676
|
+
let cachedGitBin;
|
|
1677
|
+
const WIN_GIT_CANDIDATES = [
|
|
1678
|
+
"C:\\Program Files\\Git\\cmd\\git.exe",
|
|
1679
|
+
"C:\\Program Files\\Git\\bin\\git.exe",
|
|
1680
|
+
"C:\\Program Files (x86)\\Git\\cmd\\git.exe",
|
|
1681
|
+
"C:\\Program Files (x86)\\Git\\bin\\git.exe"
|
|
1682
|
+
];
|
|
1683
|
+
const pathByRepoId = /* @__PURE__ */ new Map();
|
|
1684
|
+
function normalizePath(p) {
|
|
1685
|
+
return resolve(p).replace(/[\\/]+$/, "");
|
|
1686
|
+
}
|
|
1687
|
+
function resolveGitBin() {
|
|
1688
|
+
if (cachedGitBin !== void 0) {
|
|
1689
|
+
if (!cachedGitBin) throw new Error("未找到 git 可执行文件。请安装 Git for Windows,或把 git 加入系统 PATH 后重启 DSH。");
|
|
1690
|
+
return cachedGitBin;
|
|
1691
|
+
}
|
|
1692
|
+
const fromEnv = process.env.DSH_COMMIT_JOURNAL_GIT?.trim();
|
|
1693
|
+
if (fromEnv && existsSync(fromEnv)) {
|
|
1694
|
+
cachedGitBin = fromEnv;
|
|
1695
|
+
return cachedGitBin;
|
|
1696
|
+
}
|
|
1697
|
+
const pathDirs = (process.env.PATH || process.env.Path || "").split(delimiter).filter(Boolean);
|
|
1698
|
+
for (const dir of pathDirs) {
|
|
1699
|
+
const unix = join(dir, "git");
|
|
1700
|
+
const win = join(dir, "git.exe");
|
|
1701
|
+
if (process.platform === "win32" && existsSync(win)) {
|
|
1702
|
+
cachedGitBin = win;
|
|
1703
|
+
return cachedGitBin;
|
|
1704
|
+
}
|
|
1705
|
+
if (existsSync(unix)) {
|
|
1706
|
+
cachedGitBin = unix;
|
|
1707
|
+
return cachedGitBin;
|
|
1708
|
+
}
|
|
1709
|
+
}
|
|
1710
|
+
if (process.platform === "win32") {
|
|
1711
|
+
for (const cand of WIN_GIT_CANDIDATES) if (existsSync(cand)) {
|
|
1712
|
+
cachedGitBin = cand;
|
|
1713
|
+
return cachedGitBin;
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
cachedGitBin = null;
|
|
1717
|
+
throw new Error("未找到 git 可执行文件。请安装 Git for Windows,或把 git 加入系统 PATH 后重启 DSH。");
|
|
1718
|
+
}
|
|
1719
|
+
function repoIdForPath(absPath) {
|
|
1720
|
+
return `local:${createHash("sha1").update(normalizePath(absPath).toLowerCase()).digest("hex").slice(0, 16)}`;
|
|
1721
|
+
}
|
|
1722
|
+
function isGitDir(gitPath) {
|
|
1723
|
+
try {
|
|
1724
|
+
const st = lstatSync(gitPath);
|
|
1725
|
+
if (st.isDirectory()) return existsSync(join(gitPath, "HEAD")) || existsSync(join(gitPath, "refs"));
|
|
1726
|
+
if (st.isFile()) {
|
|
1727
|
+
const text = readFileSync(gitPath, "utf8");
|
|
1728
|
+
return /^gitdir:\s+/i.test(text.trim());
|
|
1729
|
+
}
|
|
1730
|
+
} catch {
|
|
1731
|
+
return false;
|
|
1732
|
+
}
|
|
1733
|
+
return false;
|
|
1734
|
+
}
|
|
1735
|
+
function safeRealPath(p) {
|
|
1736
|
+
try {
|
|
1737
|
+
return realpathSync(p);
|
|
1738
|
+
} catch {
|
|
1739
|
+
return normalizePath(p);
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
function walkRepos(dir, root, depth, out) {
|
|
1743
|
+
if (depth > MAX_DEPTH) return;
|
|
1744
|
+
let entries;
|
|
1745
|
+
try {
|
|
1746
|
+
entries = readdirSync(dir);
|
|
1747
|
+
} catch {
|
|
1748
|
+
return;
|
|
1749
|
+
}
|
|
1750
|
+
if (entries.includes(".git") && isGitDir(join(dir, ".git"))) {
|
|
1751
|
+
const abs = safeRealPath(dir);
|
|
1752
|
+
const id = repoIdForPath(abs);
|
|
1753
|
+
if (!out.has(id)) out.set(id, abs);
|
|
1754
|
+
return;
|
|
1755
|
+
}
|
|
1756
|
+
for (const name of entries) {
|
|
1757
|
+
if (SKIP_DIRS.has(name)) continue;
|
|
1758
|
+
if (name.startsWith(".") && name !== ".git") continue;
|
|
1759
|
+
const child = join(dir, name);
|
|
1760
|
+
let st;
|
|
1761
|
+
try {
|
|
1762
|
+
st = lstatSync(child);
|
|
1763
|
+
} catch {
|
|
1764
|
+
continue;
|
|
1765
|
+
}
|
|
1766
|
+
if (!st.isDirectory() || st.isSymbolicLink()) continue;
|
|
1767
|
+
walkRepos(child, root, depth + 1, out);
|
|
1768
|
+
}
|
|
1769
|
+
}
|
|
1770
|
+
function discoverRepos(account) {
|
|
1771
|
+
const found = /* @__PURE__ */ new Map();
|
|
1772
|
+
const roots = account.localRoots || [];
|
|
1773
|
+
for (const root of roots) {
|
|
1774
|
+
if (!existsSync(root)) continue;
|
|
1775
|
+
let st;
|
|
1776
|
+
try {
|
|
1777
|
+
st = statSync(root);
|
|
1778
|
+
} catch {
|
|
1779
|
+
continue;
|
|
1780
|
+
}
|
|
1781
|
+
if (!st.isDirectory()) continue;
|
|
1782
|
+
const absRoot = safeRealPath(root);
|
|
1783
|
+
walkRepos(absRoot, absRoot, 0, found);
|
|
1784
|
+
}
|
|
1785
|
+
const repos = [];
|
|
1786
|
+
pathByRepoId.clear();
|
|
1787
|
+
for (const [id, abs] of found) {
|
|
1788
|
+
pathByRepoId.set(id, abs);
|
|
1789
|
+
const name = basename(abs);
|
|
1790
|
+
let fullName = abs;
|
|
1791
|
+
for (const root of roots) {
|
|
1792
|
+
if (!existsSync(root)) continue;
|
|
1793
|
+
const absRoot = safeRealPath(root);
|
|
1794
|
+
const rel = relative(absRoot, abs);
|
|
1795
|
+
if (rel && !rel.startsWith("..") && !rel.includes(`..${sep}`)) {
|
|
1796
|
+
fullName = join(basename(absRoot), rel).split(sep).join("/");
|
|
1797
|
+
break;
|
|
1798
|
+
}
|
|
1799
|
+
if (normalizePath(absRoot).toLowerCase() === normalizePath(abs).toLowerCase()) {
|
|
1800
|
+
fullName = basename(abs);
|
|
1801
|
+
break;
|
|
1802
|
+
}
|
|
1803
|
+
}
|
|
1804
|
+
repos.push({
|
|
1805
|
+
id,
|
|
1806
|
+
name,
|
|
1807
|
+
fullName,
|
|
1808
|
+
webUrl: "",
|
|
1809
|
+
defaultBranch: void 0
|
|
1810
|
+
});
|
|
1811
|
+
}
|
|
1812
|
+
repos.sort((a, b) => a.fullName.localeCompare(b.fullName));
|
|
1813
|
+
return repos;
|
|
1814
|
+
}
|
|
1815
|
+
function resolveWorkTree(account, repoId) {
|
|
1816
|
+
const cached = pathByRepoId.get(repoId);
|
|
1817
|
+
if (cached && existsSync(cached)) return cached;
|
|
1818
|
+
discoverRepos(account);
|
|
1819
|
+
const again = pathByRepoId.get(repoId);
|
|
1820
|
+
if (!again || !existsSync(again)) throw new Error(`未找到本地仓库 ${repoId},请先刷新仓库列表`);
|
|
1821
|
+
return again;
|
|
1822
|
+
}
|
|
1823
|
+
async function git(cwd, args) {
|
|
1824
|
+
const bin = resolveGitBin();
|
|
1825
|
+
try {
|
|
1826
|
+
const { stdout } = await execFileAsync(bin, [
|
|
1827
|
+
"-C",
|
|
1828
|
+
cwd,
|
|
1829
|
+
...args
|
|
1830
|
+
], {
|
|
1831
|
+
encoding: "utf8",
|
|
1832
|
+
maxBuffer: 20971520,
|
|
1833
|
+
windowsHide: true
|
|
1834
|
+
});
|
|
1835
|
+
return stdout;
|
|
1836
|
+
} catch (e) {
|
|
1837
|
+
if (e?.code === "ENOENT") {
|
|
1838
|
+
cachedGitBin = void 0;
|
|
1839
|
+
throw new Error(`无法启动 git(${bin})。请确认已安装 Git,或设置环境变量 DSH_COMMIT_JOURNAL_GIT 指向 git.exe。`);
|
|
1840
|
+
}
|
|
1841
|
+
const msg = e?.stderr || e?.message || String(e);
|
|
1842
|
+
throw new Error(`git ${args.join(" ")} 失败: ${String(msg).trim()}`);
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
async function defaultBranchName(cwd) {
|
|
1846
|
+
try {
|
|
1847
|
+
const m = (await git(cwd, ["symbolic-ref", "refs/remotes/origin/HEAD"])).trim().match(/refs\/remotes\/origin\/(.+)$/);
|
|
1848
|
+
if (m?.[1]) return m[1];
|
|
1849
|
+
} catch {}
|
|
1850
|
+
try {
|
|
1851
|
+
const cur = (await git(cwd, [
|
|
1852
|
+
"rev-parse",
|
|
1853
|
+
"--abbrev-ref",
|
|
1854
|
+
"HEAD"
|
|
1855
|
+
])).trim();
|
|
1856
|
+
if (cur && cur !== "HEAD") return cur;
|
|
1857
|
+
} catch {}
|
|
1858
|
+
}
|
|
1859
|
+
/**
|
|
1860
|
+
* 本机 git 扫描适配器:按账号 localRoots 发现仓库并拉取提交
|
|
1861
|
+
*/
|
|
1862
|
+
const localGitProvider = {
|
|
1863
|
+
id: "local",
|
|
1864
|
+
async testConnection(account) {
|
|
1865
|
+
resolveGitBin();
|
|
1866
|
+
return { repoCount: discoverRepos(account).length };
|
|
1867
|
+
},
|
|
1868
|
+
async listRepos(account) {
|
|
1869
|
+
const repos = discoverRepos(account);
|
|
1870
|
+
for (const r of repos) {
|
|
1871
|
+
const cwd = pathByRepoId.get(r.id);
|
|
1872
|
+
if (!cwd) continue;
|
|
1873
|
+
try {
|
|
1874
|
+
r.defaultBranch = await defaultBranchName(cwd);
|
|
1875
|
+
} catch {}
|
|
1876
|
+
}
|
|
1877
|
+
return repos;
|
|
1878
|
+
},
|
|
1879
|
+
async listBranches(account, _token, repoId) {
|
|
1880
|
+
const cwd = resolveWorkTree(account, repoId);
|
|
1881
|
+
const def = await defaultBranchName(cwd);
|
|
1882
|
+
const names = (await git(cwd, [
|
|
1883
|
+
"for-each-ref",
|
|
1884
|
+
"--format=%(refname:short)",
|
|
1885
|
+
"refs/heads"
|
|
1886
|
+
])).split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
|
|
1887
|
+
const unique = Array.from(new Set(names));
|
|
1888
|
+
if (def && !unique.includes(def)) unique.unshift(def);
|
|
1889
|
+
return unique.map((name) => ({
|
|
1890
|
+
name,
|
|
1891
|
+
defaultBranch: name === def
|
|
1892
|
+
}));
|
|
1893
|
+
},
|
|
1894
|
+
async listCommitsSince(account, _token, repoId, opts) {
|
|
1895
|
+
const cwd = resolveWorkTree(account, repoId);
|
|
1896
|
+
const args = [
|
|
1897
|
+
"log",
|
|
1898
|
+
opts.ref || "HEAD",
|
|
1899
|
+
"--no-merges",
|
|
1900
|
+
"--date=iso-strict",
|
|
1901
|
+
"--format=%H%x1f%h%x1f%s%x1f%b%x1f%an%x1f%ae%x1f%aI%x1f%cI%x1e",
|
|
1902
|
+
"--numstat"
|
|
1903
|
+
];
|
|
1904
|
+
if (opts.since) args.push(`--since=${opts.since}`);
|
|
1905
|
+
const max = Math.max(1, (opts.maxPages ?? 20) * 100);
|
|
1906
|
+
args.push(`-n${max}`);
|
|
1907
|
+
let raw = "";
|
|
1908
|
+
try {
|
|
1909
|
+
raw = await git(cwd, args);
|
|
1910
|
+
} catch (e) {
|
|
1911
|
+
const msg = String(e?.message || e);
|
|
1912
|
+
if (/unknown revision|bad revision|ambiguous argument/i.test(msg)) return {
|
|
1913
|
+
commits: [],
|
|
1914
|
+
capped: false,
|
|
1915
|
+
pages: 0
|
|
1916
|
+
};
|
|
1917
|
+
throw e;
|
|
1918
|
+
}
|
|
1919
|
+
const commits = [];
|
|
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);
|
|
1937
|
+
}
|
|
1938
|
+
return {
|
|
1939
|
+
commits,
|
|
1940
|
+
capped: commits.length >= max,
|
|
1941
|
+
pages: Math.ceil(commits.length / 100) || (commits.length ? 1 : 0)
|
|
1942
|
+
};
|
|
1943
|
+
}
|
|
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
|
+
}
|
|
1990
|
+
// src/providers/index.ts
|
|
1991
|
+
const providers = {
|
|
1992
|
+
codeup: codeupProvider,
|
|
1993
|
+
local: localGitProvider,
|
|
1994
|
+
gitlab: gitlabProvider,
|
|
1995
|
+
github: githubProvider
|
|
1996
|
+
};
|
|
1997
|
+
function getProvider(providerId) {
|
|
1998
|
+
if (typeof providerId !== "string" && providerId.mode === "local") return localGitProvider;
|
|
1999
|
+
const id = typeof providerId === "string" ? providerId : providerId.provider;
|
|
2000
|
+
const provider = providers[id];
|
|
2001
|
+
if (!provider) throw new Error(`未知 VCS provider「${id}」。支持 codeup / gitlab / github / local。`);
|
|
2002
|
+
return provider;
|
|
2003
|
+
}
|
|
2004
|
+
// src/core/sync.ts
|
|
2005
|
+
const timers = /* @__PURE__ */ new Map();
|
|
2006
|
+
const syncing = /* @__PURE__ */ new Set();
|
|
2007
|
+
const DAY_MS = 864e5;
|
|
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
|
+
}
|
|
2018
|
+
function toApiTime(iso) {
|
|
2019
|
+
const t = Date.parse(iso);
|
|
2020
|
+
return (Number.isFinite(t) ? new Date(t) : new Date(iso)).toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
2021
|
+
}
|
|
2022
|
+
function matchAuthor(account, name, email) {
|
|
2023
|
+
if (!account.authorFilters.length) return true;
|
|
2024
|
+
const hay = `${name} ${email}`.toLowerCase();
|
|
2025
|
+
return account.authorFilters.some((f) => hay.includes(f.toLowerCase()));
|
|
2026
|
+
}
|
|
2027
|
+
function writeDailyExports(accountId, commits) {
|
|
2028
|
+
if (!commits.length) return;
|
|
2029
|
+
const root = exportsDir();
|
|
2030
|
+
const byDay = /* @__PURE__ */ new Map();
|
|
2031
|
+
for (const c of commits) {
|
|
2032
|
+
const day = c.committedAt.slice(0, 10);
|
|
2033
|
+
if (!byDay.has(day)) byDay.set(day, []);
|
|
2034
|
+
byDay.get(day).push(c);
|
|
2035
|
+
}
|
|
2036
|
+
for (const [day, list] of byDay) {
|
|
2037
|
+
const dir = join(root, accountId);
|
|
2038
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
2039
|
+
const path = join(dir, `${day}.md`);
|
|
2040
|
+
const existing = existsSync(path) ? readFileSync(path, "utf8") : `# ${day} 提交材料\n\n`;
|
|
2041
|
+
const lines = [];
|
|
2042
|
+
for (const c of list) {
|
|
2043
|
+
if (existing.includes(c.sha)) continue;
|
|
2044
|
+
const [first, ...rest] = commitFullText(c).split("\n");
|
|
2045
|
+
const stats = formatCommitDiffStats(c);
|
|
2046
|
+
lines.push(`- **[${c.repoName}]** ${stats ? `${first}(${stats})` : first}`);
|
|
2047
|
+
for (const line of rest) lines.push(` ${line}`);
|
|
2048
|
+
lines.push(` - 时间: ${c.committedAt}`);
|
|
2049
|
+
lines.push(` - 作者: ${c.authorName} <${c.authorEmail}>`);
|
|
2050
|
+
lines.push(` - SHA: \`${c.shortId}\` (${c.sha})`);
|
|
2051
|
+
if (stats) lines.push(` - 变更: ${stats}`);
|
|
2052
|
+
if (c.webUrl) lines.push(` - 链接: ${c.webUrl}`);
|
|
2053
|
+
lines.push("");
|
|
2054
|
+
}
|
|
2055
|
+
if (lines.length) writeFileSync(path, existing + lines.join("\n"), "utf8");
|
|
2056
|
+
}
|
|
2057
|
+
}
|
|
2058
|
+
async function syncAccount(accountId, repoIds) {
|
|
2059
|
+
if (syncing.has(accountId)) return {
|
|
2060
|
+
accountId,
|
|
2061
|
+
fetched: 0,
|
|
2062
|
+
inserted: 0,
|
|
2063
|
+
errors: ["同步进行中,请稍后再试"]
|
|
2064
|
+
};
|
|
2065
|
+
syncing.add(accountId);
|
|
2066
|
+
const errors = [];
|
|
2067
|
+
let fetched = 0;
|
|
2068
|
+
let inserted = 0;
|
|
2069
|
+
let matched = 0;
|
|
2070
|
+
let truncated = 0;
|
|
2071
|
+
let statsFilled = 0;
|
|
2072
|
+
try {
|
|
2073
|
+
const account = getAccount(accountId);
|
|
2074
|
+
if (!account) throw new Error("账号不存在");
|
|
2075
|
+
const token = account.mode === "local" ? "" : getAccountToken(accountId);
|
|
2076
|
+
const provider = getProvider(account);
|
|
2077
|
+
const isLocal = account.mode === "local";
|
|
2078
|
+
const onlyIds = repoIds && repoIds.length > 0 ? Array.from(new Set(repoIds.map(String))) : null;
|
|
2079
|
+
db.addSyncLog({
|
|
2080
|
+
id: v4(),
|
|
2081
|
+
accountId,
|
|
2082
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2083
|
+
level: "info",
|
|
2084
|
+
message: onlyIds ? `${isLocal ? "开始扫描指定仓库" : "开始同步指定仓库"}(${onlyIds.length} 个)` : isLocal ? "开始扫描关注的本地仓库" : "开始同步全部关注仓库"
|
|
2085
|
+
});
|
|
2086
|
+
let repos = db.listRepos(accountId);
|
|
2087
|
+
if (!onlyIds || onlyIds.some((id) => !repos.find((r) => r.id === id))) {
|
|
2088
|
+
const latest = await provider.listRepos(account, token);
|
|
2089
|
+
db.upsertRepos(accountId, latest);
|
|
2090
|
+
repos = db.listRepos(accountId);
|
|
2091
|
+
}
|
|
2092
|
+
const targets = onlyIds ? repos.filter((r) => onlyIds.includes(r.id)) : account.watchedRepoIds.length > 0 ? repos.filter((r) => account.watchedRepoIds.includes(r.id)) : repos;
|
|
2093
|
+
if (onlyIds && targets.length === 0) throw new Error("未找到要同步的仓库,请先刷新仓库列表");
|
|
2094
|
+
const newCommits = [];
|
|
2095
|
+
for (const repo of targets) try {
|
|
2096
|
+
const branch = account.repoBranches[repo.id] || repo.defaultBranch || account.defaultBranch || "master";
|
|
2097
|
+
const state = db.getSyncState(accountId, repo.id);
|
|
2098
|
+
const lookbackDays = getSyncLookbackDays();
|
|
2099
|
+
const fullFromMs = Date.now() - lookbackDays * DAY_MS;
|
|
2100
|
+
const needBackfill = !state?.lastSyncedAt || lookbackDays > (state.lookbackDays ?? 0);
|
|
2101
|
+
const lastMs = state?.lastSyncedAt ? Date.parse(state.lastSyncedAt) : NaN;
|
|
2102
|
+
const sinceMs = needBackfill ? fullFromMs : Number.isFinite(lastMs) ? lastMs - INCREMENTAL_OVERLAP_MS : fullFromMs;
|
|
2103
|
+
const since = toApiTime(new Date(sinceMs).toISOString());
|
|
2104
|
+
const { commits, capped, pages } = await provider.listCommitsSince(account, token, repo.id, {
|
|
2105
|
+
ref: branch,
|
|
2106
|
+
since
|
|
2107
|
+
});
|
|
2108
|
+
fetched += commits.length;
|
|
2109
|
+
if (capped) {
|
|
2110
|
+
truncated++;
|
|
2111
|
+
const msg = `仓库 ${shortRepoPath(repo.fullName || repo.name, account.organizationId)}: 提交过多,本次只取到 ${commits.length} 条(${pages} 页上限),更早的提交可能未同步`;
|
|
2112
|
+
db.addSyncLog({
|
|
2113
|
+
id: v4(),
|
|
2114
|
+
accountId,
|
|
2115
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2116
|
+
level: "warn",
|
|
2117
|
+
message: msg
|
|
2118
|
+
});
|
|
2119
|
+
}
|
|
2120
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
2121
|
+
const batch = [];
|
|
2122
|
+
for (const c of commits) {
|
|
2123
|
+
if (!matchAuthor(account, c.authorName, c.authorEmail)) continue;
|
|
2124
|
+
matched++;
|
|
2125
|
+
batch.push({
|
|
2126
|
+
id: v4(),
|
|
2127
|
+
accountId,
|
|
2128
|
+
repoId: repo.id,
|
|
2129
|
+
repoName: shortRepoPath(repo.fullName || repo.name, account.organizationId),
|
|
2130
|
+
sha: c.sha,
|
|
2131
|
+
shortId: c.shortId,
|
|
2132
|
+
title: c.title,
|
|
2133
|
+
message: c.message,
|
|
2134
|
+
authorName: c.authorName,
|
|
2135
|
+
authorEmail: c.authorEmail,
|
|
2136
|
+
committedAt: c.committedAt || c.authoredAt,
|
|
2137
|
+
webUrl: c.webUrl,
|
|
2138
|
+
syncedAt: now,
|
|
2139
|
+
...c.additions != null ? { additions: c.additions } : {},
|
|
2140
|
+
...c.deletions != null ? { deletions: c.deletions } : {},
|
|
2141
|
+
...c.filesChanged != null ? { filesChanged: c.filesChanged } : {}
|
|
2142
|
+
});
|
|
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);
|
|
2157
|
+
db.setSyncState({
|
|
2158
|
+
accountId,
|
|
2159
|
+
repoId: repo.id,
|
|
2160
|
+
lastSyncedAt: now,
|
|
2161
|
+
lookbackDays
|
|
2162
|
+
});
|
|
2163
|
+
} catch (e) {
|
|
2164
|
+
const msg = `仓库 ${shortRepoPath(repo.fullName || repo.name, account.organizationId)}: ${e?.message || e}`;
|
|
2165
|
+
errors.push(msg);
|
|
2166
|
+
db.addSyncLog({
|
|
2167
|
+
id: v4(),
|
|
2168
|
+
accountId,
|
|
2169
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2170
|
+
level: "error",
|
|
2171
|
+
message: msg
|
|
2172
|
+
});
|
|
2173
|
+
}
|
|
2174
|
+
inserted = db.insertCommits(newCommits);
|
|
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
|
+
}
|
|
2201
|
+
db.addSyncLog({
|
|
2202
|
+
id: v4(),
|
|
2203
|
+
accountId,
|
|
2204
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2205
|
+
level: errors.length || truncated ? "warn" : "info",
|
|
2206
|
+
message: `同步完成:拉取 ${fetched}(匹配作者 ${matched}),新增 ${inserted}${statsFilled ? `,补全变更统计 ${statsFilled}` : ""}${truncated ? `,${truncated} 个仓库触及分页上限` : ""}${errors.length ? `,失败 ${errors.length}` : ""}`
|
|
2207
|
+
});
|
|
2208
|
+
return {
|
|
2209
|
+
accountId,
|
|
2210
|
+
fetched,
|
|
2211
|
+
inserted,
|
|
2212
|
+
errors,
|
|
2213
|
+
truncated
|
|
2214
|
+
};
|
|
2215
|
+
} catch (e) {
|
|
2216
|
+
const msg = e?.message || String(e);
|
|
2217
|
+
errors.push(msg);
|
|
2218
|
+
db.addSyncLog({
|
|
2219
|
+
id: v4(),
|
|
2220
|
+
accountId,
|
|
2221
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2222
|
+
level: "error",
|
|
2223
|
+
message: msg
|
|
2224
|
+
});
|
|
2225
|
+
return {
|
|
2226
|
+
accountId,
|
|
2227
|
+
fetched,
|
|
2228
|
+
inserted,
|
|
2229
|
+
errors
|
|
2230
|
+
};
|
|
2231
|
+
} finally {
|
|
2232
|
+
syncing.delete(accountId);
|
|
2233
|
+
}
|
|
2234
|
+
}
|
|
2235
|
+
function scheduleAccount(accountId) {
|
|
2236
|
+
clearAccountSchedule(accountId);
|
|
2237
|
+
if (!getAccount(accountId)) return;
|
|
2238
|
+
const ms = getSyncIntervalMinutes() * 60 * 1e3;
|
|
2239
|
+
const timer = setInterval(() => {
|
|
2240
|
+
syncAccount(accountId);
|
|
2241
|
+
}, ms);
|
|
2242
|
+
timers.set(accountId, timer);
|
|
2243
|
+
}
|
|
2244
|
+
function clearAccountSchedule(accountId) {
|
|
2245
|
+
const t = timers.get(accountId);
|
|
2246
|
+
if (t) clearInterval(t);
|
|
2247
|
+
timers.delete(accountId);
|
|
2248
|
+
}
|
|
2249
|
+
function rescheduleAll() {
|
|
2250
|
+
for (const id of [...timers.keys()]) clearAccountSchedule(id);
|
|
2251
|
+
for (const a of listAccounts()) scheduleAccount(a.id);
|
|
2252
|
+
}
|
|
2253
|
+
function stopAllSchedules() {
|
|
2254
|
+
for (const id of [...timers.keys()]) clearAccountSchedule(id);
|
|
2255
|
+
}
|
|
2256
|
+
// src/core/cnWorkdays.ts
|
|
2257
|
+
dayjs.extend(isoWeek);
|
|
2258
|
+
const memory = /* @__PURE__ */ new Map();
|
|
2259
|
+
const inflight = /* @__PURE__ */ new Map();
|
|
2260
|
+
const CACHE_MAX_AGE_MS = 2592e6;
|
|
2261
|
+
function cachePath(year) {
|
|
2262
|
+
const dir = holidayCacheDir();
|
|
2263
|
+
mkdirSync(dir, { recursive: true });
|
|
2264
|
+
return join(dir, `${year}.json`);
|
|
2265
|
+
}
|
|
2266
|
+
function parseTimor(json) {
|
|
2267
|
+
if (json.code !== 0 || !json.holiday || typeof json.holiday !== "object") return null;
|
|
2268
|
+
const holidays = [];
|
|
2269
|
+
const makeupWorkdays = [];
|
|
2270
|
+
for (const item of Object.values(json.holiday)) {
|
|
2271
|
+
const date = (item.date || "").trim();
|
|
2272
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) continue;
|
|
2273
|
+
if (item.holiday) holidays.push(date);
|
|
2274
|
+
else makeupWorkdays.push(date);
|
|
2275
|
+
}
|
|
2276
|
+
if (holidays.length === 0 && makeupWorkdays.length === 0) return null;
|
|
2277
|
+
return {
|
|
2278
|
+
holidays,
|
|
2279
|
+
makeupWorkdays,
|
|
2280
|
+
source: "api"
|
|
2281
|
+
};
|
|
2282
|
+
}
|
|
2283
|
+
function readDiskCache(year) {
|
|
2284
|
+
const path = cachePath(year);
|
|
2285
|
+
if (!existsSync(path)) return null;
|
|
2286
|
+
try {
|
|
2287
|
+
const raw = JSON.parse(readFileSync(path, "utf8"));
|
|
2288
|
+
if (!Array.isArray(raw.holidays) || !Array.isArray(raw.makeupWorkdays)) return null;
|
|
2289
|
+
return {
|
|
2290
|
+
days: {
|
|
2291
|
+
holidays: raw.holidays,
|
|
2292
|
+
makeupWorkdays: raw.makeupWorkdays,
|
|
2293
|
+
source: "cache"
|
|
2294
|
+
},
|
|
2295
|
+
mtimeMs: statSync(path).mtimeMs
|
|
2296
|
+
};
|
|
2297
|
+
} catch {
|
|
2298
|
+
return null;
|
|
2299
|
+
}
|
|
2300
|
+
}
|
|
2301
|
+
function writeDiskCache(year, days) {
|
|
2302
|
+
writeFileSync(cachePath(year), JSON.stringify({
|
|
2303
|
+
holidays: days.holidays,
|
|
2304
|
+
makeupWorkdays: days.makeupWorkdays
|
|
2305
|
+
}, null, 2), "utf8");
|
|
2306
|
+
}
|
|
2307
|
+
function weekdayFallback(year) {
|
|
2308
|
+
return {
|
|
2309
|
+
holidays: [],
|
|
2310
|
+
makeupWorkdays: [],
|
|
2311
|
+
source: "fallback"
|
|
2312
|
+
};
|
|
2313
|
+
}
|
|
2314
|
+
async function fetchYear(year) {
|
|
2315
|
+
if (memory.has(year)) return memory.get(year);
|
|
2316
|
+
const cached = readDiskCache(year);
|
|
2317
|
+
if (cached && Date.now() - cached.mtimeMs < CACHE_MAX_AGE_MS) {
|
|
2318
|
+
memory.set(year, cached.days);
|
|
2319
|
+
return cached.days;
|
|
2320
|
+
}
|
|
2321
|
+
if (inflight.has(year)) return inflight.get(year);
|
|
2322
|
+
const task = (async () => {
|
|
2323
|
+
try {
|
|
2324
|
+
const res = await fetch(`https://timor.tech/api/holiday/year/${year}/`);
|
|
2325
|
+
if (!res.ok) throw new Error(`timor ${res.status}`);
|
|
2326
|
+
const parsed = parseTimor(await res.json());
|
|
2327
|
+
if (!parsed) throw new Error("timor parse failed");
|
|
2328
|
+
writeDiskCache(year, parsed);
|
|
2329
|
+
memory.set(year, parsed);
|
|
2330
|
+
return parsed;
|
|
2331
|
+
} catch {
|
|
2332
|
+
if (cached) {
|
|
2333
|
+
memory.set(year, cached.days);
|
|
2334
|
+
return cached.days;
|
|
2335
|
+
}
|
|
2336
|
+
const fb = weekdayFallback(year);
|
|
2337
|
+
memory.set(year, fb);
|
|
2338
|
+
return fb;
|
|
2339
|
+
} finally {
|
|
2340
|
+
inflight.delete(year);
|
|
2341
|
+
}
|
|
2342
|
+
})();
|
|
2343
|
+
inflight.set(year, task);
|
|
2344
|
+
return task;
|
|
2345
|
+
}
|
|
2346
|
+
function isWorkday(d, yearDays) {
|
|
2347
|
+
const key = d.format("YYYY-MM-DD");
|
|
2348
|
+
if (yearDays.holidays.includes(key)) return false;
|
|
2349
|
+
if (yearDays.makeupWorkdays.includes(key)) return true;
|
|
2350
|
+
const dow = d.day();
|
|
2351
|
+
return dow >= 1 && dow <= 5;
|
|
2352
|
+
}
|
|
2353
|
+
async function loadYears(from, to) {
|
|
2354
|
+
const years = /* @__PURE__ */ new Set();
|
|
2355
|
+
for (let cur = from; !cur.isAfter(to, "day"); cur = cur.add(1, "day")) years.add(cur.year());
|
|
2356
|
+
const byYear = /* @__PURE__ */ new Map();
|
|
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);
|
|
2362
|
+
let count = 0;
|
|
2363
|
+
for (let cur = from; !cur.isAfter(to, "day"); cur = cur.add(1, "day")) if (isWorkday(cur, byYear.get(cur.year()))) count++;
|
|
2364
|
+
return count;
|
|
2365
|
+
}
|
|
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;
|
|
2391
|
+
const d = dayjs(date || dayjs().format("YYYY-MM-DD"));
|
|
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
|
+
};
|
|
2417
|
+
}
|
|
2418
|
+
// src/core/reportRange.ts
|
|
2419
|
+
dayjs.extend(isoWeek);
|
|
2420
|
+
function rangeFor(kind, date, from, to) {
|
|
2421
|
+
if (kind === "custom") {
|
|
2422
|
+
if (!from || !to) throw new Error("自定义区间需提供起止日期");
|
|
2423
|
+
return {
|
|
2424
|
+
from: `${from}T00:00:00.000Z`,
|
|
2425
|
+
to: `${to}T23:59:59.999Z`,
|
|
2426
|
+
title: `自定义汇报 ${from} ~ ${to}`,
|
|
2427
|
+
fileName: `custom-${from}_${to}.md`,
|
|
2428
|
+
period: `${from} ~ ${to}`,
|
|
2429
|
+
kindLabel: "自定义汇报"
|
|
2430
|
+
};
|
|
2431
|
+
}
|
|
2432
|
+
const d = dayjs(date || dayjs().format("YYYY-MM-DD"));
|
|
2433
|
+
if (kind === "day") {
|
|
2434
|
+
const day = d.format("YYYY-MM-DD");
|
|
2435
|
+
return {
|
|
2436
|
+
from: `${day}T00:00:00.000Z`,
|
|
2437
|
+
to: `${day}T23:59:59.999Z`,
|
|
2438
|
+
title: `日报 ${day}`,
|
|
2439
|
+
fileName: `day-${day}.md`,
|
|
2440
|
+
period: day,
|
|
2441
|
+
kindLabel: "日报"
|
|
2442
|
+
};
|
|
2443
|
+
}
|
|
2444
|
+
if (kind === "week") {
|
|
2445
|
+
const start = d.startOf("isoWeek");
|
|
2446
|
+
const end = d.endOf("isoWeek");
|
|
2447
|
+
const week = d.isoWeek();
|
|
2448
|
+
const year = d.isoWeekYear();
|
|
2449
|
+
const label = `${year}-W${String(week).padStart(2, "0")}(${start.format("MM-DD")} ~ ${end.format("MM-DD")})`;
|
|
2450
|
+
return {
|
|
2451
|
+
from: start.toISOString(),
|
|
2452
|
+
to: end.toISOString(),
|
|
2453
|
+
title: `周报 ${label}`,
|
|
2454
|
+
fileName: `week-${year}-W${String(week).padStart(2, "0")}.md`,
|
|
2455
|
+
period: label,
|
|
2456
|
+
kindLabel: "周报"
|
|
2457
|
+
};
|
|
2458
|
+
}
|
|
2459
|
+
const start = d.startOf("month");
|
|
2460
|
+
const end = d.endOf("month");
|
|
2461
|
+
const ym = d.format("YYYY-MM");
|
|
2462
|
+
return {
|
|
2463
|
+
from: start.toISOString(),
|
|
2464
|
+
to: end.toISOString(),
|
|
2465
|
+
title: `月报 ${ym}`,
|
|
2466
|
+
fileName: `month-${ym}.md`,
|
|
2467
|
+
period: ym,
|
|
2468
|
+
kindLabel: "月报"
|
|
2469
|
+
};
|
|
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
|
+
}
|
|
2621
|
+
// src/core/reportMarkdown.ts
|
|
2622
|
+
const WEEKDAY_CN = [
|
|
2623
|
+
"日",
|
|
2624
|
+
"一",
|
|
2625
|
+
"二",
|
|
2626
|
+
"三",
|
|
2627
|
+
"四",
|
|
2628
|
+
"五",
|
|
2629
|
+
"六"
|
|
2630
|
+
];
|
|
2631
|
+
function buildReportHeader(title, accountName, opts) {
|
|
2632
|
+
const lines = [
|
|
2633
|
+
`# ${title}`,
|
|
2634
|
+
"",
|
|
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");
|
|
2649
|
+
}
|
|
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) {
|
|
2661
|
+
const byRepo = /* @__PURE__ */ new Map();
|
|
2662
|
+
for (const c of commits) {
|
|
2663
|
+
if (!byRepo.has(c.repoName)) byRepo.set(c.repoName, []);
|
|
2664
|
+
byRepo.get(c.repoName).push(c);
|
|
2665
|
+
}
|
|
2666
|
+
return Array.from(byRepo.entries()).sort((a, b) => a[0].localeCompare(b[0]));
|
|
2667
|
+
}
|
|
2668
|
+
/**
|
|
2669
|
+
* 按仓库列出完整提交说明
|
|
2670
|
+
*/
|
|
2671
|
+
function buildCommitDetailsMarkdown(commits) {
|
|
2672
|
+
const lines = [];
|
|
2673
|
+
for (const [repo, list] of groupByRepo(commits)) {
|
|
2674
|
+
lines.push(`### ${repo}`, "");
|
|
2675
|
+
for (const c of list) pushCommitDetail(lines, c);
|
|
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}`, "");
|
|
2687
|
+
for (const c of list) {
|
|
2688
|
+
const time = dayjs(c.committedAt).format("MM-DD HH:mm");
|
|
2689
|
+
lines.push(`- [${time}] ${appendStatsSuffix(commitTitleLine(c), c)}`);
|
|
2690
|
+
}
|
|
2691
|
+
lines.push("");
|
|
2692
|
+
}
|
|
2693
|
+
return lines.join("\n").trimEnd();
|
|
2694
|
+
}
|
|
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();
|
|
2714
|
+
for (const c of commits) {
|
|
2715
|
+
const day = dayjs(c.committedAt).format("YYYY-MM-DD");
|
|
2716
|
+
if (!byDay.has(day)) byDay.set(day, []);
|
|
2717
|
+
byDay.get(day).push(c);
|
|
2718
|
+
}
|
|
2719
|
+
const days = Array.from(byDay.keys()).sort();
|
|
2720
|
+
const lines = [];
|
|
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("");
|
|
2790
|
+
}
|
|
2791
|
+
}
|
|
2792
|
+
if (noTicket.length) {
|
|
2793
|
+
lines.push("### 无工单(按仓库)", "");
|
|
2794
|
+
lines.push(buildCommitDetailsMarkdown(noTicket));
|
|
2795
|
+
lines.push("");
|
|
2796
|
+
}
|
|
2797
|
+
if (!units.length && !noTicket.length) return "(无提交)";
|
|
2798
|
+
return lines.join("\n").trimEnd();
|
|
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
|
+
}
|
|
2831
|
+
// src/core/reports.ts
|
|
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) {
|
|
2851
|
+
const lines = [];
|
|
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
|
+
}));
|
|
2859
|
+
lines.push("## 工作摘要(草稿)");
|
|
2860
|
+
lines.push("");
|
|
2861
|
+
lines.push("> 以下为过滤后的提交材料,可据此改写成汇报用语。");
|
|
2862
|
+
lines.push("");
|
|
2863
|
+
lines.push(sectionTitleFor(opts.groupBy));
|
|
2864
|
+
lines.push("");
|
|
2865
|
+
lines.push(buildGroupedCommitMarkdown(opts.kept, opts.groupBy));
|
|
2866
|
+
lines.push("");
|
|
2867
|
+
if (opts.attendanceMarkdown) lines.push(opts.attendanceMarkdown);
|
|
2868
|
+
return lines.join("\n");
|
|
2869
|
+
}
|
|
2870
|
+
async function generateReport(req, exportFile = true) {
|
|
2871
|
+
const account = getAccount(req.accountId);
|
|
2872
|
+
if (!account) throw new Error("账号不存在");
|
|
2873
|
+
const { from, to, title, fileName } = rangeFor(req.kind, req.date, req.from, req.to);
|
|
2874
|
+
const { items } = db.queryCommits({
|
|
2875
|
+
accountId: req.accountId,
|
|
2876
|
+
from,
|
|
2877
|
+
to,
|
|
2878
|
+
limit: 5e3
|
|
2879
|
+
});
|
|
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
|
+
});
|
|
2906
|
+
let filePath;
|
|
2907
|
+
if (exportFile) {
|
|
2908
|
+
const dir = join(reportsDir(), req.accountId);
|
|
2909
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
2910
|
+
filePath = join(dir, fileName);
|
|
2911
|
+
writeFileSync(filePath, markdown, "utf8");
|
|
2912
|
+
}
|
|
2913
|
+
return {
|
|
2914
|
+
title,
|
|
2915
|
+
markdown,
|
|
2916
|
+
filePath,
|
|
2917
|
+
commitCount: filtered.kept.length,
|
|
2918
|
+
rawCommitCount: filtered.rawCount,
|
|
2919
|
+
excluded: filtered.excluded,
|
|
2920
|
+
statutoryWorkdays
|
|
2921
|
+
};
|
|
2922
|
+
}
|
|
2923
|
+
// src/tools/resolveAccount.ts
|
|
2924
|
+
function resolveAccountId(accountId) {
|
|
2925
|
+
const accounts = listAccounts();
|
|
2926
|
+
if (accountId?.trim()) {
|
|
2927
|
+
const found = accounts.find((a) => a.id === accountId.trim());
|
|
2928
|
+
if (!found) throw new Error(`账号不存在:${accountId}`);
|
|
2929
|
+
return found.id;
|
|
2930
|
+
}
|
|
2931
|
+
const activeId = getActiveAccountId();
|
|
2932
|
+
if (activeId && accounts.some((a) => a.id === activeId)) return activeId;
|
|
2933
|
+
if (accounts.length === 1) return accounts[0].id;
|
|
2934
|
+
if (accounts.length === 0) throw new Error(`本地无账号。请先调用 upsert_account(mode=remote 或 local)。数据目录:${getDataRoot()}`);
|
|
2935
|
+
throw new Error("存在多个账号,请先调用 list_accounts 后传入 accountId");
|
|
2936
|
+
}
|
|
2937
|
+
function accountSummary() {
|
|
2938
|
+
const accounts = listAccounts();
|
|
2939
|
+
const activeAccountId = getActiveAccountId();
|
|
2940
|
+
return accounts.map((a) => ({
|
|
2941
|
+
id: a.id,
|
|
2942
|
+
name: a.name,
|
|
2943
|
+
mode: a.mode,
|
|
2944
|
+
provider: a.provider,
|
|
2945
|
+
edition: a.edition,
|
|
2946
|
+
organizationId: a.organizationId,
|
|
2947
|
+
apiBaseUrl: a.apiBaseUrl,
|
|
2948
|
+
localRoots: a.localRoots,
|
|
2949
|
+
authorFilters: a.authorFilters,
|
|
2950
|
+
defaultBranch: a.defaultBranch,
|
|
2951
|
+
watchedRepoCount: a.watchedRepoIds.length,
|
|
2952
|
+
active: a.id === activeAccountId
|
|
2953
|
+
}));
|
|
2954
|
+
}
|
|
2955
|
+
// src/tools/registerTools.ts
|
|
2956
|
+
function textOut(text) {
|
|
2957
|
+
return text;
|
|
2958
|
+
}
|
|
2959
|
+
/**
|
|
2960
|
+
* 注册 commit-journal 相关 agent 工具
|
|
2961
|
+
*/
|
|
2962
|
+
function registerTools(ctx) {
|
|
2963
|
+
ctx.tools.register(defineTool({
|
|
2964
|
+
name: "list_accounts",
|
|
2965
|
+
description: "列出 Commit Journal 账号(id、名称、mode=local|remote、provider、localRoots、是否当前活跃)。总结工作前可先调用以确认 accountId。",
|
|
2966
|
+
parameters: {},
|
|
2967
|
+
output: {
|
|
2968
|
+
schema: { type: "string" },
|
|
2969
|
+
render: (_args, value) => [{
|
|
2970
|
+
type: "text",
|
|
2971
|
+
text: String(value)
|
|
2972
|
+
}]
|
|
2973
|
+
},
|
|
2974
|
+
async execute() {
|
|
2975
|
+
const list = accountSummary();
|
|
2976
|
+
if (list.length === 0) return textOut([
|
|
2977
|
+
"本地无账号。",
|
|
2978
|
+
`数据目录:${getDataRoot()}`,
|
|
2979
|
+
"请先调用 upsert_account。"
|
|
2980
|
+
].join("\n"));
|
|
2981
|
+
return textOut(JSON.stringify({
|
|
2982
|
+
accounts: list,
|
|
2983
|
+
dataRoot: getDataRoot()
|
|
2984
|
+
}, null, 2));
|
|
2985
|
+
}
|
|
2986
|
+
}));
|
|
2987
|
+
ctx.tools.register(defineTool({
|
|
2988
|
+
name: "upsert_account",
|
|
2989
|
+
description: "创建或更新账号。mode=remote(默认)按 provider 用 PAT 拉提交(codeup / gitlab / github);mode=local 扫描 localRoots 下的本机 git 仓(无需 token)。创建时不要传 id;更新时传 id。",
|
|
2990
|
+
parameters: {
|
|
2991
|
+
id: {
|
|
2992
|
+
type: "string",
|
|
2993
|
+
description: "已有账号 id;省略则新建"
|
|
2994
|
+
},
|
|
2995
|
+
name: {
|
|
2996
|
+
type: "string",
|
|
2997
|
+
required: true,
|
|
2998
|
+
description: "账号显示名"
|
|
2999
|
+
},
|
|
3000
|
+
mode: {
|
|
3001
|
+
type: "string",
|
|
3002
|
+
description: "remote | local;默认 remote"
|
|
3003
|
+
},
|
|
3004
|
+
provider: {
|
|
3005
|
+
type: "string",
|
|
3006
|
+
description: "remote 时 codeup | gitlab | github;local 固定 local"
|
|
3007
|
+
},
|
|
3008
|
+
edition: {
|
|
3009
|
+
type: "string",
|
|
3010
|
+
description: "central | region(仅 Codeup)"
|
|
3011
|
+
},
|
|
3012
|
+
organizationId: {
|
|
3013
|
+
type: "string",
|
|
3014
|
+
description: "Codeup 中心版 organizationId;GitHub 可选 org login;GitLab 可选 group path/id"
|
|
3015
|
+
},
|
|
3016
|
+
apiBaseUrl: {
|
|
3017
|
+
type: "string",
|
|
3018
|
+
description: "Codeup Region API Base;自建 GitLab / GHE 主机(可省略 /api/v4 或 /api/v3);gitlab.com / github.com 可留空"
|
|
3019
|
+
},
|
|
3020
|
+
insecureSsl: {
|
|
3021
|
+
type: "boolean",
|
|
3022
|
+
description: "跳过 TLS 证书校验(公司代理 / 自签证书)。也可用环境变量 DSH_COMMIT_JOURNAL_TLS_INSECURE=1"
|
|
3023
|
+
},
|
|
3024
|
+
localRoots: {
|
|
3025
|
+
type: "array",
|
|
3026
|
+
items: { type: "string" },
|
|
3027
|
+
description: "local 模式扫描根目录列表"
|
|
3028
|
+
},
|
|
3029
|
+
token: {
|
|
3030
|
+
type: "string",
|
|
3031
|
+
description: "remote PAT;更新时可省略表示不改;local 不需要"
|
|
3032
|
+
},
|
|
3033
|
+
authorFilters: {
|
|
3034
|
+
type: "array",
|
|
3035
|
+
items: { type: "string" },
|
|
3036
|
+
description: "作者邮箱/姓名过滤"
|
|
3037
|
+
},
|
|
3038
|
+
defaultBranch: { type: "string" },
|
|
3039
|
+
setActive: {
|
|
3040
|
+
type: "boolean",
|
|
3041
|
+
description: "设为当前活跃账号"
|
|
3042
|
+
},
|
|
3043
|
+
test: {
|
|
3044
|
+
type: "boolean",
|
|
3045
|
+
description: "保存前测试连接/扫描,默认 true"
|
|
3046
|
+
}
|
|
3047
|
+
},
|
|
3048
|
+
output: {
|
|
3049
|
+
schema: { type: "string" },
|
|
3050
|
+
render: (_a, v) => [{
|
|
3051
|
+
type: "text",
|
|
3052
|
+
text: String(v)
|
|
3053
|
+
}]
|
|
3054
|
+
},
|
|
3055
|
+
async execute(args) {
|
|
3056
|
+
const mode = args.mode === "local" ? "local" : "remote";
|
|
3057
|
+
const provider = mode === "local" ? "local" : args.provider || "codeup";
|
|
3058
|
+
const token = args.token?.trim();
|
|
3059
|
+
const localRoots = Array.isArray(args.localRoots) ? args.localRoots.map(String) : void 0;
|
|
3060
|
+
let account;
|
|
3061
|
+
if (args.id) account = updateAccount({
|
|
3062
|
+
id: String(args.id),
|
|
3063
|
+
name: args.name,
|
|
3064
|
+
mode,
|
|
3065
|
+
provider,
|
|
3066
|
+
edition: args.edition,
|
|
3067
|
+
organizationId: args.organizationId,
|
|
3068
|
+
apiBaseUrl: args.apiBaseUrl,
|
|
3069
|
+
insecureSsl: args.insecureSsl,
|
|
3070
|
+
localRoots,
|
|
3071
|
+
token,
|
|
3072
|
+
authorFilters: args.authorFilters,
|
|
3073
|
+
defaultBranch: args.defaultBranch
|
|
3074
|
+
});
|
|
3075
|
+
else {
|
|
3076
|
+
if (mode === "remote" && !token) throw new Error("远程账号新建必须提供 token");
|
|
3077
|
+
if (mode === "local" && !(localRoots && localRoots.length)) throw new Error("本地账号新建必须提供 localRoots");
|
|
3078
|
+
account = createAccount({
|
|
3079
|
+
name: args.name,
|
|
3080
|
+
mode,
|
|
3081
|
+
provider,
|
|
3082
|
+
edition: args.edition || "central",
|
|
3083
|
+
organizationId: args.organizationId,
|
|
3084
|
+
apiBaseUrl: args.apiBaseUrl,
|
|
3085
|
+
insecureSsl: args.insecureSsl,
|
|
3086
|
+
localRoots,
|
|
3087
|
+
token,
|
|
3088
|
+
authorFilters: args.authorFilters || [],
|
|
3089
|
+
defaultBranch: args.defaultBranch
|
|
3090
|
+
});
|
|
3091
|
+
}
|
|
3092
|
+
if (args.setActive !== false) setActiveAccountId(account.id);
|
|
3093
|
+
let testResult;
|
|
3094
|
+
if (args.test !== false) {
|
|
3095
|
+
const t = account.mode === "local" ? "" : getAccountToken(account.id);
|
|
3096
|
+
testResult = await getProvider(account).testConnection(account, t);
|
|
3097
|
+
}
|
|
3098
|
+
return textOut(JSON.stringify({
|
|
3099
|
+
ok: true,
|
|
3100
|
+
account: {
|
|
3101
|
+
id: account.id,
|
|
3102
|
+
name: account.name,
|
|
3103
|
+
mode: account.mode,
|
|
3104
|
+
provider: account.provider,
|
|
3105
|
+
edition: account.edition,
|
|
3106
|
+
localRoots: account.localRoots
|
|
3107
|
+
},
|
|
3108
|
+
test: testResult
|
|
3109
|
+
}, null, 2));
|
|
3110
|
+
}
|
|
3111
|
+
}));
|
|
3112
|
+
ctx.tools.register(defineTool({
|
|
3113
|
+
name: "remove_account",
|
|
3114
|
+
description: "删除本地账号及其提交缓存(不会删除远端仓库)。",
|
|
3115
|
+
parameters: { accountId: {
|
|
3116
|
+
type: "string",
|
|
3117
|
+
required: true
|
|
3118
|
+
} },
|
|
3119
|
+
output: {
|
|
3120
|
+
schema: { type: "string" },
|
|
3121
|
+
render: (_a, v) => [{
|
|
3122
|
+
type: "text",
|
|
3123
|
+
text: String(v)
|
|
3124
|
+
}]
|
|
3125
|
+
},
|
|
3126
|
+
async execute(args) {
|
|
3127
|
+
deleteAccount(String(args.accountId));
|
|
3128
|
+
return textOut(JSON.stringify({
|
|
3129
|
+
ok: true,
|
|
3130
|
+
removed: args.accountId
|
|
3131
|
+
}));
|
|
3132
|
+
}
|
|
3133
|
+
}));
|
|
3134
|
+
ctx.tools.register(defineTool({
|
|
3135
|
+
name: "sync_commits",
|
|
3136
|
+
description: "增量同步指定账号的提交到本地缓存。remote=Codeup/GitLab/GitHub API;local=扫描根目录下 git log。可先 upsert_account。",
|
|
3137
|
+
parameters: {
|
|
3138
|
+
accountId: { type: "string" },
|
|
3139
|
+
repoIds: {
|
|
3140
|
+
type: "array",
|
|
3141
|
+
items: { type: "string" },
|
|
3142
|
+
description: "可选,限制仓库"
|
|
3143
|
+
}
|
|
3144
|
+
},
|
|
3145
|
+
output: {
|
|
3146
|
+
schema: { type: "string" },
|
|
3147
|
+
render: (_a, v) => [{
|
|
3148
|
+
type: "text",
|
|
3149
|
+
text: String(v)
|
|
3150
|
+
}]
|
|
3151
|
+
},
|
|
3152
|
+
async execute(args) {
|
|
3153
|
+
const result = await syncAccount(resolveAccountId(args.accountId), args.repoIds);
|
|
3154
|
+
return textOut(JSON.stringify(result, null, 2));
|
|
3155
|
+
}
|
|
3156
|
+
}));
|
|
3157
|
+
ctx.tools.register(defineTool({
|
|
3158
|
+
name: "list_repos",
|
|
3159
|
+
description: "列出某账号下已有提交记录的仓库(或缓存的全部仓库)。refresh=true 时 remote 拉 API / local 重扫根目录。",
|
|
3160
|
+
parameters: {
|
|
3161
|
+
accountId: { type: "string" },
|
|
3162
|
+
withCommitsOnly: {
|
|
3163
|
+
type: "boolean",
|
|
3164
|
+
description: "默认 true,仅返回已有提交的仓库"
|
|
3165
|
+
},
|
|
3166
|
+
refresh: {
|
|
3167
|
+
type: "boolean",
|
|
3168
|
+
description: "是否先刷新仓库列表(remote API 或 local 扫描)"
|
|
3169
|
+
}
|
|
3170
|
+
},
|
|
3171
|
+
output: {
|
|
3172
|
+
schema: { type: "string" },
|
|
3173
|
+
render: (_a, v) => [{
|
|
3174
|
+
type: "text",
|
|
3175
|
+
text: String(v)
|
|
3176
|
+
}]
|
|
3177
|
+
},
|
|
3178
|
+
async execute(args) {
|
|
3179
|
+
const id = resolveAccountId(args.accountId);
|
|
3180
|
+
if (args.refresh) {
|
|
3181
|
+
const account = getAccount(id);
|
|
3182
|
+
const token = getAccountToken(id);
|
|
3183
|
+
const repos = await getProvider(account).listRepos(account, token);
|
|
3184
|
+
db.upsertRepos(id, repos);
|
|
3185
|
+
}
|
|
3186
|
+
const list = args.withCommitsOnly === false ? db.listRepos(id) : db.listReposWithCommits(id);
|
|
3187
|
+
return textOut(JSON.stringify({
|
|
3188
|
+
accountId: id,
|
|
3189
|
+
repos: list.map((r) => ({
|
|
3190
|
+
id: r.id,
|
|
3191
|
+
name: r.name,
|
|
3192
|
+
fullName: r.fullName,
|
|
3193
|
+
webUrl: r.webUrl,
|
|
3194
|
+
defaultBranch: r.defaultBranch
|
|
3195
|
+
}))
|
|
3196
|
+
}, null, 2));
|
|
3197
|
+
}
|
|
3198
|
+
}));
|
|
3199
|
+
ctx.tools.register(defineTool({
|
|
3200
|
+
name: "query_commits",
|
|
3201
|
+
description: "按日期/仓库/关键词查询本地已同步的提交。",
|
|
3202
|
+
parameters: {
|
|
3203
|
+
accountId: { type: "string" },
|
|
3204
|
+
repoId: { type: "string" },
|
|
3205
|
+
from: {
|
|
3206
|
+
type: "string",
|
|
3207
|
+
description: "YYYY-MM-DD 或 ISO"
|
|
3208
|
+
},
|
|
3209
|
+
to: {
|
|
3210
|
+
type: "string",
|
|
3211
|
+
description: "YYYY-MM-DD 或 ISO"
|
|
3212
|
+
},
|
|
3213
|
+
keyword: { type: "string" },
|
|
3214
|
+
limit: { type: "number" },
|
|
3215
|
+
subjectOnly: {
|
|
3216
|
+
type: "boolean",
|
|
3217
|
+
description: "仅提交首行"
|
|
3218
|
+
}
|
|
3219
|
+
},
|
|
3220
|
+
output: {
|
|
3221
|
+
schema: { type: "string" },
|
|
3222
|
+
render: (_a, v) => [{
|
|
3223
|
+
type: "text",
|
|
3224
|
+
text: String(v)
|
|
3225
|
+
}]
|
|
3226
|
+
},
|
|
3227
|
+
async execute(args) {
|
|
3228
|
+
const id = resolveAccountId(args.accountId);
|
|
3229
|
+
const account = getAccount(id);
|
|
3230
|
+
const { items, total } = db.queryCommits({
|
|
3231
|
+
accountId: id,
|
|
3232
|
+
repoId: args.repoId,
|
|
3233
|
+
from: args.from,
|
|
3234
|
+
to: args.to,
|
|
3235
|
+
keyword: args.keyword,
|
|
3236
|
+
limit: args.limit ?? 200
|
|
3237
|
+
});
|
|
3238
|
+
const body = args.subjectOnly ? buildCommitSubjectListMarkdown(items) : buildCommitDetailsMarkdown(items);
|
|
3239
|
+
return textOut([
|
|
3240
|
+
`# 提交查询结果`,
|
|
3241
|
+
"",
|
|
3242
|
+
`- 账号:${account.name}`,
|
|
3243
|
+
`- 返回:${items.length} / 共 ${total} 条`,
|
|
3244
|
+
`- 生成时间:${dayjs().format("YYYY-MM-DD HH:mm:ss")}`,
|
|
3245
|
+
"",
|
|
3246
|
+
body || "(无提交)"
|
|
3247
|
+
].join("\n"));
|
|
3248
|
+
}
|
|
3249
|
+
}));
|
|
3250
|
+
ctx.tools.register(defineTool({
|
|
3251
|
+
name: "get_period_report",
|
|
3252
|
+
description: "按日/周/月/自定义区间生成报告 Markdown 材料。默认按仓库分组、排除 merge;周/月含法定工作日出勤对照。groupBy=ticket 时按工单归组(无工单仍按仓库)。",
|
|
3253
|
+
parameters: {
|
|
3254
|
+
accountId: { type: "string" },
|
|
3255
|
+
kind: {
|
|
3256
|
+
type: "string",
|
|
3257
|
+
required: true,
|
|
3258
|
+
description: "day | week | month | custom"
|
|
3259
|
+
},
|
|
3260
|
+
date: {
|
|
3261
|
+
type: "string",
|
|
3262
|
+
description: "锚点日期 YYYY-MM-DD"
|
|
3263
|
+
},
|
|
3264
|
+
from: {
|
|
3265
|
+
type: "string",
|
|
3266
|
+
description: "custom 起始"
|
|
3267
|
+
},
|
|
3268
|
+
to: {
|
|
3269
|
+
type: "string",
|
|
3270
|
+
description: "custom 结束"
|
|
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
|
+
},
|
|
3284
|
+
exportFile: {
|
|
3285
|
+
type: "boolean",
|
|
3286
|
+
description: "是否落盘,默认 true"
|
|
3287
|
+
}
|
|
3288
|
+
},
|
|
3289
|
+
output: {
|
|
3290
|
+
schema: { type: "string" },
|
|
3291
|
+
render: (_a, v) => [{
|
|
3292
|
+
type: "text",
|
|
3293
|
+
text: String(v)
|
|
3294
|
+
}]
|
|
3295
|
+
},
|
|
3296
|
+
async execute(args) {
|
|
3297
|
+
const id = resolveAccountId(args.accountId);
|
|
3298
|
+
const groupBy = args.groupBy;
|
|
3299
|
+
const result = await generateReport({
|
|
3300
|
+
accountId: id,
|
|
3301
|
+
kind: args.kind,
|
|
3302
|
+
date: args.date,
|
|
3303
|
+
from: args.from,
|
|
3304
|
+
to: args.to,
|
|
3305
|
+
groupBy,
|
|
3306
|
+
excludeMerge: args.excludeMerge,
|
|
3307
|
+
includeAttendance: args.includeAttendance
|
|
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) : [];
|
|
3315
|
+
return textOut([
|
|
3316
|
+
result.markdown,
|
|
3317
|
+
"",
|
|
3318
|
+
result.filePath ? `已落盘:${result.filePath}` : "",
|
|
3319
|
+
result.rawCommitCount != null && result.rawCommitCount !== result.commitCount ? `提交:原始 ${result.rawCommitCount} → 纳入 ${result.commitCount}` + (exclParts.length ? `(排除 ${exclParts.join(" / ")})` : "") : "",
|
|
3320
|
+
result.statutoryWorkdays != null ? `法定工作日:${result.statutoryWorkdays} 天` : ""
|
|
3321
|
+
].filter(Boolean).join("\n"));
|
|
3322
|
+
}
|
|
3323
|
+
}));
|
|
3324
|
+
ctx.tools.register(defineTool({
|
|
3325
|
+
name: "get_activity_heatmap",
|
|
3326
|
+
description: "获取提交活跃热力图数据:按本地自然日聚合。可指定 year,或不传表示近一年。传 date 时返回该日提交明细。",
|
|
3327
|
+
parameters: {
|
|
3328
|
+
accountId: { type: "string" },
|
|
3329
|
+
year: {
|
|
3330
|
+
type: "number",
|
|
3331
|
+
description: "自然年;省略=近一年"
|
|
3332
|
+
},
|
|
3333
|
+
date: {
|
|
3334
|
+
type: "string",
|
|
3335
|
+
description: "YYYY-MM-DD,返回当日明细"
|
|
3336
|
+
}
|
|
3337
|
+
},
|
|
3338
|
+
output: {
|
|
3339
|
+
schema: { type: "string" },
|
|
3340
|
+
render: (_a, v) => [{
|
|
3341
|
+
type: "text",
|
|
3342
|
+
text: String(v)
|
|
3343
|
+
}]
|
|
3344
|
+
},
|
|
3345
|
+
async execute(args) {
|
|
3346
|
+
const id = resolveAccountId(args.accountId);
|
|
3347
|
+
if (args.date) {
|
|
3348
|
+
const items = db.listDayCommits(id, args.date);
|
|
3349
|
+
return textOut(JSON.stringify({
|
|
3350
|
+
accountId: id,
|
|
3351
|
+
date: args.date,
|
|
3352
|
+
count: items.length,
|
|
3353
|
+
commits: items.map((c) => ({
|
|
3354
|
+
time: c.committedAt,
|
|
3355
|
+
repo: c.repoName,
|
|
3356
|
+
title: c.title,
|
|
3357
|
+
sha: c.shortId,
|
|
3358
|
+
webUrl: c.webUrl,
|
|
3359
|
+
additions: c.additions,
|
|
3360
|
+
deletions: c.deletions,
|
|
3361
|
+
filesChanged: c.filesChanged
|
|
3362
|
+
}))
|
|
3363
|
+
}, null, 2));
|
|
3364
|
+
}
|
|
3365
|
+
const data = db.getActivity(id, args.year);
|
|
3366
|
+
return textOut(JSON.stringify({
|
|
3367
|
+
accountId: id,
|
|
3368
|
+
...data
|
|
3369
|
+
}, null, 2));
|
|
3370
|
+
}
|
|
3371
|
+
}));
|
|
3372
|
+
ctx.tools.register(defineTool({
|
|
3373
|
+
name: "update_journal_settings",
|
|
3374
|
+
description: "更新本地同步/导出/热力图 UI 端口与报告设置(过滤、默认 groupBy)。",
|
|
3375
|
+
parameters: {
|
|
3376
|
+
exportsPath: { type: "string" },
|
|
3377
|
+
syncIntervalMinutes: { type: "number" },
|
|
3378
|
+
syncLookbackDays: { 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
|
+
}
|
|
3398
|
+
},
|
|
3399
|
+
output: {
|
|
3400
|
+
schema: { type: "string" },
|
|
3401
|
+
render: (_a, v) => [{
|
|
3402
|
+
type: "text",
|
|
3403
|
+
text: String(v)
|
|
3404
|
+
}]
|
|
3405
|
+
},
|
|
3406
|
+
async execute(args) {
|
|
3407
|
+
const next = updateSettings(args);
|
|
3408
|
+
return textOut(JSON.stringify({
|
|
3409
|
+
ok: true,
|
|
3410
|
+
settings: describeSettings(),
|
|
3411
|
+
saved: next
|
|
3412
|
+
}, null, 2));
|
|
3413
|
+
}
|
|
3414
|
+
}));
|
|
3415
|
+
}
|
|
3416
|
+
// src/ui/server.ts
|
|
3417
|
+
let server = null;
|
|
3418
|
+
let listenPort = null;
|
|
3419
|
+
function corsHeaders() {
|
|
3420
|
+
return {
|
|
3421
|
+
"Access-Control-Allow-Origin": "*",
|
|
3422
|
+
"Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
|
|
3423
|
+
"Access-Control-Allow-Headers": "Content-Type"
|
|
3424
|
+
};
|
|
3425
|
+
}
|
|
3426
|
+
function sendJson(res, status, body) {
|
|
3427
|
+
const raw = JSON.stringify(body);
|
|
3428
|
+
res.writeHead(status, {
|
|
3429
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
3430
|
+
...corsHeaders()
|
|
3431
|
+
});
|
|
3432
|
+
res.end(raw);
|
|
3433
|
+
}
|
|
3434
|
+
function readBody(req) {
|
|
3435
|
+
return new Promise((resolve, reject) => {
|
|
3436
|
+
const chunks = [];
|
|
3437
|
+
req.on("data", (c) => chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c)));
|
|
3438
|
+
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
|
3439
|
+
req.on("error", reject);
|
|
3440
|
+
});
|
|
3441
|
+
}
|
|
3442
|
+
async function readJson(req) {
|
|
3443
|
+
const raw = await readBody(req);
|
|
3444
|
+
if (!raw.trim()) return {};
|
|
3445
|
+
return JSON.parse(raw);
|
|
3446
|
+
}
|
|
3447
|
+
function accountPublic(a, activeId) {
|
|
3448
|
+
return {
|
|
3449
|
+
id: a.id,
|
|
3450
|
+
name: a.name,
|
|
3451
|
+
mode: a.mode,
|
|
3452
|
+
provider: a.provider,
|
|
3453
|
+
edition: a.edition,
|
|
3454
|
+
organizationId: a.organizationId,
|
|
3455
|
+
apiBaseUrl: a.apiBaseUrl,
|
|
3456
|
+
insecureSsl: Boolean(a.insecureSsl),
|
|
3457
|
+
localRoots: a.localRoots || [],
|
|
3458
|
+
authorFilters: a.authorFilters,
|
|
3459
|
+
defaultBranch: a.defaultBranch,
|
|
3460
|
+
watchedRepoIds: a.watchedRepoIds,
|
|
3461
|
+
repoBranches: a.repoBranches,
|
|
3462
|
+
createdAt: a.createdAt,
|
|
3463
|
+
updatedAt: a.updatedAt,
|
|
3464
|
+
active: a.id === activeId
|
|
3465
|
+
};
|
|
3466
|
+
}
|
|
3467
|
+
function matchRoute(pathname, pattern) {
|
|
3468
|
+
const pp = pattern.split("/").filter(Boolean);
|
|
3469
|
+
const ap = pathname.split("/").filter(Boolean);
|
|
3470
|
+
if (pp.length !== ap.length) return null;
|
|
3471
|
+
const params = {};
|
|
3472
|
+
for (let i = 0; i < pp.length; i++) if (pp[i].startsWith(":")) params[pp[i].slice(1)] = decodeURIComponent(ap[i]);
|
|
3473
|
+
else if (pp[i] !== ap[i]) return null;
|
|
3474
|
+
return params;
|
|
3475
|
+
}
|
|
3476
|
+
async function handler(req, res) {
|
|
3477
|
+
const url = new URL(req.url || "/", `http://127.0.0.1`);
|
|
3478
|
+
const method = req.method || "GET";
|
|
3479
|
+
if (method === "OPTIONS") {
|
|
3480
|
+
res.writeHead(204, corsHeaders());
|
|
3481
|
+
res.end();
|
|
3482
|
+
return;
|
|
3483
|
+
}
|
|
3484
|
+
try {
|
|
3485
|
+
if (method === "GET" && (url.pathname === "/" || url.pathname === "/api/health")) {
|
|
3486
|
+
sendJson(res, 200, {
|
|
3487
|
+
ok: true,
|
|
3488
|
+
port: listenPort,
|
|
3489
|
+
dataRoot: getDataRoot()
|
|
3490
|
+
});
|
|
3491
|
+
return;
|
|
3492
|
+
}
|
|
3493
|
+
if (method === "GET" && url.pathname === "/api/accounts") {
|
|
3494
|
+
const activeId = getActiveAccountId();
|
|
3495
|
+
sendJson(res, 200, {
|
|
3496
|
+
dataRoot: getDataRoot(),
|
|
3497
|
+
activeAccountId: activeId,
|
|
3498
|
+
accounts: listAccounts().map((a) => accountPublic(a, activeId))
|
|
3499
|
+
});
|
|
3500
|
+
return;
|
|
3501
|
+
}
|
|
3502
|
+
if (method === "POST" && url.pathname === "/api/accounts") {
|
|
3503
|
+
const body = await readJson(req);
|
|
3504
|
+
const mode = body.mode === "local" ? "local" : "remote";
|
|
3505
|
+
const account = createAccount({
|
|
3506
|
+
name: body.name,
|
|
3507
|
+
mode,
|
|
3508
|
+
provider: mode === "local" ? "local" : body.provider || "codeup",
|
|
3509
|
+
edition: body.edition || "central",
|
|
3510
|
+
organizationId: body.organizationId,
|
|
3511
|
+
apiBaseUrl: body.apiBaseUrl,
|
|
3512
|
+
insecureSsl: body.insecureSsl,
|
|
3513
|
+
localRoots: Array.isArray(body.localRoots) ? body.localRoots : typeof body.localRootsText === "string" ? String(body.localRootsText).split(/\r?\n/) : void 0,
|
|
3514
|
+
token: body.token,
|
|
3515
|
+
authorFilters: body.authorFilters || [],
|
|
3516
|
+
defaultBranch: body.defaultBranch,
|
|
3517
|
+
watchedRepoIds: body.watchedRepoIds,
|
|
3518
|
+
repoBranches: body.repoBranches
|
|
3519
|
+
});
|
|
3520
|
+
if (body.setActive !== false) setActiveAccountId(account.id);
|
|
3521
|
+
let test;
|
|
3522
|
+
if (body.test !== false) {
|
|
3523
|
+
const token = account.mode === "local" ? "" : getAccountToken(account.id);
|
|
3524
|
+
test = await getProvider(account).testConnection(account, token);
|
|
3525
|
+
}
|
|
3526
|
+
sendJson(res, 200, {
|
|
3527
|
+
account: accountPublic(account, getActiveAccountId()),
|
|
3528
|
+
test
|
|
3529
|
+
});
|
|
3530
|
+
return;
|
|
3531
|
+
}
|
|
3532
|
+
{
|
|
3533
|
+
const m = matchRoute(url.pathname, "/api/accounts/:id");
|
|
3534
|
+
if (m) {
|
|
3535
|
+
if (method === "PATCH" || method === "PUT") {
|
|
3536
|
+
const body = await readJson(req);
|
|
3537
|
+
sendJson(res, 200, { account: accountPublic(updateAccount({
|
|
3538
|
+
id: m.id,
|
|
3539
|
+
name: body.name,
|
|
3540
|
+
mode: body.mode,
|
|
3541
|
+
provider: body.provider,
|
|
3542
|
+
edition: body.edition,
|
|
3543
|
+
organizationId: body.organizationId,
|
|
3544
|
+
apiBaseUrl: body.apiBaseUrl,
|
|
3545
|
+
insecureSsl: body.insecureSsl,
|
|
3546
|
+
localRoots: Array.isArray(body.localRoots) ? body.localRoots : typeof body.localRootsText === "string" ? String(body.localRootsText).split(/\r?\n/) : void 0,
|
|
3547
|
+
token: body.token,
|
|
3548
|
+
authorFilters: body.authorFilters,
|
|
3549
|
+
defaultBranch: body.defaultBranch,
|
|
3550
|
+
watchedRepoIds: body.watchedRepoIds,
|
|
3551
|
+
repoBranches: body.repoBranches
|
|
3552
|
+
}), getActiveAccountId()) });
|
|
3553
|
+
return;
|
|
3554
|
+
}
|
|
3555
|
+
if (method === "DELETE") {
|
|
3556
|
+
deleteAccount(m.id);
|
|
3557
|
+
sendJson(res, 200, {
|
|
3558
|
+
ok: true,
|
|
3559
|
+
removed: m.id
|
|
3560
|
+
});
|
|
3561
|
+
return;
|
|
3562
|
+
}
|
|
3563
|
+
}
|
|
3564
|
+
}
|
|
3565
|
+
{
|
|
3566
|
+
const m = matchRoute(url.pathname, "/api/accounts/:id/activate");
|
|
3567
|
+
if (m && method === "POST") {
|
|
3568
|
+
if (!getAccount(m.id)) return sendJson(res, 404, { error: "账号不存在" });
|
|
3569
|
+
setActiveAccountId(m.id);
|
|
3570
|
+
sendJson(res, 200, {
|
|
3571
|
+
ok: true,
|
|
3572
|
+
activeAccountId: m.id
|
|
3573
|
+
});
|
|
3574
|
+
return;
|
|
3575
|
+
}
|
|
3576
|
+
}
|
|
3577
|
+
{
|
|
3578
|
+
const m = matchRoute(url.pathname, "/api/accounts/:id/test");
|
|
3579
|
+
if (m && method === "POST") {
|
|
3580
|
+
const account = getAccount(m.id);
|
|
3581
|
+
if (!account) return sendJson(res, 404, { error: "账号不存在" });
|
|
3582
|
+
const token = account.mode === "local" ? "" : getAccountToken(m.id);
|
|
3583
|
+
sendJson(res, 200, {
|
|
3584
|
+
ok: true,
|
|
3585
|
+
...await getProvider(account).testConnection(account, token)
|
|
3586
|
+
});
|
|
3587
|
+
return;
|
|
3588
|
+
}
|
|
3589
|
+
}
|
|
3590
|
+
if (method === "GET" && url.pathname === "/api/repos") {
|
|
3591
|
+
const accountId = url.searchParams.get("accountId") || getActiveAccountId() || "";
|
|
3592
|
+
if (!accountId) return sendJson(res, 400, { error: "accountId required" });
|
|
3593
|
+
const account = getAccount(accountId);
|
|
3594
|
+
if (!account) return sendJson(res, 404, { error: "账号不存在" });
|
|
3595
|
+
const list = url.searchParams.get("withCommitsOnly") === "1" ? db.listReposWithCommits(accountId) : db.listRepos(accountId);
|
|
3596
|
+
sendJson(res, 200, {
|
|
3597
|
+
accountId,
|
|
3598
|
+
watchedRepoIds: account.watchedRepoIds,
|
|
3599
|
+
repoBranches: account.repoBranches,
|
|
3600
|
+
repos: list.map((r) => {
|
|
3601
|
+
const displayName = shortRepoPath(r.fullName || r.name, account.organizationId);
|
|
3602
|
+
return {
|
|
3603
|
+
id: r.id,
|
|
3604
|
+
name: r.name,
|
|
3605
|
+
fullName: displayName,
|
|
3606
|
+
displayName,
|
|
3607
|
+
webUrl: r.webUrl,
|
|
3608
|
+
defaultBranch: r.defaultBranch,
|
|
3609
|
+
lastActivityAt: r.lastActivityAt,
|
|
3610
|
+
participating: r.participating,
|
|
3611
|
+
watched: account.watchedRepoIds.length === 0 || account.watchedRepoIds.includes(r.id),
|
|
3612
|
+
branchOverride: account.repoBranches[r.id] || ""
|
|
3613
|
+
};
|
|
3614
|
+
})
|
|
3615
|
+
});
|
|
3616
|
+
return;
|
|
3617
|
+
}
|
|
3618
|
+
if (method === "GET" && url.pathname === "/api/repo-branches") {
|
|
3619
|
+
const accountId = url.searchParams.get("accountId") || getActiveAccountId() || "";
|
|
3620
|
+
const repoId = String(url.searchParams.get("repoId") || "").trim();
|
|
3621
|
+
const account = getAccount(accountId);
|
|
3622
|
+
if (!account) return sendJson(res, 404, { error: "账号不存在" });
|
|
3623
|
+
if (!repoId) return sendJson(res, 400, { error: "缺少 repoId" });
|
|
3624
|
+
const token = getAccountToken(accountId);
|
|
3625
|
+
sendJson(res, 200, {
|
|
3626
|
+
repoId,
|
|
3627
|
+
branches: (await getProvider(account).listBranches(account, token, repoId)).map((b) => ({
|
|
3628
|
+
name: b.name,
|
|
3629
|
+
defaultBranch: b.defaultBranch,
|
|
3630
|
+
protected: b.protected
|
|
3631
|
+
}))
|
|
3632
|
+
});
|
|
3633
|
+
return;
|
|
3634
|
+
}
|
|
3635
|
+
{
|
|
3636
|
+
const branchPath = url.pathname.match(/^\/api\/repos\/(.+)\/branches\/?$/);
|
|
3637
|
+
if (branchPath && method === "GET") {
|
|
3638
|
+
const accountId = url.searchParams.get("accountId") || getActiveAccountId() || "";
|
|
3639
|
+
const repoId = decodeURIComponent(branchPath[1]);
|
|
3640
|
+
const account = getAccount(accountId);
|
|
3641
|
+
if (!account) return sendJson(res, 404, { error: "账号不存在" });
|
|
3642
|
+
const token = getAccountToken(accountId);
|
|
3643
|
+
sendJson(res, 200, {
|
|
3644
|
+
repoId,
|
|
3645
|
+
branches: (await getProvider(account).listBranches(account, token, repoId)).map((b) => ({
|
|
3646
|
+
name: b.name,
|
|
3647
|
+
defaultBranch: b.defaultBranch,
|
|
3648
|
+
protected: b.protected
|
|
3649
|
+
}))
|
|
3650
|
+
});
|
|
3651
|
+
return;
|
|
3652
|
+
}
|
|
3653
|
+
}
|
|
3654
|
+
if (method === "POST" && url.pathname === "/api/repos/refresh") {
|
|
3655
|
+
const body = await readJson(req);
|
|
3656
|
+
const accountId = String(body.accountId || getActiveAccountId() || "");
|
|
3657
|
+
const account = getAccount(accountId);
|
|
3658
|
+
if (!account) return sendJson(res, 404, { error: "账号不存在" });
|
|
3659
|
+
const token = getAccountToken(accountId);
|
|
3660
|
+
const repos = await getProvider(account).listRepos(account, token);
|
|
3661
|
+
db.upsertRepos(accountId, repos);
|
|
3662
|
+
sendJson(res, 200, {
|
|
3663
|
+
accountId,
|
|
3664
|
+
count: repos.length,
|
|
3665
|
+
repos: db.listRepos(accountId)
|
|
3666
|
+
});
|
|
3667
|
+
return;
|
|
3668
|
+
}
|
|
3669
|
+
if (method === "PUT" && url.pathname === "/api/repos/watch") {
|
|
3670
|
+
const body = await readJson(req);
|
|
3671
|
+
const accountId = String(body.accountId || "");
|
|
3672
|
+
if (!getAccount(accountId)) return sendJson(res, 404, { error: "账号不存在" });
|
|
3673
|
+
const account = updateAccount({
|
|
3674
|
+
id: accountId,
|
|
3675
|
+
watchedRepoIds: Array.isArray(body.watchedRepoIds) ? body.watchedRepoIds.map(String) : [],
|
|
3676
|
+
repoBranches: body.repoBranches || {}
|
|
3677
|
+
});
|
|
3678
|
+
sendJson(res, 200, {
|
|
3679
|
+
ok: true,
|
|
3680
|
+
watchedRepoIds: account.watchedRepoIds,
|
|
3681
|
+
repoBranches: account.repoBranches
|
|
3682
|
+
});
|
|
3683
|
+
return;
|
|
3684
|
+
}
|
|
3685
|
+
if (method === "POST" && url.pathname === "/api/sync") {
|
|
3686
|
+
const body = await readJson(req);
|
|
3687
|
+
const accountId = String(body.accountId || getActiveAccountId() || "");
|
|
3688
|
+
if (!accountId) return sendJson(res, 400, { error: "accountId required" });
|
|
3689
|
+
sendJson(res, 200, await syncAccount(accountId, Array.isArray(body.repoIds) ? body.repoIds.map(String) : void 0));
|
|
3690
|
+
return;
|
|
3691
|
+
}
|
|
3692
|
+
if (method === "GET" && url.pathname === "/api/commits") {
|
|
3693
|
+
const accountId = url.searchParams.get("accountId") || getActiveAccountId() || "";
|
|
3694
|
+
if (!accountId) return sendJson(res, 400, { error: "accountId required" });
|
|
3695
|
+
const limit = Number(url.searchParams.get("limit") || 20);
|
|
3696
|
+
const offset = Number(url.searchParams.get("offset") || 0);
|
|
3697
|
+
sendJson(res, 200, db.queryCommits({
|
|
3698
|
+
accountId,
|
|
3699
|
+
repoId: url.searchParams.get("repoId") || void 0,
|
|
3700
|
+
from: url.searchParams.get("from") || void 0,
|
|
3701
|
+
to: url.searchParams.get("to") || void 0,
|
|
3702
|
+
keyword: url.searchParams.get("keyword") || void 0,
|
|
3703
|
+
limit,
|
|
3704
|
+
offset
|
|
3705
|
+
}));
|
|
3706
|
+
return;
|
|
3707
|
+
}
|
|
3708
|
+
if (method === "POST" && url.pathname === "/api/commits/clear") {
|
|
3709
|
+
const body = await readJson(req);
|
|
3710
|
+
const accountId = String(body.accountId || "");
|
|
3711
|
+
if (!accountId) return sendJson(res, 400, { error: "accountId required" });
|
|
3712
|
+
sendJson(res, 200, db.clearCommits(accountId, body.repoId ? String(body.repoId) : void 0));
|
|
3713
|
+
return;
|
|
3714
|
+
}
|
|
3715
|
+
if (method === "GET" && url.pathname === "/api/activity") {
|
|
3716
|
+
const accountId = url.searchParams.get("accountId") || getActiveAccountId() || "";
|
|
3717
|
+
const yearRaw = url.searchParams.get("year");
|
|
3718
|
+
const year = yearRaw ? Number(yearRaw) : void 0;
|
|
3719
|
+
if (!accountId) return sendJson(res, 400, { error: "accountId required" });
|
|
3720
|
+
sendJson(res, 200, db.getActivity(accountId, year));
|
|
3721
|
+
return;
|
|
3722
|
+
}
|
|
3723
|
+
if (method === "GET" && url.pathname === "/api/activity/day") {
|
|
3724
|
+
const accountId = url.searchParams.get("accountId") || getActiveAccountId() || "";
|
|
3725
|
+
const date = url.searchParams.get("date") || "";
|
|
3726
|
+
if (!accountId || !date) return sendJson(res, 400, { error: "accountId/date required" });
|
|
3727
|
+
sendJson(res, 200, { commits: db.listDayCommits(accountId, date).map((c) => ({
|
|
3728
|
+
id: c.id,
|
|
3729
|
+
time: c.committedAt,
|
|
3730
|
+
repo: c.repoName,
|
|
3731
|
+
title: c.title,
|
|
3732
|
+
message: c.message,
|
|
3733
|
+
authorName: c.authorName,
|
|
3734
|
+
sha: c.shortId,
|
|
3735
|
+
webUrl: c.webUrl,
|
|
3736
|
+
additions: c.additions,
|
|
3737
|
+
deletions: c.deletions,
|
|
3738
|
+
filesChanged: c.filesChanged
|
|
3739
|
+
})) });
|
|
3740
|
+
return;
|
|
3741
|
+
}
|
|
3742
|
+
if (method === "GET" && url.pathname === "/api/logs") {
|
|
3743
|
+
const accountId = url.searchParams.get("accountId") || getActiveAccountId() || "";
|
|
3744
|
+
if (!accountId) return sendJson(res, 400, { error: "accountId required" });
|
|
3745
|
+
const limit = Number(url.searchParams.get("limit") || 50);
|
|
3746
|
+
const offset = Number(url.searchParams.get("offset") || 0);
|
|
3747
|
+
sendJson(res, 200, db.listSyncLogs(accountId, limit, offset));
|
|
3748
|
+
return;
|
|
3749
|
+
}
|
|
3750
|
+
if (method === "DELETE" && url.pathname === "/api/logs") {
|
|
3751
|
+
const accountId = url.searchParams.get("accountId") || await readJson(req).then((b) => b.accountId).catch(() => "") || "";
|
|
3752
|
+
sendJson(res, 200, { deleted: db.clearSyncLogs(accountId || void 0) });
|
|
3753
|
+
return;
|
|
3754
|
+
}
|
|
3755
|
+
if (method === "GET" && url.pathname === "/api/settings") {
|
|
3756
|
+
sendJson(res, 200, {
|
|
3757
|
+
...describeSettings(),
|
|
3758
|
+
listenPort,
|
|
3759
|
+
apiBase: listenPort ? `http://127.0.0.1:${listenPort}` : null
|
|
3760
|
+
});
|
|
3761
|
+
return;
|
|
3762
|
+
}
|
|
3763
|
+
if ((method === "PUT" || method === "PATCH") && url.pathname === "/api/settings") {
|
|
3764
|
+
const body = await readJson(req);
|
|
3765
|
+
const next = updateSettings({
|
|
3766
|
+
exportsPath: body.exportsPath,
|
|
3767
|
+
syncIntervalMinutes: body.syncIntervalMinutes,
|
|
3768
|
+
syncLookbackDays: body.syncLookbackDays,
|
|
3769
|
+
uiPort: body.uiPort,
|
|
3770
|
+
reportExcludeMerge: body.reportExcludeMerge,
|
|
3771
|
+
reportExcludeTypes: body.reportExcludeTypes,
|
|
3772
|
+
reportExcludeAuthors: body.reportExcludeAuthors,
|
|
3773
|
+
reportGroupBy: body.reportGroupBy
|
|
3774
|
+
});
|
|
3775
|
+
sendJson(res, 200, {
|
|
3776
|
+
ok: true,
|
|
3777
|
+
settings: describeSettings(),
|
|
3778
|
+
saved: next
|
|
3779
|
+
});
|
|
3780
|
+
return;
|
|
3781
|
+
}
|
|
3782
|
+
sendJson(res, 404, { error: "not found" });
|
|
3783
|
+
} catch (e) {
|
|
3784
|
+
sendJson(res, 500, { error: e?.message || String(e) });
|
|
3785
|
+
}
|
|
3786
|
+
}
|
|
3787
|
+
function getHeatmapUrl() {
|
|
3788
|
+
return listenPort ? `http://127.0.0.1:${listenPort}/` : null;
|
|
3789
|
+
}
|
|
3790
|
+
async function startUiServer(port = getUiPort()) {
|
|
3791
|
+
if (server && listenPort) return `http://127.0.0.1:${listenPort}/`;
|
|
3792
|
+
server = createServer((req, res) => {
|
|
3793
|
+
handler(req, res);
|
|
3794
|
+
});
|
|
3795
|
+
await new Promise((resolve, reject) => {
|
|
3796
|
+
server.once("error", reject);
|
|
3797
|
+
server.listen(port, "127.0.0.1", () => resolve());
|
|
3798
|
+
});
|
|
3799
|
+
listenPort = port;
|
|
3800
|
+
return `http://127.0.0.1:${port}/`;
|
|
3801
|
+
}
|
|
3802
|
+
async function stopUiServer() {
|
|
3803
|
+
if (!server) return;
|
|
3804
|
+
const s = server;
|
|
3805
|
+
server = null;
|
|
3806
|
+
listenPort = null;
|
|
3807
|
+
await new Promise((resolve) => s.close(() => resolve()));
|
|
3808
|
+
}
|
|
3809
|
+
// src/index.ts
|
|
3810
|
+
const name = "commit-journal";
|
|
3811
|
+
const inject = ["tools"];
|
|
3812
|
+
/**
|
|
3813
|
+
* Commit Journal dsh 插件:同步 VCS 提交与活跃热力图面板
|
|
3814
|
+
*/
|
|
3815
|
+
function apply(ctx) {
|
|
3816
|
+
ensureDataLayout();
|
|
3817
|
+
registerTools(ctx);
|
|
3818
|
+
ctx.tools.register(defineTool({
|
|
3819
|
+
name: "open_activity_heatmap",
|
|
3820
|
+
description: "返回本机 Commit Journal API 基址(侧栏面板数据源)。",
|
|
3821
|
+
parameters: {},
|
|
3822
|
+
output: {
|
|
3823
|
+
schema: { type: "string" },
|
|
3824
|
+
render: (_a, v) => [{
|
|
3825
|
+
type: "text",
|
|
3826
|
+
text: String(v)
|
|
3827
|
+
}]
|
|
3828
|
+
},
|
|
3829
|
+
async execute() {
|
|
3830
|
+
const url = await startUiServer();
|
|
3831
|
+
return JSON.stringify({
|
|
3832
|
+
url,
|
|
3833
|
+
dataRoot: getDataRoot()
|
|
3834
|
+
}, null, 2);
|
|
3835
|
+
}
|
|
3836
|
+
}));
|
|
3837
|
+
ctx.effect(() => {
|
|
3838
|
+
startUiServer().catch((e) => {
|
|
3839
|
+
ctx.logger?.warn?.(`[commit-journal] ui server: ${e?.message || e}`);
|
|
3840
|
+
});
|
|
3841
|
+
try {
|
|
3842
|
+
rescheduleAll();
|
|
3843
|
+
} catch {}
|
|
3844
|
+
return () => {
|
|
3845
|
+
stopAllSchedules();
|
|
3846
|
+
stopUiServer();
|
|
3847
|
+
};
|
|
3848
|
+
});
|
|
3849
|
+
}
|
|
3850
|
+
export { apply, getDataRoot, getHeatmapUrl, inject, name, startUiServer, stopUiServer };
|
|
3851
|
+
|
|
3852
|
+
//# sourceMappingURL=index.js.map
|