revgraph 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +135 -2
- package/README.zh-CN.md +84 -0
- package/assets/logo.svg +62 -0
- package/examples/cc-switch.rules.json +77 -0
- package/package.json +41 -4
- package/skills/revgraph/SKILL.md +128 -0
- package/skills/revgraph/references/rules.json +126 -0
- package/skills/revgraph/scripts/cli.mjs +471 -0
- package/skills/revgraph/scripts/git.mjs +559 -0
- package/skills/revgraph/scripts/graph.mjs +608 -0
- package/skills/revgraph/scripts/parsers/common.mjs +308 -0
- package/skills/revgraph/scripts/parsers/go.mjs +137 -0
- package/skills/revgraph/scripts/parsers/python.mjs +181 -0
- package/skills/revgraph/scripts/parsers/rust.mjs +253 -0
- package/skills/revgraph/scripts/parsers/tauri.mjs +363 -0
- package/skills/revgraph/scripts/parsers/ts.mjs +199 -0
|
@@ -0,0 +1,559 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Run a command safely without shell interpolation.
|
|
7
|
+
*/
|
|
8
|
+
export function runCmd(bin, args, cwd, { allowFailure = false, maxBuffer = 64 * 1024 * 1024 } = {}) {
|
|
9
|
+
try {
|
|
10
|
+
const out = execFileSync(bin, args, {
|
|
11
|
+
cwd,
|
|
12
|
+
encoding: "utf8",
|
|
13
|
+
maxBuffer,
|
|
14
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
15
|
+
});
|
|
16
|
+
return { ok: true, stdout: out, stderr: "", code: 0 };
|
|
17
|
+
} catch (err) {
|
|
18
|
+
if (allowFailure) {
|
|
19
|
+
return {
|
|
20
|
+
ok: false,
|
|
21
|
+
stdout: err.stdout ? String(err.stdout) : "",
|
|
22
|
+
stderr: err.stderr ? String(err.stderr) : err.message,
|
|
23
|
+
code: typeof err.status === "number" ? err.status : 1,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
const detail = err.stderr ? String(err.stderr).trim() : err.message;
|
|
27
|
+
throw new Error(`Command failed: ${bin} ${args.join(" ")}\n${detail}`);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function git(repoDir, args, opts = {}) {
|
|
32
|
+
return runCmd("git", ["--no-pager", ...args], repoDir, opts);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Convert a glob pattern (*, **, ?) into a RegExp matching posix paths.
|
|
37
|
+
*/
|
|
38
|
+
export function globToRegex(pattern) {
|
|
39
|
+
const normalized = pattern.trim().replace(/\\/g, "/");
|
|
40
|
+
let re = "^";
|
|
41
|
+
let i = 0;
|
|
42
|
+
while (i < normalized.length) {
|
|
43
|
+
const ch = normalized[i];
|
|
44
|
+
if (ch === "*") {
|
|
45
|
+
if (normalized[i + 1] === "*") {
|
|
46
|
+
if (normalized[i + 2] === "/") {
|
|
47
|
+
re += "(?:.*/)?";
|
|
48
|
+
i += 3;
|
|
49
|
+
} else {
|
|
50
|
+
re += ".*";
|
|
51
|
+
i += 2;
|
|
52
|
+
}
|
|
53
|
+
} else {
|
|
54
|
+
re += "[^/]*";
|
|
55
|
+
i += 1;
|
|
56
|
+
}
|
|
57
|
+
} else if (ch === "?") {
|
|
58
|
+
re += "[^/]";
|
|
59
|
+
i += 1;
|
|
60
|
+
} else if ("+.^$|()[]{}\\".includes(ch)) {
|
|
61
|
+
re += "\\" + ch;
|
|
62
|
+
i += 1;
|
|
63
|
+
} else {
|
|
64
|
+
re += ch;
|
|
65
|
+
i += 1;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
re += "$";
|
|
69
|
+
return new RegExp(re);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function matchesAnyGlob(relPath, patterns) {
|
|
73
|
+
const p = relPath.replace(/\\/g, "/");
|
|
74
|
+
const base = path.posix.basename(p);
|
|
75
|
+
for (const pat of patterns) {
|
|
76
|
+
if (!pat) continue;
|
|
77
|
+
const regex = globToRegex(pat);
|
|
78
|
+
if (regex.test(p)) return pat;
|
|
79
|
+
if (!pat.includes("/") && regex.test(base)) return pat;
|
|
80
|
+
}
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function parsePrInput(raw) {
|
|
85
|
+
if (!raw) return null;
|
|
86
|
+
const trimmed = String(raw).trim();
|
|
87
|
+
const numOnly = trimmed.match(/^#?(\d+)$/);
|
|
88
|
+
if (numOnly) return { number: Number(numOnly[1]), raw: trimmed };
|
|
89
|
+
const urlMatch = trimmed.match(/github\.com\/([^/]+\/[^/]+)\/pull\/(\d+)/i);
|
|
90
|
+
if (urlMatch) {
|
|
91
|
+
return { repo: urlMatch[1], number: Number(urlMatch[2]), raw: trimmed };
|
|
92
|
+
}
|
|
93
|
+
throw new Error(`Invalid --pr value "${raw}". Expected PR number (e.g. 123) or GitHub PR URL.`);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function resolveRefExists(repoDir, ref) {
|
|
97
|
+
if (!ref) return false;
|
|
98
|
+
return git(repoDir, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], { allowFailure: true }).ok;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function parseNumstat(stdout) {
|
|
102
|
+
const map = new Map();
|
|
103
|
+
for (const line of stdout.split("\n")) {
|
|
104
|
+
if (!line.trim()) continue;
|
|
105
|
+
const parts = line.split("\t");
|
|
106
|
+
if (parts.length < 3) continue;
|
|
107
|
+
const [insStr, delStr, ...rest] = parts;
|
|
108
|
+
const rawPath = rest.join("\t");
|
|
109
|
+
let filePath = rawPath;
|
|
110
|
+
if (rawPath.includes(" => ")) {
|
|
111
|
+
filePath = rawPath.replace(/\{[^{}]*=>\s*([^{}]*)\}/g, "$1").replace(/^.*=>\s*/, "");
|
|
112
|
+
}
|
|
113
|
+
const binary = insStr === "-" || delStr === "-";
|
|
114
|
+
const insertions = binary ? 0 : Number.parseInt(insStr, 10) || 0;
|
|
115
|
+
const deletions = binary ? 0 : Number.parseInt(delStr, 10) || 0;
|
|
116
|
+
map.set(filePath, { insertions, deletions, binary });
|
|
117
|
+
}
|
|
118
|
+
return map;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function parseNameStatus(stdout) {
|
|
122
|
+
const entries = [];
|
|
123
|
+
for (const line of stdout.split("\n")) {
|
|
124
|
+
if (!line.trim()) continue;
|
|
125
|
+
const parts = line.split("\t");
|
|
126
|
+
const rawStatus = parts[0];
|
|
127
|
+
const code = rawStatus[0];
|
|
128
|
+
if ((code === "R" || code === "C") && parts.length >= 3) {
|
|
129
|
+
entries.push({ status: code === "R" ? "renamed" : "copied", oldPath: parts[1], path: parts[2] });
|
|
130
|
+
} else if (parts.length >= 2) {
|
|
131
|
+
const statusMap = { A: "added", M: "modified", D: "deleted", T: "typechange" };
|
|
132
|
+
entries.push({ status: statusMap[code] || rawStatus, path: parts[1] });
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return entries;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function parseUnifiedDiffStats(diffText) {
|
|
139
|
+
const fileMap = new Map();
|
|
140
|
+
let current = null;
|
|
141
|
+
for (const line of diffText.split("\n")) {
|
|
142
|
+
if (line.startsWith("diff --git ")) {
|
|
143
|
+
const m = line.match(/^diff --git a\/(.+?) b\/(.+)$/);
|
|
144
|
+
if (m) {
|
|
145
|
+
current = {
|
|
146
|
+
path: m[2],
|
|
147
|
+
oldPath: m[1] !== m[2] ? m[1] : undefined,
|
|
148
|
+
status: "modified",
|
|
149
|
+
insertions: 0,
|
|
150
|
+
deletions: 0,
|
|
151
|
+
binary: false,
|
|
152
|
+
patchLines: [line],
|
|
153
|
+
};
|
|
154
|
+
fileMap.set(current.path, current);
|
|
155
|
+
}
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
if (!current) continue;
|
|
159
|
+
current.patchLines.push(line);
|
|
160
|
+
if (line.startsWith("new file mode ")) current.status = "added";
|
|
161
|
+
else if (line.startsWith("deleted file mode ")) current.status = "deleted";
|
|
162
|
+
else if (line.startsWith("rename to ")) current.status = "renamed";
|
|
163
|
+
else if (line.startsWith("Binary files ")) current.binary = true;
|
|
164
|
+
else if (line.startsWith("+") && !line.startsWith("+++ ")) current.insertions += 1;
|
|
165
|
+
else if (line.startsWith("-") && !line.startsWith("--- ")) current.deletions += 1;
|
|
166
|
+
}
|
|
167
|
+
return fileMap;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function isLikelyBinaryFile(absPath) {
|
|
171
|
+
try {
|
|
172
|
+
const fd = fs.openSync(absPath, "r");
|
|
173
|
+
const buf = Buffer.alloc(4096);
|
|
174
|
+
const bytes = fs.readSync(fd, buf, 0, buf.length, 0);
|
|
175
|
+
fs.closeSync(fd);
|
|
176
|
+
for (let i = 0; i < bytes; i++) {
|
|
177
|
+
if (buf[i] === 0) return true;
|
|
178
|
+
}
|
|
179
|
+
return false;
|
|
180
|
+
} catch {
|
|
181
|
+
return false;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Parse `git status --porcelain=v1 -z -uall` to preserve exact paths (spaces/unicode)
|
|
187
|
+
* and keep distinct (path, status) pairs when a deleted file is recreated untracked.
|
|
188
|
+
*/
|
|
189
|
+
function parseWorkspacePorcelainZ(repoRoot, statusZ, numstat) {
|
|
190
|
+
const tokens = statusZ.split("\0");
|
|
191
|
+
const rawFiles = [];
|
|
192
|
+
const seen = new Set();
|
|
193
|
+
|
|
194
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
195
|
+
const entry = tokens[i];
|
|
196
|
+
if (!entry || entry.length < 4) continue;
|
|
197
|
+
const xy = entry.slice(0, 2);
|
|
198
|
+
let filePath = entry.slice(3);
|
|
199
|
+
let oldPath;
|
|
200
|
+
|
|
201
|
+
// For renames/copies in -z mode, the next NUL token is the original path
|
|
202
|
+
if (xy[0] === "R" || xy[0] === "C" || xy[1] === "R" || xy[1] === "C") {
|
|
203
|
+
oldPath = tokens[++i];
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
if (xy === "??") {
|
|
207
|
+
const key = `${filePath}::untracked`;
|
|
208
|
+
if (seen.has(key)) continue;
|
|
209
|
+
seen.add(key);
|
|
210
|
+
const abs = path.join(repoRoot, filePath);
|
|
211
|
+
let lines = 0;
|
|
212
|
+
let binary = false;
|
|
213
|
+
if (fs.existsSync(abs) && fs.statSync(abs).isFile()) {
|
|
214
|
+
binary = isLikelyBinaryFile(abs);
|
|
215
|
+
if (!binary) {
|
|
216
|
+
try {
|
|
217
|
+
lines = fs.readFileSync(abs, "utf8").split("\n").length;
|
|
218
|
+
} catch {
|
|
219
|
+
lines = 0;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
rawFiles.push({ path: filePath, status: "untracked", insertions: lines, deletions: 0, binary });
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
let status = "modified";
|
|
228
|
+
if (xy.includes("D")) status = "deleted";
|
|
229
|
+
else if (xy.includes("A")) status = "added";
|
|
230
|
+
else if (xy.includes("R")) status = "renamed";
|
|
231
|
+
else if (xy.includes("C")) status = "copied";
|
|
232
|
+
|
|
233
|
+
const key = `${filePath}::${status}`;
|
|
234
|
+
if (seen.has(key)) continue;
|
|
235
|
+
seen.add(key);
|
|
236
|
+
const stats = numstat.get(filePath) || { insertions: 0, deletions: 0, binary: false };
|
|
237
|
+
rawFiles.push({ path: filePath, ...(oldPath ? { oldPath } : {}), status, ...stats });
|
|
238
|
+
}
|
|
239
|
+
return rawFiles;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Resolve review target (PR / range / commit / workspace) and return structured preview metadata.
|
|
244
|
+
*/
|
|
245
|
+
export function collectReviewTarget(repoDir, opts, excludePatterns = []) {
|
|
246
|
+
const repoRoot = git(repoDir, ["rev-parse", "--show-toplevel"]).stdout.trim();
|
|
247
|
+
const warnings = [];
|
|
248
|
+
let mode = "workspace";
|
|
249
|
+
let prMeta = null;
|
|
250
|
+
let fromRef = null;
|
|
251
|
+
let toRef = null;
|
|
252
|
+
let commitRef = null;
|
|
253
|
+
let mergeBase = null;
|
|
254
|
+
let headGitRef = null;
|
|
255
|
+
let fallbackDiffMap = null;
|
|
256
|
+
let rawFiles = [];
|
|
257
|
+
|
|
258
|
+
if (opts.pr) {
|
|
259
|
+
mode = "pr";
|
|
260
|
+
const parsedPr = parsePrInput(opts.pr);
|
|
261
|
+
const ghArgs = [
|
|
262
|
+
"pr",
|
|
263
|
+
"view",
|
|
264
|
+
String(parsedPr.number),
|
|
265
|
+
"--json",
|
|
266
|
+
"number,title,body,author,baseRefName,headRefName,baseRefOid,headRefOid,url,additions,deletions",
|
|
267
|
+
];
|
|
268
|
+
if (parsedPr.repo) ghArgs.push("--repo", parsedPr.repo);
|
|
269
|
+
const prRes = runCmd("gh", ghArgs, repoRoot);
|
|
270
|
+
const prJson = JSON.parse(prRes.stdout);
|
|
271
|
+
prMeta = {
|
|
272
|
+
number: prJson.number,
|
|
273
|
+
title: prJson.title,
|
|
274
|
+
author: prJson.author?.login || "unknown",
|
|
275
|
+
url: prJson.url,
|
|
276
|
+
base_ref: prJson.baseRefName,
|
|
277
|
+
head_ref: prJson.headRefName,
|
|
278
|
+
base_oid: prJson.baseRefOid,
|
|
279
|
+
head_oid: prJson.headRefOid,
|
|
280
|
+
body: (prJson.body || "").slice(0, 4000),
|
|
281
|
+
};
|
|
282
|
+
|
|
283
|
+
// Fetch PR head into git object store without modifying working tree
|
|
284
|
+
if (resolveRefExists(repoRoot, prJson.headRefOid)) {
|
|
285
|
+
headGitRef = prJson.headRefOid;
|
|
286
|
+
} else {
|
|
287
|
+
const fetchRes = git(
|
|
288
|
+
repoRoot,
|
|
289
|
+
["fetch", "--no-tags", "origin", `pull/${prJson.number}/head`],
|
|
290
|
+
{ allowFailure: true },
|
|
291
|
+
);
|
|
292
|
+
if (fetchRes.ok) {
|
|
293
|
+
headGitRef = git(repoRoot, ["rev-parse", "FETCH_HEAD"]).stdout.trim();
|
|
294
|
+
} else {
|
|
295
|
+
warnings.push(
|
|
296
|
+
`Could not fetch origin pull/${prJson.number}/head (${fetchRes.stderr.trim()}); falling back to 'gh pr diff'.`,
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const baseCandidates = [prJson.baseRefOid, `origin/${prJson.baseRefName}`, prJson.baseRefName];
|
|
302
|
+
let resolvedBase = baseCandidates.find((r) => resolveRefExists(repoRoot, r)) || null;
|
|
303
|
+
if (!resolvedBase && headGitRef) {
|
|
304
|
+
const fetchBase = git(
|
|
305
|
+
repoRoot,
|
|
306
|
+
["fetch", "--no-tags", "origin", prJson.baseRefName],
|
|
307
|
+
{ allowFailure: true },
|
|
308
|
+
);
|
|
309
|
+
if (fetchBase.ok && resolveRefExists(repoRoot, `origin/${prJson.baseRefName}`)) {
|
|
310
|
+
resolvedBase = `origin/${prJson.baseRefName}`;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
fromRef = resolvedBase || prJson.baseRefName;
|
|
315
|
+
toRef = headGitRef || prJson.headRefName;
|
|
316
|
+
|
|
317
|
+
if (headGitRef && resolvedBase) {
|
|
318
|
+
const mbRes = git(repoRoot, ["merge-base", resolvedBase, headGitRef], { allowFailure: true });
|
|
319
|
+
mergeBase = mbRes.ok ? mbRes.stdout.trim() : resolvedBase;
|
|
320
|
+
const ns = git(repoRoot, ["diff", "--name-status", "-M", `${mergeBase}..${headGitRef}`]).stdout;
|
|
321
|
+
const numstat = parseNumstat(
|
|
322
|
+
git(repoRoot, ["diff", "--numstat", "-M", `${mergeBase}..${headGitRef}`]).stdout,
|
|
323
|
+
);
|
|
324
|
+
rawFiles = parseNameStatus(ns).map((entry) => ({
|
|
325
|
+
...entry,
|
|
326
|
+
...(numstat.get(entry.path) || { insertions: 0, deletions: 0, binary: false }),
|
|
327
|
+
}));
|
|
328
|
+
} else {
|
|
329
|
+
const diffArgs = ["pr", "diff", String(parsedPr.number)];
|
|
330
|
+
if (parsedPr.repo) diffArgs.push("--repo", parsedPr.repo);
|
|
331
|
+
const ghDiff = runCmd("gh", diffArgs, repoRoot).stdout;
|
|
332
|
+
fallbackDiffMap = parseUnifiedDiffStats(ghDiff);
|
|
333
|
+
rawFiles = Array.from(fallbackDiffMap.values()).map(({ patchLines: _, ...rest }) => rest);
|
|
334
|
+
}
|
|
335
|
+
} else if (opts.commit) {
|
|
336
|
+
mode = "commit";
|
|
337
|
+
commitRef = git(repoRoot, ["rev-parse", `${opts.commit}^{commit}`]).stdout.trim();
|
|
338
|
+
headGitRef = commitRef;
|
|
339
|
+
const parentRes = git(repoRoot, ["rev-parse", "--verify", "--quiet", `${commitRef}^`], {
|
|
340
|
+
allowFailure: true,
|
|
341
|
+
});
|
|
342
|
+
fromRef = parentRes.ok ? parentRes.stdout.trim() : null;
|
|
343
|
+
toRef = commitRef;
|
|
344
|
+
const ns = git(repoRoot, ["show", "--format=", "--name-status", "-M", commitRef]).stdout;
|
|
345
|
+
const numstat = parseNumstat(
|
|
346
|
+
git(repoRoot, ["show", "--format=", "--numstat", "-M", commitRef]).stdout,
|
|
347
|
+
);
|
|
348
|
+
rawFiles = parseNameStatus(ns).map((entry) => ({
|
|
349
|
+
...entry,
|
|
350
|
+
...(numstat.get(entry.path) || { insertions: 0, deletions: 0, binary: false }),
|
|
351
|
+
}));
|
|
352
|
+
} else if (opts.from || opts.to) {
|
|
353
|
+
mode = "range";
|
|
354
|
+
fromRef = opts.from || "main";
|
|
355
|
+
toRef = opts.to || "HEAD";
|
|
356
|
+
headGitRef = git(repoRoot, ["rev-parse", `${toRef}^{commit}`]).stdout.trim();
|
|
357
|
+
const mbRes = git(repoRoot, ["merge-base", fromRef, headGitRef], { allowFailure: true });
|
|
358
|
+
mergeBase = mbRes.ok ? mbRes.stdout.trim() : fromRef;
|
|
359
|
+
const ns = git(repoRoot, ["diff", "--name-status", "-M", `${mergeBase}..${headGitRef}`]).stdout;
|
|
360
|
+
const numstat = parseNumstat(
|
|
361
|
+
git(repoRoot, ["diff", "--numstat", "-M", `${mergeBase}..${headGitRef}`]).stdout,
|
|
362
|
+
);
|
|
363
|
+
rawFiles = parseNameStatus(ns).map((entry) => ({
|
|
364
|
+
...entry,
|
|
365
|
+
...(numstat.get(entry.path) || { insertions: 0, deletions: 0, binary: false }),
|
|
366
|
+
}));
|
|
367
|
+
} else {
|
|
368
|
+
mode = "workspace";
|
|
369
|
+
const hasHead = resolveRefExists(repoRoot, "HEAD");
|
|
370
|
+
const statusZ = git(repoRoot, ["status", "--porcelain=v1", "-z", "-uall"]).stdout;
|
|
371
|
+
const numstat = hasHead
|
|
372
|
+
? parseNumstat(git(repoRoot, ["diff", "--numstat", "HEAD"]).stdout)
|
|
373
|
+
: parseNumstat(git(repoRoot, ["diff", "--cached", "--numstat"]).stdout);
|
|
374
|
+
rawFiles = parseWorkspacePorcelainZ(repoRoot, statusZ, numstat);
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
const reviewableFiles = [];
|
|
378
|
+
const excludedFiles = [];
|
|
379
|
+
|
|
380
|
+
for (const f of rawFiles) {
|
|
381
|
+
if (f.binary) {
|
|
382
|
+
excludedFiles.push({ path: f.path, status: f.status, reason: "binary file" });
|
|
383
|
+
continue;
|
|
384
|
+
}
|
|
385
|
+
const matchedExclude = matchesAnyGlob(f.path, excludePatterns);
|
|
386
|
+
if (matchedExclude) {
|
|
387
|
+
excludedFiles.push({ path: f.path, status: f.status, reason: `matches exclude: ${matchedExclude}` });
|
|
388
|
+
continue;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
let diffCmd = "";
|
|
392
|
+
if (mode === "pr" || mode === "range") {
|
|
393
|
+
if (mergeBase && headGitRef) {
|
|
394
|
+
diffCmd = `git --no-pager diff --no-ext-diff --no-textconv --no-color ${mergeBase}..${headGitRef} -- "${f.path}"`;
|
|
395
|
+
} else if (prMeta) {
|
|
396
|
+
diffCmd = `gh pr diff ${prMeta.number}`;
|
|
397
|
+
}
|
|
398
|
+
} else if (mode === "commit") {
|
|
399
|
+
diffCmd = `git --no-pager show --no-ext-diff --no-textconv --no-color ${commitRef} -- "${f.path}"`;
|
|
400
|
+
} else if (f.status === "untracked") {
|
|
401
|
+
diffCmd = `cat "${f.path}"`;
|
|
402
|
+
} else if (resolveRefExists(repoRoot, "HEAD")) {
|
|
403
|
+
diffCmd = `git --no-pager diff --no-ext-diff --no-textconv --no-color HEAD -- "${f.path}"`;
|
|
404
|
+
} else {
|
|
405
|
+
diffCmd = `git --no-pager diff --cached --no-ext-diff --no-textconv --no-color -- "${f.path}"`;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
reviewableFiles.push({
|
|
409
|
+
path: f.path,
|
|
410
|
+
...(f.oldPath ? { old_path: f.oldPath } : {}),
|
|
411
|
+
status: f.status,
|
|
412
|
+
insertions: f.insertions,
|
|
413
|
+
deletions: f.deletions,
|
|
414
|
+
diff_cmd: diffCmd,
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
return {
|
|
419
|
+
repo_root: repoRoot,
|
|
420
|
+
mode,
|
|
421
|
+
...(prMeta ? { pr: prMeta } : {}),
|
|
422
|
+
from: fromRef,
|
|
423
|
+
to: toRef,
|
|
424
|
+
commit: commitRef,
|
|
425
|
+
merge_base: mergeBase,
|
|
426
|
+
head_git_ref: headGitRef,
|
|
427
|
+
reviewable_files: reviewableFiles,
|
|
428
|
+
excluded_files: excludedFiles,
|
|
429
|
+
warnings,
|
|
430
|
+
_fallbackDiffMap: fallbackDiffMap,
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* List repository files at the target snapshot using git (respects .gitignore and any monorepo layout).
|
|
436
|
+
*/
|
|
437
|
+
export function listRepoFiles(target) {
|
|
438
|
+
let raw = "";
|
|
439
|
+
if (target.mode !== "workspace" && target.head_git_ref) {
|
|
440
|
+
const res = git(target.repo_root, ["ls-tree", "-r", "--name-only", "-z", target.head_git_ref], {
|
|
441
|
+
allowFailure: true,
|
|
442
|
+
});
|
|
443
|
+
if (res.ok) raw = res.stdout;
|
|
444
|
+
}
|
|
445
|
+
if (!raw) {
|
|
446
|
+
const res = git(target.repo_root, ["ls-files", "-co", "--exclude-standard", "-z"], {
|
|
447
|
+
allowFailure: true,
|
|
448
|
+
});
|
|
449
|
+
if (res.ok) raw = res.stdout;
|
|
450
|
+
}
|
|
451
|
+
const files = raw
|
|
452
|
+
.split("\0")
|
|
453
|
+
.filter(Boolean)
|
|
454
|
+
.map((p) => p.replace(/\\/g, "/"));
|
|
455
|
+
return Array.from(new Set(files)).sort();
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/**
|
|
459
|
+
* Read file text at the target snapshot without modifying the working tree.
|
|
460
|
+
*/
|
|
461
|
+
export function readFileAtTarget(target, relPath, cache = new Map()) {
|
|
462
|
+
if (cache.has(relPath)) return cache.get(relPath);
|
|
463
|
+
let content = null;
|
|
464
|
+
if (target.mode === "workspace" || !target.head_git_ref) {
|
|
465
|
+
const abs = path.join(target.repo_root, relPath);
|
|
466
|
+
if (fs.existsSync(abs) && fs.statSync(abs).isFile()) {
|
|
467
|
+
try {
|
|
468
|
+
content = fs.readFileSync(abs, "utf8");
|
|
469
|
+
} catch {
|
|
470
|
+
content = null;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
} else {
|
|
474
|
+
const res = git(target.repo_root, ["show", `${target.head_git_ref}:${relPath}`], {
|
|
475
|
+
allowFailure: true,
|
|
476
|
+
});
|
|
477
|
+
if (res.ok) content = res.stdout;
|
|
478
|
+
}
|
|
479
|
+
cache.set(relPath, content);
|
|
480
|
+
return content;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/**
|
|
484
|
+
* Get zero-context unified diff for a file and extract changed line ranges and +/- text.
|
|
485
|
+
*/
|
|
486
|
+
export function getFileDiffInfo(target, fileEntry) {
|
|
487
|
+
const relPath = fileEntry.path;
|
|
488
|
+
let patch = "";
|
|
489
|
+
|
|
490
|
+
if (fileEntry.status === "untracked") {
|
|
491
|
+
const content = readFileAtTarget(target, relPath);
|
|
492
|
+
const lines = content ? content.split("\n") : [];
|
|
493
|
+
return {
|
|
494
|
+
patch: content || "",
|
|
495
|
+
added_lines: lines.length > 0 ? [{ start: 1, end: lines.length }] : [],
|
|
496
|
+
removed_lines: [],
|
|
497
|
+
added_text: lines,
|
|
498
|
+
removed_text: [],
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
if (target._fallbackDiffMap && target._fallbackDiffMap.has(relPath)) {
|
|
503
|
+
patch = target._fallbackDiffMap.get(relPath).patchLines.join("\n");
|
|
504
|
+
} else if ((target.mode === "pr" || target.mode === "range") && target.merge_base && target.head_git_ref) {
|
|
505
|
+
patch = git(
|
|
506
|
+
target.repo_root,
|
|
507
|
+
["diff", "--no-ext-diff", "--no-textconv", "--no-color", "-U0", `${target.merge_base}..${target.head_git_ref}`, "--", relPath],
|
|
508
|
+
{ allowFailure: true },
|
|
509
|
+
).stdout;
|
|
510
|
+
} else if (target.mode === "commit" && target.commit) {
|
|
511
|
+
patch = git(
|
|
512
|
+
target.repo_root,
|
|
513
|
+
["show", "--format=", "--no-ext-diff", "--no-textconv", "--no-color", "-U0", target.commit, "--", relPath],
|
|
514
|
+
{ allowFailure: true },
|
|
515
|
+
).stdout;
|
|
516
|
+
} else if (target.mode === "workspace") {
|
|
517
|
+
const args = resolveRefExists(target.repo_root, "HEAD")
|
|
518
|
+
? ["diff", "--no-ext-diff", "--no-textconv", "--no-color", "-U0", "HEAD", "--", relPath]
|
|
519
|
+
: ["diff", "--cached", "--no-ext-diff", "--no-textconv", "--no-color", "-U0", "--", relPath];
|
|
520
|
+
patch = git(target.repo_root, args, { allowFailure: true }).stdout;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
const addedRanges = [];
|
|
524
|
+
const removedRanges = [];
|
|
525
|
+
const addedText = [];
|
|
526
|
+
const removedText = [];
|
|
527
|
+
|
|
528
|
+
for (const line of patch.split("\n")) {
|
|
529
|
+
const hunk = line.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
|
|
530
|
+
if (hunk) {
|
|
531
|
+
const oldStart = Number(hunk[1]);
|
|
532
|
+
const oldCount = hunk[2] === undefined ? 1 : Number(hunk[2]);
|
|
533
|
+
const newStart = Number(hunk[3]);
|
|
534
|
+
const newCount = hunk[4] === undefined ? 1 : Number(hunk[4]);
|
|
535
|
+
if (newCount > 0) {
|
|
536
|
+
addedRanges.push({ start: newStart, end: newStart + newCount - 1 });
|
|
537
|
+
} else {
|
|
538
|
+
addedRanges.push({ start: Math.max(1, newStart), end: Math.max(1, newStart) });
|
|
539
|
+
}
|
|
540
|
+
if (oldCount > 0) {
|
|
541
|
+
removedRanges.push({ start: oldStart, end: oldStart + oldCount - 1 });
|
|
542
|
+
}
|
|
543
|
+
continue;
|
|
544
|
+
}
|
|
545
|
+
if (line.startsWith("+") && !line.startsWith("+++ ")) {
|
|
546
|
+
addedText.push(line.slice(1));
|
|
547
|
+
} else if (line.startsWith("-") && !line.startsWith("--- ")) {
|
|
548
|
+
removedText.push(line.slice(1));
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
return {
|
|
553
|
+
patch,
|
|
554
|
+
added_lines: addedRanges,
|
|
555
|
+
removed_lines: removedRanges,
|
|
556
|
+
added_text: addedText,
|
|
557
|
+
removed_text: removedText,
|
|
558
|
+
};
|
|
559
|
+
}
|