@lukstei/dsh-client-review-git 0.0.0-stage → 0.2.2-rc.5.4
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 +144 -2
- package/cordis.patch.yml +4 -0
- package/dist/client.js +3378 -0
- package/dist/host.js +1059 -0
- package/lib/typert.host.d.ts +3 -0
- package/lib/typert.host.js +611 -0
- package/lib/typert.remote-client.d.ts +37 -0
- package/lib/typert.remote-client.d.ts.map +1 -0
- package/lib/typert.remote-client.js +505 -0
- package/package.json +156 -3
- package/src/client/FileInspector.tsx +162 -0
- package/src/client/GitDiffPane.tsx +252 -0
- package/src/client/GitReviewCard.tsx +202 -0
- package/src/client/GitReviewRow.tsx +191 -0
- package/src/client/ReviewToolbar.tsx +470 -0
- package/src/client/contract.ts +27 -0
- package/src/client/css.d.ts +5 -0
- package/src/client/index.tsx +230 -0
- package/src/client/review-turn.ts +193 -0
- package/src/client/reviewSelection.ts +14 -0
- package/src/client/useLoad.ts +38 -0
- package/src/client/useReviewViewState.ts +244 -0
- package/src/git-service.ts +845 -0
- package/src/index.ts +67 -0
- package/src/review-tool.ts +85 -0
- package/src/workspace-review-service.ts +400 -0
|
@@ -0,0 +1,845 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { execFile } from "node:child_process";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { lstat, readFile, readlink, realpath, stat } from "node:fs/promises";
|
|
5
|
+
import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
|
|
6
|
+
import { promisify } from "node:util";
|
|
7
|
+
import { branchLabel, snapshotSchema } from "@lukstei/util-review-ui/review";
|
|
8
|
+
import {
|
|
9
|
+
COMMIT_PAGE_SIZE,
|
|
10
|
+
type GitCommit,
|
|
11
|
+
type GitCommitPage,
|
|
12
|
+
type GitComparison,
|
|
13
|
+
type GitDiffView,
|
|
14
|
+
type GitFileContents,
|
|
15
|
+
type GitFileDiff,
|
|
16
|
+
type GitRepository,
|
|
17
|
+
type GitSnapshot,
|
|
18
|
+
MAX_BRANCH_AGE_MS,
|
|
19
|
+
type ResolvedReviewScope,
|
|
20
|
+
type ReviewTarget,
|
|
21
|
+
} from "@lukstei/util-review-ui/types";
|
|
22
|
+
import { z } from "zod";
|
|
23
|
+
|
|
24
|
+
const execute = promisify(execFile);
|
|
25
|
+
const targetSchema = z.object({ branch: z.string().min(1) });
|
|
26
|
+
const statusSchema = z.object({
|
|
27
|
+
stacks: z.array(
|
|
28
|
+
z.object({
|
|
29
|
+
branches: z.array(
|
|
30
|
+
z.object({
|
|
31
|
+
name: z.string(),
|
|
32
|
+
commits: z.array(
|
|
33
|
+
z.object({
|
|
34
|
+
commitId: z.string(),
|
|
35
|
+
message: z.string(),
|
|
36
|
+
authorName: z.string(),
|
|
37
|
+
createdAt: z.string(),
|
|
38
|
+
}),
|
|
39
|
+
),
|
|
40
|
+
}),
|
|
41
|
+
),
|
|
42
|
+
}),
|
|
43
|
+
),
|
|
44
|
+
});
|
|
45
|
+
const diffOptions = [
|
|
46
|
+
"--no-ext-diff",
|
|
47
|
+
"--no-textconv",
|
|
48
|
+
"--no-color",
|
|
49
|
+
"--no-renames",
|
|
50
|
+
"--no-relative",
|
|
51
|
+
];
|
|
52
|
+
|
|
53
|
+
async function git(
|
|
54
|
+
cwd: string,
|
|
55
|
+
args: string[],
|
|
56
|
+
signal: AbortSignal,
|
|
57
|
+
): Promise<string> {
|
|
58
|
+
const { stdout } = await execute(
|
|
59
|
+
"git",
|
|
60
|
+
[
|
|
61
|
+
"--no-optional-locks",
|
|
62
|
+
"-c",
|
|
63
|
+
"core.quotePath=false",
|
|
64
|
+
"-c",
|
|
65
|
+
"diff.autoRefreshIndex=false",
|
|
66
|
+
...args,
|
|
67
|
+
],
|
|
68
|
+
{
|
|
69
|
+
cwd,
|
|
70
|
+
signal,
|
|
71
|
+
maxBuffer: 10 * 1024 * 1024,
|
|
72
|
+
},
|
|
73
|
+
);
|
|
74
|
+
return stdout;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export async function repositoryRoot(
|
|
78
|
+
cwd: string,
|
|
79
|
+
signal: AbortSignal,
|
|
80
|
+
): Promise<string | null> {
|
|
81
|
+
try {
|
|
82
|
+
const { stdout } = await execute("git", ["rev-parse", "--show-toplevel"], {
|
|
83
|
+
cwd,
|
|
84
|
+
signal,
|
|
85
|
+
env: { ...process.env, LC_ALL: "C" },
|
|
86
|
+
});
|
|
87
|
+
return stdout.trim();
|
|
88
|
+
} catch (error) {
|
|
89
|
+
signal.throwIfAborted();
|
|
90
|
+
if (
|
|
91
|
+
error instanceof Error &&
|
|
92
|
+
"stderr" in error &&
|
|
93
|
+
typeof error.stderr === "string" &&
|
|
94
|
+
error.stderr.includes("fatal: not a git repository")
|
|
95
|
+
)
|
|
96
|
+
return null;
|
|
97
|
+
throw error;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function resolveCommit(
|
|
102
|
+
cwd: string,
|
|
103
|
+
ref: string,
|
|
104
|
+
signal: AbortSignal,
|
|
105
|
+
): Promise<string> {
|
|
106
|
+
return (
|
|
107
|
+
await git(
|
|
108
|
+
cwd,
|
|
109
|
+
["rev-parse", "--verify", "--end-of-options", `${ref}^{commit}`],
|
|
110
|
+
signal,
|
|
111
|
+
)
|
|
112
|
+
).trim();
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function head(cwd: string, signal: AbortSignal): Promise<string | null> {
|
|
116
|
+
try {
|
|
117
|
+
return (
|
|
118
|
+
await git(cwd, ["rev-parse", "--verify", "--quiet", "HEAD"], signal)
|
|
119
|
+
).trim();
|
|
120
|
+
} catch (error) {
|
|
121
|
+
// edge case: an unborn branch has an index but no HEAD commit.
|
|
122
|
+
if (error instanceof Error && "code" in error && error.code === 1)
|
|
123
|
+
return null;
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async function targetBranch(cwd: string, signal: AbortSignal): Promise<string> {
|
|
129
|
+
const { stdout } = await execute("but", ["--json", "config", "target"], {
|
|
130
|
+
cwd,
|
|
131
|
+
signal,
|
|
132
|
+
});
|
|
133
|
+
const value: unknown = JSON.parse(stdout);
|
|
134
|
+
return targetSchema.parse(value).branch;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function readStacks(cwd: string, signal: AbortSignal) {
|
|
138
|
+
const { stdout } = await execute("but", ["--json", "status"], {
|
|
139
|
+
cwd,
|
|
140
|
+
signal,
|
|
141
|
+
maxBuffer: 10 * 1024 * 1024,
|
|
142
|
+
});
|
|
143
|
+
const value: unknown = JSON.parse(stdout);
|
|
144
|
+
return statusSchema.parse(value).stacks;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function readButler(cwd: string, signal: AbortSignal) {
|
|
148
|
+
try {
|
|
149
|
+
const commonDir = (
|
|
150
|
+
await git(cwd, ["rev-parse", "--git-common-dir"], signal)
|
|
151
|
+
).trim();
|
|
152
|
+
const marker = resolve(cwd, commonDir, "gitbutler");
|
|
153
|
+
const info = await stat(marker);
|
|
154
|
+
if (!info.isDirectory()) return { kind: "unconfigured" as const };
|
|
155
|
+
} catch {
|
|
156
|
+
signal.throwIfAborted();
|
|
157
|
+
return { kind: "unconfigured" as const };
|
|
158
|
+
}
|
|
159
|
+
try {
|
|
160
|
+
const [target, stacks] = await Promise.all([
|
|
161
|
+
targetBranch(cwd, signal),
|
|
162
|
+
readStacks(cwd, signal),
|
|
163
|
+
]);
|
|
164
|
+
return { kind: "ready" as const, target, stacks };
|
|
165
|
+
} catch (error) {
|
|
166
|
+
signal.throwIfAborted();
|
|
167
|
+
const output =
|
|
168
|
+
error instanceof Error
|
|
169
|
+
? `${error.message} ${"stdout" in error ? String(error.stdout) : ""} ${"stderr" in error ? String(error.stderr) : ""}`
|
|
170
|
+
: String(error);
|
|
171
|
+
const code =
|
|
172
|
+
error instanceof Error && "code" in error ? String(error.code) : "";
|
|
173
|
+
const unconfigured =
|
|
174
|
+
code === "ENOENT" ||
|
|
175
|
+
output.includes("ENOENT") ||
|
|
176
|
+
output.includes("not installed") ||
|
|
177
|
+
output.includes("setup_required") ||
|
|
178
|
+
output.includes("No GitButler project found") ||
|
|
179
|
+
output.includes("not a GitButler project");
|
|
180
|
+
if (unconfigured) return { kind: "unconfigured" as const };
|
|
181
|
+
return {
|
|
182
|
+
kind: "unavailable" as const,
|
|
183
|
+
message: error instanceof Error ? error.message : String(error),
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function branchBase(
|
|
189
|
+
stacks: z.infer<typeof statusSchema>["stacks"],
|
|
190
|
+
ref: string,
|
|
191
|
+
target: string | null,
|
|
192
|
+
): string | null {
|
|
193
|
+
const name = ref.startsWith("refs/heads/")
|
|
194
|
+
? ref.slice("refs/heads/".length)
|
|
195
|
+
: ref;
|
|
196
|
+
for (const { branches } of stacks) {
|
|
197
|
+
const index = branches.findIndex((branch) => branch.name === name);
|
|
198
|
+
// edge case: GitButler orders branches top-first; exclude all changes below the selected branch.
|
|
199
|
+
if (index !== -1 && index + 1 < branches.length)
|
|
200
|
+
return `refs/heads/${branches[index + 1].name}`;
|
|
201
|
+
}
|
|
202
|
+
return target;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export async function readRepository(
|
|
206
|
+
cwd: string,
|
|
207
|
+
signal: AbortSignal,
|
|
208
|
+
): Promise<GitRepository> {
|
|
209
|
+
const [refs, butler] = await Promise.all([
|
|
210
|
+
git(
|
|
211
|
+
cwd,
|
|
212
|
+
[
|
|
213
|
+
"for-each-ref",
|
|
214
|
+
"--sort=refname",
|
|
215
|
+
"--format=%(refname)%09%(symref)%09%(committerdate:unix)",
|
|
216
|
+
"refs/heads",
|
|
217
|
+
"refs/remotes",
|
|
218
|
+
],
|
|
219
|
+
signal,
|
|
220
|
+
),
|
|
221
|
+
readButler(cwd, signal),
|
|
222
|
+
]);
|
|
223
|
+
const entries = refs
|
|
224
|
+
.split("\n")
|
|
225
|
+
.filter(Boolean)
|
|
226
|
+
.map((line) => {
|
|
227
|
+
const [ref, symbolic, committed] = line.split("\t");
|
|
228
|
+
return { ref, symbolic, modifiedAt: Number(committed) * 1000 };
|
|
229
|
+
});
|
|
230
|
+
const defaults = [
|
|
231
|
+
...new Set(
|
|
232
|
+
entries
|
|
233
|
+
.filter(
|
|
234
|
+
(item) =>
|
|
235
|
+
item.ref.startsWith("refs/remotes/") &&
|
|
236
|
+
item.ref.endsWith("/HEAD") &&
|
|
237
|
+
item.symbolic !== "",
|
|
238
|
+
)
|
|
239
|
+
.map((item) => item.symbolic),
|
|
240
|
+
),
|
|
241
|
+
];
|
|
242
|
+
const label = (ref: string) => ref.replace(/^refs\/(?:heads|remotes)\//, "");
|
|
243
|
+
const target = defaults.length === 1 ? defaults[0] : null;
|
|
244
|
+
const baselines = entries
|
|
245
|
+
.filter((item) => item.symbolic === "")
|
|
246
|
+
.map(({ ref }) => ({ ref, label: label(ref) }));
|
|
247
|
+
let managedTarget: string | null = null;
|
|
248
|
+
let gitbutlerError: string | null = null;
|
|
249
|
+
if (butler.kind === "unavailable") {
|
|
250
|
+
gitbutlerError = butler.message;
|
|
251
|
+
} else if (butler.kind === "ready") {
|
|
252
|
+
const exact = baselines.find((entry) => entry.ref === butler.target);
|
|
253
|
+
const matches =
|
|
254
|
+
exact === undefined
|
|
255
|
+
? baselines.filter((entry) => entry.label === butler.target)
|
|
256
|
+
: [exact];
|
|
257
|
+
if (matches.length === 1) managedTarget = matches[0].ref;
|
|
258
|
+
else
|
|
259
|
+
gitbutlerError = `GitButler target "${butler.target}" ${matches.length === 0 ? "was not found" : "is ambiguous"}; configure an explicit branch ref.`;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const branches = entries
|
|
263
|
+
.filter(
|
|
264
|
+
(item) =>
|
|
265
|
+
item.ref.startsWith("refs/heads/") &&
|
|
266
|
+
item.symbolic === "" &&
|
|
267
|
+
Date.now() - item.modifiedAt <= MAX_BRANCH_AGE_MS &&
|
|
268
|
+
(butler.kind !== "ready" ||
|
|
269
|
+
![
|
|
270
|
+
"refs/heads/gitbutler/workspace",
|
|
271
|
+
"refs/heads/gitbutler/target",
|
|
272
|
+
"refs/heads/main",
|
|
273
|
+
].includes(item.ref)),
|
|
274
|
+
)
|
|
275
|
+
.sort((a, b) => b.modifiedAt - a.modifiedAt)
|
|
276
|
+
.map(({ ref, modifiedAt }) => {
|
|
277
|
+
const name = label(ref);
|
|
278
|
+
const managed =
|
|
279
|
+
butler.kind === "ready" &&
|
|
280
|
+
butler.stacks.some((stack) =>
|
|
281
|
+
stack.branches.some((branch) => branch.name === name),
|
|
282
|
+
);
|
|
283
|
+
return {
|
|
284
|
+
ref,
|
|
285
|
+
label: name,
|
|
286
|
+
modifiedAt,
|
|
287
|
+
base:
|
|
288
|
+
managed && butler.kind === "ready"
|
|
289
|
+
? branchBase(butler.stacks, ref, managedTarget)
|
|
290
|
+
: target,
|
|
291
|
+
kind: managed ? ("gitbutler" as const) : ("git" as const),
|
|
292
|
+
};
|
|
293
|
+
});
|
|
294
|
+
return {
|
|
295
|
+
cwd,
|
|
296
|
+
target,
|
|
297
|
+
baselines,
|
|
298
|
+
branches,
|
|
299
|
+
gitbutlerError,
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const commitFormat = "%H%x00%s%x00%an%x00%aI";
|
|
304
|
+
|
|
305
|
+
function parseCommitRecord(entry: string): GitCommit {
|
|
306
|
+
const [sha, subject, author, date] = entry.split("\0");
|
|
307
|
+
assert(sha !== undefined && subject !== undefined);
|
|
308
|
+
assert(author !== undefined && date !== undefined);
|
|
309
|
+
return { sha, subject, author, date };
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
export async function readCommit(
|
|
313
|
+
cwd: string,
|
|
314
|
+
rev: string,
|
|
315
|
+
signal: AbortSignal,
|
|
316
|
+
): Promise<GitCommit> {
|
|
317
|
+
const entry = (
|
|
318
|
+
await git(cwd, ["show", "-s", `--format=${commitFormat}`, rev], signal)
|
|
319
|
+
).trimEnd();
|
|
320
|
+
return parseCommitRecord(entry);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
async function isAncestor(
|
|
324
|
+
cwd: string,
|
|
325
|
+
ancestor: string,
|
|
326
|
+
descendant: string,
|
|
327
|
+
signal: AbortSignal,
|
|
328
|
+
): Promise<boolean> {
|
|
329
|
+
try {
|
|
330
|
+
await git(
|
|
331
|
+
cwd,
|
|
332
|
+
["merge-base", "--is-ancestor", ancestor, descendant],
|
|
333
|
+
signal,
|
|
334
|
+
);
|
|
335
|
+
return true;
|
|
336
|
+
} catch (error) {
|
|
337
|
+
signal.throwIfAborted();
|
|
338
|
+
// edge case: `merge-base --is-ancestor` exits 1 for a rejected pair and uses other codes for real failures.
|
|
339
|
+
if (error instanceof Error && "code" in error && error.code === 1)
|
|
340
|
+
return false;
|
|
341
|
+
throw error;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Turn a repository path and branch/commit request into the scope the review pane renders.
|
|
347
|
+
* @param cwd - repository root, or a directory inside it.
|
|
348
|
+
* @param target - requested repository, branch, and optional commit.
|
|
349
|
+
* @param signal - cancellation for every Git read.
|
|
350
|
+
* @returns the branch scope with a resolved baseline and commit page entry.
|
|
351
|
+
*/
|
|
352
|
+
export async function resolveReviewScope(
|
|
353
|
+
cwd: string,
|
|
354
|
+
target: ReviewTarget,
|
|
355
|
+
signal: AbortSignal,
|
|
356
|
+
): Promise<ResolvedReviewScope> {
|
|
357
|
+
const repository = (
|
|
358
|
+
await git(cwd, ["rev-parse", "--show-toplevel"], signal)
|
|
359
|
+
).trim();
|
|
360
|
+
const repo = await readRepository(repository, signal);
|
|
361
|
+
const known = repo.branches.find(
|
|
362
|
+
(item) => item.ref === target.branch || item.label === target.branch,
|
|
363
|
+
);
|
|
364
|
+
let ref: string;
|
|
365
|
+
let label: string;
|
|
366
|
+
let base: string;
|
|
367
|
+
if (known === undefined) {
|
|
368
|
+
// edge case: branches hidden by the review list's age or GitButler filters still exist in Git.
|
|
369
|
+
ref = target.branch.startsWith("refs/heads/")
|
|
370
|
+
? target.branch
|
|
371
|
+
: `refs/heads/${target.branch}`;
|
|
372
|
+
label = branchLabel(ref);
|
|
373
|
+
try {
|
|
374
|
+
await resolveCommit(repository, ref, signal);
|
|
375
|
+
} catch {
|
|
376
|
+
signal.throwIfAborted();
|
|
377
|
+
const names = repo.branches.slice(0, 20).map((item) => item.label);
|
|
378
|
+
throw new Error(
|
|
379
|
+
`Unknown branch "${target.branch}" in ${repository}. Available: ${names.length === 0 ? "none" : names.join(", ")}`,
|
|
380
|
+
);
|
|
381
|
+
}
|
|
382
|
+
base = repo.target ?? "";
|
|
383
|
+
} else {
|
|
384
|
+
ref = known.ref;
|
|
385
|
+
label = known.label;
|
|
386
|
+
base = known.base ?? repo.target ?? "";
|
|
387
|
+
}
|
|
388
|
+
if (base === "")
|
|
389
|
+
throw new Error(
|
|
390
|
+
`Cannot compare "${label}" without a baseline; set a remote HEAD or choose a baseline in the review toolbar`,
|
|
391
|
+
);
|
|
392
|
+
const scope = {
|
|
393
|
+
kind: "branch" as const,
|
|
394
|
+
repository,
|
|
395
|
+
ref,
|
|
396
|
+
base: { kind: "manual" as const, ref: base },
|
|
397
|
+
};
|
|
398
|
+
if (target.commit === undefined)
|
|
399
|
+
return { ...scope, revision: { kind: "all-commits" } };
|
|
400
|
+
const sha = await resolveCommit(repository, target.commit, signal);
|
|
401
|
+
if (!(await isAncestor(repository, sha, ref, signal)))
|
|
402
|
+
throw new Error(
|
|
403
|
+
`Commit "${target.commit}" is not an ancestor of "${label}"`,
|
|
404
|
+
);
|
|
405
|
+
return {
|
|
406
|
+
...scope,
|
|
407
|
+
revision: {
|
|
408
|
+
kind: "commit",
|
|
409
|
+
commit: await readCommit(repository, sha, signal),
|
|
410
|
+
},
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
export async function listCommits(
|
|
415
|
+
cwd: string,
|
|
416
|
+
branch: string,
|
|
417
|
+
base: string,
|
|
418
|
+
offset: number,
|
|
419
|
+
signal: AbortSignal,
|
|
420
|
+
): Promise<GitCommitPage> {
|
|
421
|
+
assert(Number.isSafeInteger(offset) && offset >= 0, "Invalid commit offset");
|
|
422
|
+
const butler = await readButler(cwd, signal);
|
|
423
|
+
const name = branch.startsWith("refs/heads/")
|
|
424
|
+
? branch.slice("refs/heads/".length)
|
|
425
|
+
: branch;
|
|
426
|
+
if (butler.kind === "ready") {
|
|
427
|
+
const owned = butler.stacks
|
|
428
|
+
.flatMap((stack) => stack.branches)
|
|
429
|
+
.find((item) => item.name === name);
|
|
430
|
+
if (owned !== undefined)
|
|
431
|
+
return {
|
|
432
|
+
commits: owned.commits
|
|
433
|
+
.slice(offset, offset + COMMIT_PAGE_SIZE)
|
|
434
|
+
.map((commit) => ({
|
|
435
|
+
sha: commit.commitId,
|
|
436
|
+
subject: commit.message.split("\n")[0],
|
|
437
|
+
author: commit.authorName,
|
|
438
|
+
date: commit.createdAt,
|
|
439
|
+
})),
|
|
440
|
+
hasMore: owned.commits.length > offset + COMMIT_PAGE_SIZE,
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
const [sha, baseline] = await Promise.all([
|
|
444
|
+
resolveCommit(cwd, branch, signal),
|
|
445
|
+
resolveCommit(cwd, base, signal),
|
|
446
|
+
]);
|
|
447
|
+
const log = await git(
|
|
448
|
+
cwd,
|
|
449
|
+
[
|
|
450
|
+
"log",
|
|
451
|
+
`--format=${commitFormat}`,
|
|
452
|
+
`--skip=${offset}`,
|
|
453
|
+
`--max-count=${COMMIT_PAGE_SIZE + 1}`,
|
|
454
|
+
`${baseline}..${sha}`,
|
|
455
|
+
"--",
|
|
456
|
+
],
|
|
457
|
+
signal,
|
|
458
|
+
);
|
|
459
|
+
const entries = log.trimEnd().split("\n").filter(Boolean);
|
|
460
|
+
return {
|
|
461
|
+
commits: entries.slice(0, COMMIT_PAGE_SIZE).map(parseCommitRecord),
|
|
462
|
+
hasMore: entries.length > COMMIT_PAGE_SIZE,
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
function revisionArgs(snapshot: GitSnapshot): string[] {
|
|
467
|
+
return snapshot.before === null
|
|
468
|
+
? ["diff-tree", "--root", "--no-commit-id", "-r", snapshot.after]
|
|
469
|
+
: ["diff", snapshot.before, snapshot.after];
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
async function fileMetadata(
|
|
473
|
+
cwd: string,
|
|
474
|
+
args: string[],
|
|
475
|
+
signal: AbortSignal,
|
|
476
|
+
): Promise<GitFileDiff[]> {
|
|
477
|
+
const [names, stats] = await Promise.all([
|
|
478
|
+
git(cwd, [...args, ...diffOptions, "--name-status", "-z", "--"], signal),
|
|
479
|
+
git(cwd, [...args, ...diffOptions, "--numstat", "-z", "--"], signal),
|
|
480
|
+
]);
|
|
481
|
+
const counts = new Map(
|
|
482
|
+
stats
|
|
483
|
+
.split("\0")
|
|
484
|
+
.filter(Boolean)
|
|
485
|
+
.map((record) => {
|
|
486
|
+
const first = record.indexOf("\t");
|
|
487
|
+
const second = record.indexOf("\t", first + 1);
|
|
488
|
+
assert(first > 0 && second > first, "Invalid Git numstat record");
|
|
489
|
+
const added = record.slice(0, first);
|
|
490
|
+
const deleted = record.slice(first + 1, second);
|
|
491
|
+
return [
|
|
492
|
+
record.slice(second + 1),
|
|
493
|
+
{
|
|
494
|
+
addedLines: added === "-" ? 0 : Number(added),
|
|
495
|
+
deletedLines: deleted === "-" ? 0 : Number(deleted),
|
|
496
|
+
},
|
|
497
|
+
];
|
|
498
|
+
}),
|
|
499
|
+
);
|
|
500
|
+
const records = names.split("\0");
|
|
501
|
+
assert.equal(records.pop(), "", "Git filenames must be NUL-terminated");
|
|
502
|
+
const diffs: GitFileDiff[] = [];
|
|
503
|
+
for (let i = 0; i < records.length; i += 2) {
|
|
504
|
+
const status = records[i];
|
|
505
|
+
const path = records[i + 1];
|
|
506
|
+
assert.notEqual(
|
|
507
|
+
status,
|
|
508
|
+
"U",
|
|
509
|
+
"Unresolved index conflicts cannot be displayed as a two-sided diff",
|
|
510
|
+
);
|
|
511
|
+
assert(
|
|
512
|
+
["A", "D", "M", "T"].includes(status),
|
|
513
|
+
`Unsupported Git change: ${status}`,
|
|
514
|
+
);
|
|
515
|
+
const count = counts.get(path);
|
|
516
|
+
// edge case: name-status can report stat-only modifications; numstat confirms actual differences without refreshing the index.
|
|
517
|
+
if (count === undefined && status === "M") continue;
|
|
518
|
+
assert(count, "Git change is missing its numstat record");
|
|
519
|
+
diffs.push({
|
|
520
|
+
path,
|
|
521
|
+
status:
|
|
522
|
+
status === "A" ? "added" : status === "D" ? "deleted" : "modified",
|
|
523
|
+
...count,
|
|
524
|
+
});
|
|
525
|
+
}
|
|
526
|
+
return diffs;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
function summary(diffs: GitFileDiff[]) {
|
|
530
|
+
return {
|
|
531
|
+
files: diffs.length,
|
|
532
|
+
added: diffs.reduce((sum, file) => sum + file.addedLines, 0),
|
|
533
|
+
deleted: diffs.reduce((sum, file) => sum + file.deletedLines, 0),
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
function digest(value: string | Buffer): string {
|
|
538
|
+
return createHash("sha256").update(value).digest("hex");
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
async function worktreeFile(repository: string, path: string) {
|
|
542
|
+
const filename = resolve(repository, path);
|
|
543
|
+
const inside = relative(repository, filename);
|
|
544
|
+
assert(
|
|
545
|
+
inside !== "" &&
|
|
546
|
+
!isAbsolute(inside) &&
|
|
547
|
+
inside !== ".." &&
|
|
548
|
+
!inside.startsWith(`..${sep}`),
|
|
549
|
+
"File must stay inside the repository",
|
|
550
|
+
);
|
|
551
|
+
const parent = relative(
|
|
552
|
+
await realpath(repository),
|
|
553
|
+
await realpath(dirname(filename)),
|
|
554
|
+
);
|
|
555
|
+
assert(
|
|
556
|
+
!isAbsolute(parent) && parent !== ".." && !parent.startsWith(`..${sep}`),
|
|
557
|
+
"File parent must stay inside the repository",
|
|
558
|
+
);
|
|
559
|
+
const stat = await lstat(filename);
|
|
560
|
+
// edge case: display a symlink's stored target text, never the target file's contents.
|
|
561
|
+
if (stat.isSymbolicLink())
|
|
562
|
+
return {
|
|
563
|
+
contents: await readlink(filename, { encoding: "buffer" }),
|
|
564
|
+
mode: stat.mode,
|
|
565
|
+
};
|
|
566
|
+
if (!stat.isFile()) return { contents: null, mode: stat.mode };
|
|
567
|
+
return { contents: await readFile(filename), mode: stat.mode };
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
async function workingChanges(
|
|
571
|
+
repository: string,
|
|
572
|
+
kind: "staged" | "unstaged",
|
|
573
|
+
signal: AbortSignal,
|
|
574
|
+
) {
|
|
575
|
+
const index = await git(repository, ["ls-files", "--stage", "-z"], signal);
|
|
576
|
+
const conflicts = await git(
|
|
577
|
+
repository,
|
|
578
|
+
["ls-files", "--unmerged", "-z"],
|
|
579
|
+
signal,
|
|
580
|
+
);
|
|
581
|
+
assert.equal(
|
|
582
|
+
conflicts,
|
|
583
|
+
"",
|
|
584
|
+
"Unresolved index conflicts cannot be displayed as a two-sided diff",
|
|
585
|
+
);
|
|
586
|
+
const before =
|
|
587
|
+
kind === "staged" ? await head(repository, signal) : digest(index);
|
|
588
|
+
const args =
|
|
589
|
+
kind === "staged"
|
|
590
|
+
? ["diff", "--cached", ...(before === null ? [] : [before])]
|
|
591
|
+
: ["diff"];
|
|
592
|
+
const diffs = await fileMetadata(repository, args, signal);
|
|
593
|
+
const contents = new Map<string, Buffer | null>();
|
|
594
|
+
const identities: [string, number, string | null][] = [];
|
|
595
|
+
if (kind === "unstaged") {
|
|
596
|
+
const untracked = (
|
|
597
|
+
await git(
|
|
598
|
+
repository,
|
|
599
|
+
["ls-files", "--others", "--exclude-standard", "-z"],
|
|
600
|
+
signal,
|
|
601
|
+
)
|
|
602
|
+
)
|
|
603
|
+
.split("\0")
|
|
604
|
+
.filter(Boolean);
|
|
605
|
+
const untrackedPaths = new Set(untracked);
|
|
606
|
+
for (const path of untracked)
|
|
607
|
+
diffs.push({ path, status: "added", addedLines: 0, deletedLines: 0 });
|
|
608
|
+
await Promise.all(
|
|
609
|
+
diffs.map(async (file) => {
|
|
610
|
+
if (file.status === "deleted") {
|
|
611
|
+
contents.set(file.path, null);
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
const value = await worktreeFile(repository, file.path);
|
|
615
|
+
contents.set(file.path, value.contents);
|
|
616
|
+
identities.push([
|
|
617
|
+
file.path,
|
|
618
|
+
value.mode,
|
|
619
|
+
value.contents === null ? null : digest(value.contents),
|
|
620
|
+
]);
|
|
621
|
+
const supportsLineCounting =
|
|
622
|
+
value.contents !== null && !value.contents.includes(0);
|
|
623
|
+
if (untrackedPaths.has(file.path) && supportsLineCounting) {
|
|
624
|
+
file.addedLines =
|
|
625
|
+
value.contents.length === 0
|
|
626
|
+
? 0
|
|
627
|
+
: value.contents.toString("utf8").split("\n").length -
|
|
628
|
+
(value.contents.at(-1) === 10 ? 1 : 0);
|
|
629
|
+
}
|
|
630
|
+
}),
|
|
631
|
+
);
|
|
632
|
+
}
|
|
633
|
+
assert.equal(
|
|
634
|
+
await git(repository, ["ls-files", "--stage", "-z"], signal),
|
|
635
|
+
index,
|
|
636
|
+
"Index changed; refresh the comparison",
|
|
637
|
+
);
|
|
638
|
+
const snapshot: GitSnapshot = {
|
|
639
|
+
kind,
|
|
640
|
+
repository,
|
|
641
|
+
before,
|
|
642
|
+
after:
|
|
643
|
+
kind === "staged"
|
|
644
|
+
? digest(index)
|
|
645
|
+
: digest(
|
|
646
|
+
JSON.stringify([
|
|
647
|
+
diffs,
|
|
648
|
+
identities.sort(([a], [b]) => a.localeCompare(b)),
|
|
649
|
+
]),
|
|
650
|
+
),
|
|
651
|
+
};
|
|
652
|
+
return { snapshot, diffs, index, contents };
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
export async function compare(
|
|
656
|
+
cwd: string,
|
|
657
|
+
comparison: GitComparison,
|
|
658
|
+
signal: AbortSignal,
|
|
659
|
+
): Promise<GitDiffView> {
|
|
660
|
+
const repository = (
|
|
661
|
+
await git(cwd, ["rev-parse", "--show-toplevel"], signal)
|
|
662
|
+
).trim();
|
|
663
|
+
if (comparison.kind === "staged" || comparison.kind === "unstaged") {
|
|
664
|
+
const { snapshot, diffs } = await workingChanges(
|
|
665
|
+
repository,
|
|
666
|
+
comparison.kind,
|
|
667
|
+
signal,
|
|
668
|
+
);
|
|
669
|
+
return {
|
|
670
|
+
target:
|
|
671
|
+
comparison.kind === "staged" ? "HEAD → Index" : "Index → Working tree",
|
|
672
|
+
snapshot,
|
|
673
|
+
diffs,
|
|
674
|
+
summary: summary(diffs),
|
|
675
|
+
};
|
|
676
|
+
}
|
|
677
|
+
const branch = await resolveCommit(repository, comparison.branch, signal);
|
|
678
|
+
let before: string | null;
|
|
679
|
+
let after: string;
|
|
680
|
+
let target: string;
|
|
681
|
+
if (comparison.kind === "branch") {
|
|
682
|
+
const base = await resolveCommit(repository, comparison.base, signal);
|
|
683
|
+
before = (
|
|
684
|
+
await git(repository, ["merge-base", base, branch], signal)
|
|
685
|
+
).trim();
|
|
686
|
+
after = branch;
|
|
687
|
+
target = comparison.base;
|
|
688
|
+
} else {
|
|
689
|
+
after = await resolveCommit(repository, comparison.commit, signal);
|
|
690
|
+
await git(
|
|
691
|
+
repository,
|
|
692
|
+
["merge-base", "--is-ancestor", after, branch],
|
|
693
|
+
signal,
|
|
694
|
+
);
|
|
695
|
+
const parents = (
|
|
696
|
+
await git(
|
|
697
|
+
repository,
|
|
698
|
+
["rev-list", "--parents", "-n", "1", after, "--"],
|
|
699
|
+
signal,
|
|
700
|
+
)
|
|
701
|
+
)
|
|
702
|
+
.trim()
|
|
703
|
+
.split(" ");
|
|
704
|
+
// edge case: root commits have no parent; merge commits compare to their first parent.
|
|
705
|
+
before = parents.length === 1 ? null : parents[1];
|
|
706
|
+
target = before === null ? "Initial commit" : before;
|
|
707
|
+
}
|
|
708
|
+
const snapshot: GitSnapshot = { kind: "revision", repository, before, after };
|
|
709
|
+
const diffs = await fileMetadata(repository, revisionArgs(snapshot), signal);
|
|
710
|
+
return { target, snapshot, diffs, summary: summary(diffs) };
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
async function blob(
|
|
714
|
+
repository: string,
|
|
715
|
+
object: string,
|
|
716
|
+
signal: AbortSignal,
|
|
717
|
+
): Promise<Buffer> {
|
|
718
|
+
const { stdout } = await execute("git", ["cat-file", "blob", object], {
|
|
719
|
+
cwd: repository,
|
|
720
|
+
signal,
|
|
721
|
+
encoding: "buffer",
|
|
722
|
+
maxBuffer: 10 * 1024 * 1024,
|
|
723
|
+
});
|
|
724
|
+
return stdout;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
async function revisionFile(
|
|
728
|
+
repository: string,
|
|
729
|
+
revision: string | null,
|
|
730
|
+
path: string,
|
|
731
|
+
signal: AbortSignal,
|
|
732
|
+
): Promise<Buffer | null> {
|
|
733
|
+
if (revision === null) return null;
|
|
734
|
+
const entry = await git(
|
|
735
|
+
repository,
|
|
736
|
+
["--literal-pathspecs", "ls-tree", "-z", revision, "--", path],
|
|
737
|
+
signal,
|
|
738
|
+
);
|
|
739
|
+
if (entry === "") return null;
|
|
740
|
+
const separator = entry.indexOf("\t");
|
|
741
|
+
const [, type, object] = entry.slice(0, separator).split(" ");
|
|
742
|
+
assert.equal(
|
|
743
|
+
entry.slice(separator + 1, -1),
|
|
744
|
+
path,
|
|
745
|
+
"Expected an exact file path",
|
|
746
|
+
);
|
|
747
|
+
assert.equal(type, "blob", "Only file blobs can be displayed");
|
|
748
|
+
return blob(repository, object, signal);
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
export async function readFileContents(
|
|
752
|
+
cwd: string,
|
|
753
|
+
snapshot: GitSnapshot,
|
|
754
|
+
path: string,
|
|
755
|
+
signal: AbortSignal,
|
|
756
|
+
): Promise<GitFileContents> {
|
|
757
|
+
snapshotSchema.parse(snapshot);
|
|
758
|
+
const repository = (
|
|
759
|
+
await git(cwd, ["rev-parse", "--show-toplevel"], signal)
|
|
760
|
+
).trim();
|
|
761
|
+
assert.equal(
|
|
762
|
+
snapshot.repository,
|
|
763
|
+
repository,
|
|
764
|
+
"Comparison belongs to another repository",
|
|
765
|
+
);
|
|
766
|
+
let before: Buffer | null;
|
|
767
|
+
let after: Buffer | null;
|
|
768
|
+
if (snapshot.kind === "revision") {
|
|
769
|
+
const diffs = await fileMetadata(
|
|
770
|
+
repository,
|
|
771
|
+
revisionArgs(snapshot),
|
|
772
|
+
signal,
|
|
773
|
+
);
|
|
774
|
+
assert(
|
|
775
|
+
diffs.some((file) => file.path === path),
|
|
776
|
+
"File must belong to this comparison",
|
|
777
|
+
);
|
|
778
|
+
[before, after] = await Promise.all([
|
|
779
|
+
revisionFile(repository, snapshot.before, path, signal),
|
|
780
|
+
revisionFile(repository, snapshot.after, path, signal),
|
|
781
|
+
]);
|
|
782
|
+
} else {
|
|
783
|
+
// smell: stateless fingerprints rescan changed files per read; per-file identities would reduce work for large reviews.
|
|
784
|
+
const current = await workingChanges(repository, snapshot.kind, signal);
|
|
785
|
+
assert.deepEqual(
|
|
786
|
+
current.snapshot,
|
|
787
|
+
snapshot,
|
|
788
|
+
"Contents changed; refresh the comparison",
|
|
789
|
+
);
|
|
790
|
+
const file = current.diffs.find((file) => file.path === path);
|
|
791
|
+
assert(file, "File must belong to this comparison");
|
|
792
|
+
const entry = current.index
|
|
793
|
+
.split("\0")
|
|
794
|
+
.find((entry) => entry.slice(entry.indexOf("\t") + 1) === path);
|
|
795
|
+
let staged: Buffer | null = null;
|
|
796
|
+
if (entry !== undefined) {
|
|
797
|
+
const [mode, object] = entry.slice(0, entry.indexOf("\t")).split(" ");
|
|
798
|
+
if (mode === "160000")
|
|
799
|
+
return {
|
|
800
|
+
kind: "unavailable",
|
|
801
|
+
message: "Submodule change; no text display or line comments.",
|
|
802
|
+
};
|
|
803
|
+
staged = await blob(repository, object, signal);
|
|
804
|
+
}
|
|
805
|
+
if (snapshot.kind === "staged") {
|
|
806
|
+
before = await revisionFile(repository, snapshot.before, path, signal);
|
|
807
|
+
after = staged;
|
|
808
|
+
} else {
|
|
809
|
+
before = staged;
|
|
810
|
+
const content = current.contents.get(path);
|
|
811
|
+
assert(
|
|
812
|
+
content !== undefined,
|
|
813
|
+
"Working-tree content must belong to this comparison",
|
|
814
|
+
);
|
|
815
|
+
if (content === null && file.status !== "deleted")
|
|
816
|
+
return {
|
|
817
|
+
kind: "unavailable",
|
|
818
|
+
message: "Only files and symlinks can be displayed.",
|
|
819
|
+
};
|
|
820
|
+
after = content;
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
if (
|
|
824
|
+
[before, after]
|
|
825
|
+
.filter((content) => content !== null)
|
|
826
|
+
.some((content) => content.includes(0))
|
|
827
|
+
)
|
|
828
|
+
return {
|
|
829
|
+
kind: "unavailable",
|
|
830
|
+
message: "Files containing NUL bytes cannot be displayed or annotated.",
|
|
831
|
+
};
|
|
832
|
+
try {
|
|
833
|
+
const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
834
|
+
return {
|
|
835
|
+
kind: "text",
|
|
836
|
+
before: before === null ? null : decoder.decode(before),
|
|
837
|
+
after: after === null ? null : decoder.decode(after),
|
|
838
|
+
};
|
|
839
|
+
} catch {
|
|
840
|
+
return {
|
|
841
|
+
kind: "unavailable",
|
|
842
|
+
message: "Only UTF-8 text files can be displayed.",
|
|
843
|
+
};
|
|
844
|
+
}
|
|
845
|
+
}
|