Repository navigation
Expand file tree
/
Copy pathdiff-engine.ts
More file actions
1009 lines (939 loc) · 33.8 KB
/
Copy pathdiff-engine.ts
File metadata and controls
1009 lines (939 loc) · 33.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { createHash } from 'crypto';
import { promises as fs } from 'fs';
import path from 'path';
import type { GitMutationResult } from '../../../common/git.js';
import { mapWithConcurrencyResult } from '../../common/concurrency.js';
import { parseNumstatZ, parseUnmergedPaths } from './diff-file-list.js';
import { GitDomainError } from './git-domain-error.js';
import { assertGitWorkingPath } from './operation-context.js';
import { chunkGitPathspecs, literalGitPathspec } from './pathspecs.js';
import {
changeKindForStatus,
hasIndexChange,
hasWorkTreeChange,
parsePorcelainV1Z,
} from './porcelain-status.js';
import { categoryForPath } from './review-patch.js';
import {
GitReviewDocumentRegistry,
registeredWorkbenchFile,
} from './review-document-registry.js';
import { createReviewDocumentOperations } from './review-document-service.js';
import { measureGitReviewPhaseSync } from './review-performance.js';
import {
assertGitRepository,
isBinaryFile,
readGitBlobPrefix,
readOnlyGitOptions,
resolvePathWithinProject,
runGit,
runGitWithStdin,
} from './run.js';
import type {
ChangeEntry,
ChangeFacet,
ChangesTreeResult,
CompatibleTreeFields,
DiffStats,
GitReviewDocumentSummary,
GitReviewFileSummary,
GitReviewMode,
GitWorkbenchSnapshotOptions,
GitWorkbenchSnapshotResponse,
HunkHeaderResult,
HunkLineCounts,
NumstatMap,
ParsedPatch,
PatchHunk,
PorcelainStatusEntry,
StageHunkOptions,
StageSelectionOptions,
TransformedHunk,
TreeMap,
TreeNode
} from './types.js';
import {
GIT_REVIEW_DOCUMENT_LIMITS
} from './types.js';
import { captureWorkingPathTokensFromObservation } from './working-path-token.js';
import {
captureWorkingTreeObservation,
getWorkingTreeFingerprint,
GitWorkingTreeNotRepositoryError,
parseLsFilesStageZ,
type GitWorkingTreeObservation
} from './working-tree-observation.js';
const GIT_EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
function buildFacet(
status: string,
filePath: string,
stats?: DiffStats,
originalPath?: string,
): ChangeFacet | undefined {
if (!status || status === ' ' || status === '!') return undefined;
return {
status,
changeKind: changeKindForStatus(status),
stats: stats || { additions: 0, deletions: 0 },
...(originalPath ? { originalPath } : {}),
category: categoryForPath(filePath),
};
}
function compatibleTreeFields(stagedFacet?: ChangeFacet, unstagedFacet?: ChangeFacet): CompatibleTreeFields {
const primaryFacet = unstagedFacet ?? stagedFacet;
const stats = compatibleStats(stagedFacet, unstagedFacet);
return {
staged: Boolean(stagedFacet),
hasUnstaged: Boolean(unstagedFacet),
changeKind: primaryFacet?.changeKind,
additions: stats.additions,
deletions: stats.deletions,
category: primaryFacet?.category,
};
}
function compatibleStats(stagedFacet?: ChangeFacet, unstagedFacet?: ChangeFacet): DiffStats {
return unstagedFacet?.stats ?? stagedFacet?.stats ?? { additions: 0, deletions: 0 };
}
function buildChangeEntry(
statusEntry: PorcelainStatusEntry,
workingStats: NumstatMap,
cachedStats: NumstatMap,
): ChangeEntry {
const filePath = statusEntry.path.replace(/\/+$/g, '');
const stagedFacet = hasIndexChange(statusEntry.indexStatus)
? buildFacet(statusEntry.indexStatus, filePath, cachedStats[filePath], statusEntry.originalPath)
: undefined;
const unstagedStatus = statusEntry.indexStatus === '?' ? '?' : statusEntry.workTreeStatus;
const unstagedFacet = hasWorkTreeChange(unstagedStatus)
? buildFacet(unstagedStatus, filePath, workingStats[filePath], statusEntry.originalPath)
: undefined;
return {
path: filePath,
indexStatus: statusEntry.indexStatus,
workTreeStatus: statusEntry.workTreeStatus,
stagedFacet,
unstagedFacet,
};
}
function mapTreeToArray(map: TreeMap): TreeNode[] {
const result: TreeNode[] = [];
for (const [, node] of map) {
const entry: TreeNode = { ...node, children: node.children instanceof Map ? mapTreeToArray(node.children) : node.children };
result.push(entry);
}
result.sort((a, b) => {
if (a.kind !== b.kind) return a.kind === 'directory' ? -1 : 1;
return a.name.localeCompare(b.name);
});
return result;
}
function buildTreeFromStatusEntries(
statusEntries: PorcelainStatusEntry[],
workingStats: NumstatMap,
cachedStats: NumstatMap,
hasCommits: boolean,
statsState: ChangesTreeResult['statsState'],
): ChangesTreeResult {
const entries = statusEntries
.map((entry) => buildChangeEntry(entry, workingStats, cachedStats))
.filter((entry) => entry.path);
return buildTreeFromChangeEntries(entries, hasCommits, statsState);
}
function buildTreeFromChangeEntries(
entries: ChangeEntry[],
hasCommits: boolean,
statsState: ChangesTreeResult['statsState'],
): ChangesTreeResult {
const rootMap: TreeMap = new Map();
for (const entry of entries) {
const segments = entry.path.split('/').filter(Boolean);
if (segments.length === 0) continue;
let currentLevel = rootMap;
for (let i = 0; i < segments.length; i++) {
const segment = segments[i];
const isLastSegment = i === segments.length - 1;
if (!currentLevel.has(segment)) {
if (isLastSegment) {
const compatible = compatibleTreeFields(entry.stagedFacet, entry.unstagedFacet);
currentLevel.set(segment, {
path: entry.path,
name: segment,
kind: 'file',
indexStatus: entry.indexStatus,
workTreeStatus: entry.workTreeStatus,
stagedFacet: entry.stagedFacet,
unstagedFacet: entry.unstagedFacet,
...compatible,
});
} else {
currentLevel.set(segment, {
path: segments.slice(0, i + 1).join('/'),
name: segment,
kind: 'directory',
indexStatus: ' ',
workTreeStatus: ' ',
staged: false,
hasUnstaged: false,
additions: 0,
deletions: 0,
children: new Map(),
});
}
}
const node = currentLevel.get(segment);
if (!node) continue;
if (!isLastSegment && node.kind === 'directory' && node.children instanceof Map) {
const stats = compatibleStats(entry.stagedFacet, entry.unstagedFacet);
if (entry.stagedFacet) {
node.staged = true;
node.stagedFacet = node.stagedFacet || entry.stagedFacet;
node.indexStatus = 'M';
}
if (entry.unstagedFacet) {
node.hasUnstaged = true;
node.unstagedFacet = node.unstagedFacet || entry.unstagedFacet;
node.workTreeStatus = 'M';
}
node.changeKind = node.unstagedFacet?.changeKind ?? node.stagedFacet?.changeKind;
node.additions = (node.additions || 0) + stats.additions;
node.deletions = (node.deletions || 0) + stats.deletions;
currentLevel = node.children;
}
}
}
return { root: mapTreeToArray(rootMap), hasCommits, statsState };
}
// Partial-staging implementation follows lazygit's patch-transform approach.
// See https://github.com/jesseduffield/lazygit (pkg/commands/patch/).
//
// Key design decisions (lazygit-aligned):
//
// 1. The patch is always built from the SAME diff the UI displayed. The
// frontend passes viewMode and contextLines so the server reproduces
// the exact diff, ensuring line indices match.
//
// 2. For staging (forward apply): unselected deletions become context
// lines (the old line stays in the index unchanged). Unselected
// additions are dropped entirely (they won't appear in the index).
//
// 3. For unstaging (reverse apply): the inverse -- unselected additions
// become context, unselected deletions are dropped.
//
// 4. Hunk headers (@@ lines) are always recomputed from the transformed
// body rather than parsed from the original, avoiding count drift.
//
// 5. newStart is computed as oldStart + cumulativeOffset where the offset
// tracks the net line-count delta from prior transformed hunks.
//
// 6. The patch is applied via `git apply --cached` (staging) or
// `git apply --cached --reverse` (unstaging).
// Replaces full diff header with minimal a/b paths, matching lazygit's
// FileNameOverride approach. Prevents failures when partially staging
// deleted files or files with mode changes.
function simplifyDiffHeader(filePath: string): string[] {
return [
`--- a/${filePath}`,
`+++ b/${filePath}`,
];
}
function stagingDiffHeader(file: string, parsed: ParsedPatch, mode: 'stage' | 'unstage'): string[] {
if (mode === 'stage') {
const fileSectionCount = parsed.header.filter((line) => line.startsWith('diff --git ')).length;
const createsFile = parsed.header.some((line) => line.startsWith('new file mode '));
if (fileSectionCount === 1 && createsFile) return parsed.header;
}
return simplifyDiffHeader(file);
}
// Strips the trailing empty element that `split('\n')` produces from a
// newline-terminated diff -- without this, the last hunk would contain a
// spurious empty line that corrupts line counts in buildHunkHeader.
function parsePatch(patchText: string): ParsedPatch {
const allLines = patchText.split('\n');
if (allLines.length > 0 && allLines[allLines.length - 1] === '') {
allLines.pop();
}
const header: string[] = [];
const hunks: PatchHunk[] = [];
let current: PatchHunk | null = null;
for (const line of allLines) {
if (line.startsWith('diff --git ')) {
if (current) hunks.push(current);
current = null;
header.push(line);
continue;
}
if (!current && (line.startsWith('index ') ||
line.startsWith('new file') || line.startsWith('deleted file') ||
line.startsWith('---') || line.startsWith('+++') ||
line.startsWith('old mode') || line.startsWith('new mode'))) {
header.push(line);
continue;
}
if (line.startsWith('@@')) {
if (current) hunks.push(current);
current = { rawHeader: line, lines: [] };
continue;
}
if (current) {
current.lines.push(line);
}
}
if (current) hunks.push(current);
return { header, hunks };
}
// Transforms hunk body lines for partial staging/unstaging.
//
// For each line in the hunk body, decides whether to keep, convert to
// context, or drop based on whether its diffLineIndex is in selectedSet.
//
// Forward staging (reverse=false):
// - Selected lines: kept as-is (both + and -)
// - Unselected `-` lines: converted to context (` ` prefix). The line
// exists in the old file and we're NOT removing it from the index.
// - Unselected `+` lines: dropped entirely. We're NOT adding them.
//
// Reverse staging / unstaging (reverse=true):
// - Selected lines: kept as-is
// - Unselected `+` lines: converted to context. In reverse mode,
// additions in the cached diff represent lines IN the index that we
// want to keep, so they become context.
// - Unselected `-` lines: dropped. In reverse mode, deletions represent
// lines NOT in the index; dropping them is a no-op.
//
// `\ No newline at end of file` markers are dropped when their preceding
// change line was dropped, preserving patch validity.
function transformHunkLines(
bodyLines: string[],
selectedSet: Set<number>,
startIndex: number,
reverse: boolean,
): TransformedHunk {
const result: string[] = [];
let idx = startIndex;
let lastLineDropped = false;
for (const line of bodyLines) {
if (line.startsWith('\\')) {
// Keep the no-newline marker only if we kept the preceding change line.
if (!lastLineDropped) result.push(line);
continue;
}
const isAdd = line.startsWith('+');
const isDel = line.startsWith('-');
if (!isAdd && !isDel) {
// Context line: always preserved in the transformed patch.
result.push(line);
idx++;
lastLineDropped = false;
continue;
}
const selected = selectedSet.has(idx);
idx++;
if (selected) {
result.push(line);
lastLineDropped = false;
} else if (reverse ? isAdd : isDel) {
// Unselected deletion (forward) or addition (reverse): convert to
// context. This preserves the line in the index unchanged.
result.push(' ' + line.substring(1));
lastLineDropped = false;
} else {
// Unselected addition (forward) or deletion (reverse): drop from
// the patch entirely. This omits the change from the index.
lastLineDropped = true;
}
}
return { lines: result, nextIndex: idx };
}
// Returns true when a transformed hunk body contains real changes.
function hunkHasChanges(bodyLines: string[]): boolean {
return bodyLines.some((l) => l.startsWith('+') || l.startsWith('-'));
}
// Counts old-side and new-side lines in a hunk body. Context lines count
// toward both sides. `\` markers are ignored. This always recomputes from
// the actual body content rather than trusting the original @@ header,
// because transformHunkLines may have changed the line composition.
function countHunkLines(bodyLines: string[]): HunkLineCounts {
let oldCount = 0;
let newCount = 0;
for (const l of bodyLines) {
if (l.startsWith('\\')) continue;
if (l.startsWith('-')) oldCount++;
else if (l.startsWith('+')) newCount++;
else { oldCount++; newCount++; }
}
return { oldCount, newCount };
}
// Builds a corrected @@ hunk header. `startOffset` is the cumulative
// delta (newCount - oldCount) from all prior hunks. newStart is computed
// as oldStart + startOffset, with an additional adjustment when a side
// transitions to/from zero length (matching lazygit's hunk header logic).
function buildHunkHeader(rawHeader: string, bodyLines: string[], startOffset: number): HunkHeaderResult {
const match = rawHeader.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@(.*)$/);
if (!match) return { header: rawHeader, nextOffset: startOffset };
const oldStart = parseInt(match[1], 10);
const trailing = match[3] || '';
const { oldCount, newCount } = countHunkLines(bodyLines);
// When a side is zero-length (e.g. new file or deleted file), the start
// position needs an extra +1/-1 adjustment per unified diff convention.
let zeroLengthAdj = 0;
if (oldCount === 0) zeroLengthAdj = 1;
else if (newCount === 0) zeroLengthAdj = -1;
const newStart = oldStart + startOffset + zeroLengthAdj;
const nextOffset = startOffset + (newCount - oldCount);
return {
header: `@@ -${oldStart},${oldCount} +${newStart},${newCount} @@${trailing}`,
nextOffset,
};
}
function hashString(input: string): string {
return createHash('sha256').update(input).digest('hex').slice(0, 16);
}
async function hashFilePrefix(filePath: string): Promise<string> {
await assertGitWorkingPath(filePath);
const handle = await fs.open(filePath, 'r');
try {
const buffer = Buffer.alloc(65_536);
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
return createHash('sha256').update(buffer.subarray(0, bytesRead)).digest('hex').slice(0, 16);
} finally {
await handle.close();
}
}
async function indexFingerprint(projectPath: string, file: string, signal?: AbortSignal): Promise<string> {
try {
const { stdout } = await runGit(
projectPath,
['ls-files', '-s', '--', literalGitPathspec(file)],
readOnlyGitOptions({ signal }),
);
return stdout.trim();
} catch {
return '';
}
}
async function headObjectFingerprint(projectPath: string, file: string, signal?: AbortSignal): Promise<string> {
try {
const { stdout } = await runGit(
projectPath,
['rev-parse', `HEAD:${file}`],
readOnlyGitOptions({ signal }),
);
return stdout.trim();
} catch {
return '';
}
}
async function worktreeFingerprint(
projectPath: string,
file: string,
options: { includeContentHash?: boolean } = {},
): Promise<string> {
try {
const filePath = resolvePathWithinProject(projectPath, file);
await assertGitWorkingPath(filePath);
const stats = await fs.stat(filePath);
if (!stats.isFile()) return `not-file:${stats.size}:${stats.mtimeMs}`;
const parts: Array<string | number> = [
'file',
stats.size,
Math.trunc(stats.mtimeMs),
];
if (options.includeContentHash) parts.push(await hashFilePrefix(filePath));
return parts.join(':');
} catch {
return 'missing';
}
}
interface BatchedFingerprintInputs {
indexEntriesByPath: Map<string, string>;
headEntriesByPath: Map<string, string>;
}
function parseLsTreeZ(output: string): Map<string, string> {
const map = new Map<string, string>();
for (const token of output.split('\0')) {
if (!token) continue;
const tabIndex = token.indexOf('\t');
if (tabIndex < 0) continue;
const filePath = token.slice(tabIndex + 1);
const objectId = token.slice(0, tabIndex).split(' ')[2] ?? '';
if (filePath && objectId) map.set(filePath, objectId);
}
return map;
}
async function loadBatchedFingerprintInputs(
projectPath: string,
files: TreeNode[],
existingIndexEntries: Map<string, string> | undefined,
signal?: AbortSignal,
): Promise<BatchedFingerprintInputs> {
const paths = files.map((file) => file.path);
const indexEntriesByPath = new Map(existingIndexEntries);
const headEntriesByPath = new Map<string, string>();
for (const chunk of chunkGitPathspecs(paths)) {
const [indexResult, headResult] = await Promise.allSettled([
existingIndexEntries
? Promise.resolve({ stdout: '' })
: runGit(
projectPath,
['ls-files', '-s', '-z', '--', ...chunk],
readOnlyGitOptions({ signal }),
),
runGit(projectPath, ['ls-tree', '-rz', 'HEAD', '--', ...chunk], readOnlyGitOptions({ signal })),
]);
if (!existingIndexEntries && indexResult.status === 'fulfilled') {
for (const [filePath, entry] of parseLsFilesStageZ(indexResult.value.stdout)) {
indexEntriesByPath.set(filePath, entry);
}
}
if (headResult.status === 'fulfilled') {
for (const [filePath, entry] of parseLsTreeZ(headResult.value.stdout)) {
headEntriesByPath.set(filePath, entry);
}
}
}
return { indexEntriesByPath, headEntriesByPath };
}
async function buildSummaryBodyFingerprint(
projectPath: string,
file: string,
statusEntry: PorcelainStatusEntry,
mode: GitReviewMode,
inputs: BatchedFingerprintInputs,
): Promise<string> {
const base = [
mode,
file,
statusEntry.originalPath ?? '',
statusEntry.indexStatus,
statusEntry.workTreeStatus,
];
if (mode === 'staged') {
base.push(inputs.indexEntriesByPath.get(file) ?? '');
} else if (statusEntry.workTreeStatus === 'D') {
base.push(inputs.indexEntriesByPath.get(file) ?? '');
base.push(inputs.headEntriesByPath.get(file) ?? '');
} else {
base.push(await worktreeFingerprint(projectPath, file, { includeContentHash: true }));
}
return hashString(base.join('\x1f'));
}
async function buildBodyFingerprint(
projectPath: string,
file: string,
statusEntry: PorcelainStatusEntry,
mode: GitReviewMode,
signal?: AbortSignal,
): Promise<string> {
const base = [
mode,
file,
statusEntry.originalPath ?? '',
statusEntry.indexStatus,
statusEntry.workTreeStatus,
];
if (mode === 'staged') {
base.push(await indexFingerprint(projectPath, file, signal));
} else if (statusEntry.workTreeStatus === 'D') {
base.push(await indexFingerprint(projectPath, file, signal));
base.push(await headObjectFingerprint(projectPath, file, signal));
} else {
base.push(await worktreeFingerprint(projectPath, file, { includeContentHash: true }));
}
return hashString(base.join('\x1f'));
}
async function isBinaryWorktreeFile(projectPath: string, file: string): Promise<boolean> {
try {
const filePath = resolvePathWithinProject(projectPath, file);
await assertGitWorkingPath(filePath);
const stats = await fs.stat(filePath);
return stats.isFile() && await isBinaryFile(filePath);
} catch {
return false;
}
}
async function isBinaryIndexBlobPrefix(
projectPath: string,
file: string,
signal?: AbortSignal,
): Promise<boolean> {
try { return (await readGitBlobPrefix(projectPath, `:${file}`, signal)).includes(0x00); }
catch { return false; }
}
async function isSummaryBinaryFile(
projectPath: string,
file: string,
statusEntry: PorcelainStatusEntry,
mode: GitReviewMode,
stats: DiffStats,
signal?: AbortSignal,
): Promise<boolean> {
if (stats.isBinary) return true;
const isAmbiguousChange = stats.additions === 0 && stats.deletions === 0;
if (mode === 'staged') {
return statusEntry.indexStatus !== 'D' && isAmbiguousChange
? isBinaryIndexBlobPrefix(projectPath, file, signal)
: false;
}
if (statusEntry.workTreeStatus === 'D') return false;
const isUntracked = statusEntry.indexStatus === '?' || statusEntry.workTreeStatus === '?';
return (isUntracked || isAmbiguousChange) && await isBinaryWorktreeFile(projectPath, file);
}
function flattenFileNodes(nodes: TreeNode[]): TreeNode[] {
const files: TreeNode[] = [];
for (const node of nodes) {
if (node.kind === 'file') {
files.push(node);
continue;
}
if (Array.isArray(node.children)) files.push(...flattenFileNodes(node.children));
}
return files;
}
function facetForReviewMode(node: TreeNode, mode: GitReviewMode): ChangeFacet | undefined {
return mode === 'staged' ? node.stagedFacet : node.unstagedFacet;
}
async function summarizeReviewFile(
projectPath: string,
node: TreeNode,
mode: GitReviewMode,
fingerprintInputs?: BatchedFingerprintInputs,
unmergedPaths: ReadonlySet<string> = new Set(),
signal?: AbortSignal,
): Promise<GitReviewFileSummary | null> {
const facet = facetForReviewMode(node, mode);
if (!facet) return null;
const statusEntry: PorcelainStatusEntry = {
path: node.path,
originalPath: facet.originalPath,
indexStatus: node.indexStatus ?? ' ',
workTreeStatus: node.workTreeStatus ?? ' ',
};
const stats = facet.stats ?? { additions: 0, deletions: 0 };
const category = facet.category ?? node.category ?? categoryForPath(node.path);
const isBinary = await isSummaryBinaryFile(projectPath, node.path, statusEntry, mode, stats, signal);
const estimatedRows = Math.max(1, stats.additions + stats.deletions + 1);
const isConflicted = unmergedPaths.has(node.path);
const exceedsRowLimit = !isBinary && estimatedRows > GIT_REVIEW_DOCUMENT_LIMITS.maxFileRows;
const isTooLarge = isConflicted || exceedsRowLimit;
const bodyFingerprint = fingerprintInputs
? await buildSummaryBodyFingerprint(projectPath, node.path, statusEntry, mode, fingerprintInputs)
: await buildBodyFingerprint(projectPath, node.path, statusEntry, mode, signal);
return {
path: node.path,
...(facet.originalPath ? { originalPath: facet.originalPath } : {}),
indexStatus: statusEntry.indexStatus,
workTreeStatus: statusEntry.workTreeStatus,
category: isBinary ? 'binary' : isTooLarge ? 'large' : category,
additions: stats.additions,
deletions: stats.deletions,
estimatedRows,
bodyState: isBinary ? 'binary' : isTooLarge ? 'too-large' : 'unloaded',
bodyFingerprint,
isGenerated: category === 'generated',
isBinary,
isTooLarge,
...(isBinary ? { limitReason: 'binary' as const, limitMessage: 'Binary diff is not available.' } : {}),
...(isConflicted
? {
limitReason: 'unsupported-file-kind' as const,
limitMessage: 'Resolve this conflict before reviewing its diff.',
}
: isTooLarge
? {
limitReason: 'file-too-many-rows' as const,
limitMessage: `Diff exceeds ${GIT_REVIEW_DOCUMENT_LIMITS.maxFileRows} estimated rows.`,
}
: {}),
};
}
function reviewDocumentId(
projectPath: string,
mode: GitReviewMode,
context: number,
files: GitReviewFileSummary[],
): string {
return hashString([
projectPath,
mode,
context,
...files.map((file) => `${file.path}:${file.bodyFingerprint}`),
].join('\x1f'));
}
async function buildReviewDocumentSummaryFromTree({
projectPath,
mode,
context,
treeRoot,
indexEntriesByPath,
unmergedPaths,
signal,
}: {
projectPath: string;
mode: GitReviewMode;
context: number;
treeRoot: TreeNode[];
indexEntriesByPath?: Map<string, string>;
unmergedPaths?: ReadonlySet<string>;
signal?: AbortSignal;
}): Promise<GitReviewDocumentSummary> {
const effectiveMode = mode === 'staged' ? 'staged' : 'working';
const allFiles = flattenFileNodes(treeRoot);
const relevantFiles = allFiles.filter((node) => Boolean(facetForReviewMode(node, effectiveMode)));
const limitedFiles = relevantFiles.slice(0, GIT_REVIEW_DOCUMENT_LIMITS.maxSummaryFiles);
const fingerprintInputs = await loadBatchedFingerprintInputs(
projectPath,
limitedFiles,
indexEntriesByPath,
signal,
);
const summaries = (await mapWithConcurrencyResult(
limitedFiles,
GIT_REVIEW_DOCUMENT_LIMITS.bodyConcurrency,
(node) =>
summarizeReviewFile(
projectPath,
node,
effectiveMode,
fingerprintInputs,
unmergedPaths,
signal,
),
)).filter((summary): summary is GitReviewFileSummary => Boolean(summary));
const documentId = reviewDocumentId(projectPath, effectiveMode, context, summaries);
return {
documentId,
project: projectPath,
mode: effectiveMode,
context,
files: summaries,
limits: GIT_REVIEW_DOCUMENT_LIMITS,
...(relevantFiles.length > limitedFiles.length
? {
collectionLimit: {
reason: 'collection-too-many-files' as const,
message: `Showing ${limitedFiles.length} of ${relevantFiles.length} changed files.`,
visibleFiles: limitedFiles.length,
totalFilesKnown: relevantFiles.length,
},
}
: {}),
};
}
function chooseSelectedFile(files: GitReviewFileSummary[], selectedFile?: string | null): string | null {
if (selectedFile && files.some((file) => file.path === selectedFile)) return selectedFile;
return files[0]?.path ?? null;
}
function chooseFirstBodyCandidates(
files: GitReviewFileSummary[],
selectedFile: string | null,
count: number,
): string[] {
const candidates: string[] = [];
const seen = new Set<string>();
function add(filePath: string | null): void {
if (!filePath || seen.has(filePath) || candidates.length >= count) return;
const file = files.find((candidate) => candidate.path === filePath);
if (!file || file.bodyState !== 'unloaded') return;
seen.add(filePath);
candidates.push(filePath);
}
add(selectedFile);
for (const file of files) add(file.path);
return candidates;
}
export function notRepositorySnapshot(projectPath: string): GitWorkbenchSnapshotResponse {
return {
status: 'not-git-repository',
project: projectPath,
target: null,
tree: null,
reviewSummary: null,
selectedFile: null,
firstBodyCandidates: [],
message: 'Git is not initialized in this directory.',
};
}
async function getWorkbenchSnapshot({
projectPath,
mode,
context,
selectedFile,
bodyCandidateCount = 8,
trace,
metrics,
signal,
}: GitWorkbenchSnapshotOptions, registry: GitReviewDocumentRegistry): Promise<GitWorkbenchSnapshotResponse> {
try {
await fs.access(projectPath);
} catch {
return notRepositorySnapshot(projectPath);
}
let observation: GitWorkingTreeObservation;
try {
observation = await captureWorkingTreeObservation({ projectPath, trace, signal });
} catch (error) {
if (error instanceof GitWorkingTreeNotRepositoryError) {
return notRepositorySnapshot(projectPath);
}
throw error;
}
const effectiveMode = mode === 'staged' ? 'staged' : 'working';
const { repoRoot, branch, head, statusEntries } = observation;
const hasCommits = Boolean(head);
const workingStats = parseNumstatZ(observation.workingStatsOutput);
const cachedStats = parseNumstatZ(observation.cachedStatsOutput);
const tree = buildTreeFromStatusEntries(statusEntries, workingStats, cachedStats, hasCommits, 'loaded');
const reviewSummary = await buildReviewDocumentSummaryFromTree({
projectPath,
mode: effectiveMode,
context,
treeRoot: tree.root,
indexEntriesByPath: observation.indexEntriesByPath,
unmergedPaths: parseUnmergedPaths(observation.unmergedOutput),
signal,
});
const workingPathTokens = await captureWorkingPathTokensFromObservation(
repoRoot,
reviewSummary.files.flatMap((file) =>
file.originalPath ? [file.path, file.originalPath] : [file.path],
),
observation,
{ scope: effectiveMode === 'staged' ? 'index' : 'working-tree' },
signal,
);
const document = measureGitReviewPhaseSync(metrics, 'document-register', () =>
registry.register({
sourceCacheKey: `workbench:${repoRoot}:${effectiveMode}:${context}`,
projectPath,
repoRoot,
context,
source: {
kind: 'workbench',
mode: effectiveMode,
stagedBaseHash: head || GIT_EMPTY_TREE,
fingerprint: observation.fingerprint,
},
files: reviewSummary.files.map(registeredWorkbenchFile),
workingPathTokens,
}));
const registeredSummary = { ...reviewSummary, documentId: document.id };
const selected = chooseSelectedFile(registeredSummary.files, selectedFile);
return {
status: 'ready',
project: projectPath,
target: {
projectPath,
repoRoot,
worktreePath: repoRoot,
label: path.basename(projectPath) || projectPath,
branch,
source: 'chat-project',
},
tree: {
root: tree.root,
hasCommits,
statsState: 'loaded',
},
reviewSummary: registeredSummary,
selectedFile: selected,
firstBodyCandidates: chooseFirstBodyCandidates(
registeredSummary.files,
selected,
Math.max(0, Math.min(bodyCandidateCount, GIT_REVIEW_DOCUMENT_LIMITS.maxBodyBatchFiles)),
),
snapshotId: document.id,
workbenchFingerprint: observation.fingerprint,
};
}
async function stageSelection({
projectPath,
file,
mode,
selection,
}: StageSelectionOptions, patchText: string): Promise<GitMutationResult> {
await assertGitRepository(projectPath);
const reverse = mode === 'unstage';
if (!patchText.trim()) {
throw new GitDomainError('INVALID_INPUT', 'No diff is available for the requested file.');
}
const selectedSet = new Set(selection.lineIndices);
const parsed = parsePatch(patchText);
const outputLines = [...stagingDiffHeader(file, parsed, mode)];
const headerLength = outputLines.length;
let startOffset = 0;
let diffLineIndex = 0;
for (const hunk of parsed.hunks) {
const { lines: bodyLines, nextIndex } = transformHunkLines(
hunk.lines, selectedSet, diffLineIndex, reverse,
);
diffLineIndex = nextIndex;
if (!hunkHasChanges(bodyLines)) continue;
const { header: hunkHeader, nextOffset } = buildHunkHeader(
hunk.rawHeader, bodyLines, startOffset,
);
startOffset = nextOffset;
outputLines.push(hunkHeader, ...bodyLines);
}
if (outputLines.length === headerLength) {
throw new GitDomainError('INVALID_INPUT', 'No changed lines were selected.');
}
const transformedPatch = outputLines.join('\n') + '\n';
const applyArgs = reverse
? ['apply', '--cached', '--reverse', '-']
: ['apply', '--cached', '-'];
await runGitWithStdin(projectPath, applyArgs, transformedPatch);
return { success: true };
}
// Stages or unstages a single hunk by its index. The hunk index refers
// to the diff the frontend tab displayed (unstaged tab = `git diff`,
// staged tab = `git diff --cached`).
async function stageHunk({
projectPath,
file,
mode,
hunkIndex,
}: StageHunkOptions, fullPatch: string): Promise<GitMutationResult> {
await assertGitRepository(projectPath);
const isUnstage = mode === 'unstage';
if (!fullPatch.trim()) {
throw new GitDomainError('INVALID_INPUT', 'No diff is available for the requested target.');
}
const parsed = parsePatch(fullPatch);
if (hunkIndex < 0 || hunkIndex >= parsed.hunks.length) {
throw new GitDomainError('INVALID_INPUT', `Invalid hunk index ${hunkIndex}`);
}
const hunk = parsed.hunks[hunkIndex];
const singleHunkPatch = [...stagingDiffHeader(file, parsed, mode), hunk.rawHeader, ...hunk.lines].join('\n') + '\n';
const applyArgs = isUnstage
? ['apply', '--cached', '--reverse', '-']
: ['apply', '--cached', '-'];
await runGitWithStdin(projectPath, applyArgs, singleHunkPatch);
return { success: true };
}
export function createDiffEngine(registry: GitReviewDocumentRegistry) {
const documents = createReviewDocumentOperations(registry);
async function displayedPatch(options: StageSelectionOptions | StageHunkOptions): Promise<string> {
const stale = () => new GitDomainError('STALE_DOCUMENT', 'The displayed patch changed. Refresh and select it again.');
if (!options.documentId || !options.bodyFingerprint || !options.patchDigest) throw stale();
const lease = registry.acquire(options.projectPath, options.documentId);
if (!lease) throw stale();
try {
const expectedMode = options.mode === 'stage' ? 'working' : 'staged';
if (lease.document.source.kind !== 'workbench' || lease.document.source.mode !== expectedMode
|| lease.document.context !== options.contextLines
|| lease.document.patchDigests.get(options.file) !== options.patchDigest) throw stale();
const response = await documents.getReviewDocumentFileBodies({ projectPath: options.projectPath, documentId: options.documentId, files: [options.file], purpose: 'visible', signal: options.signal });
if (response.status !== 'ready') throw stale();
const body = response.files[options.file];
if (!body?.patch || body.bodyState !== 'loaded' || body.bodyFingerprint !== options.bodyFingerprint || body.patchDigest !== options.patchDigest) throw stale();
return body.patch;
} finally { lease.release(); }