-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathgitDiff.test.ts
More file actions
2292 lines (2052 loc) · 81.8 KB
/
Copy pathgitDiff.test.ts
File metadata and controls
2292 lines (2052 loc) · 81.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
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { execFile } from 'node:child_process';
import * as fs from 'node:fs/promises';
import * as os from 'node:os';
import * as path from 'node:path';
import { promisify } from 'node:util';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import {
fetchGitDiff,
fetchGitDiffHunks,
fetchGitDiffHunksForFile,
fetchGitLog,
fetchGitCommitDetail,
getGitWorkingTreeStatus,
MAX_DIFF_SIZE_BYTES,
MAX_FILES,
MAX_LINES_PER_FILE,
parseDeletedFromNameStatus,
parseGitDiff,
parseGitNumstat,
parseShortstat,
parseStatusBranchLine,
parseStatusEntries,
resolveGitDir,
} from './gitDiff.js';
const execFileAsync = promisify(execFile);
async function git(cwd: string, ...args: string[]): Promise<void> {
await execFileAsync('git', args, { cwd });
}
async function makeRepo(): Promise<string> {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'qwen-gitdiff-test-'));
await git(dir, 'init', '-q', '-b', 'main');
await git(dir, 'config', 'user.email', 'test@example.com');
await git(dir, 'config', 'user.name', 'Test');
await git(dir, 'config', 'commit.gpgsign', 'false');
return dir;
}
describe('parseGitNumstat', () => {
it('parses added/removed counts and file totals (NUL-delimited -z format)', () => {
const out = '3\t1\tsrc/a.ts\0' + '10\t0\tsrc/b.ts\0' + '0\t5\tsrc/c.ts\0';
const { stats, perFileStats } = parseGitNumstat(out);
expect(stats).toEqual({
filesCount: 3,
linesAdded: 13,
linesRemoved: 6,
});
expect(perFileStats.get('src/a.ts')).toEqual({
added: 3,
removed: 1,
isBinary: false,
});
expect(perFileStats.size).toBe(3);
});
it('treats `-` counts as binary with zero line deltas', () => {
const out = '-\t-\timg/logo.png\0';
const { stats, perFileStats } = parseGitNumstat(out);
expect(stats.filesCount).toBe(1);
expect(stats.linesAdded).toBe(0);
expect(stats.linesRemoved).toBe(0);
expect(perFileStats.get('img/logo.png')).toEqual({
added: 0,
removed: 0,
isBinary: true,
});
});
it('keeps accurate totals but caps per-file entries at MAX_FILES', () => {
const tokens: string[] = [];
const totalFiles = MAX_FILES + 5;
for (let i = 0; i < totalFiles; i++) {
tokens.push(`1\t0\tfile${i}.ts`);
}
const { stats, perFileStats } = parseGitNumstat(tokens.join('\0') + '\0');
expect(stats.filesCount).toBe(totalFiles);
expect(stats.linesAdded).toBe(totalFiles);
expect(perFileStats.size).toBe(MAX_FILES);
});
it('ignores malformed rows without crashing', () => {
const out = 'garbage-token\0' + '2\t1\tsrc/a.ts\0';
const { stats, perFileStats } = parseGitNumstat(out);
expect(stats.filesCount).toBe(1);
expect(perFileStats.has('src/a.ts')).toBe(true);
});
it('preserves literal tabs in tracked filenames via the -z wire format', () => {
// With -z, git emits the raw path; no C-style quoting. `split('\t')`
// would mis-attribute characters after the first tab, so the parser has
// to use index-based slicing instead.
const out = '1\t2\tweird\tname.ts\0';
const { perFileStats } = parseGitNumstat(out);
expect(perFileStats.has('weird\tname.ts')).toBe(true);
expect(perFileStats.get('weird\tname.ts')).toEqual({
added: 1,
removed: 2,
isBinary: false,
});
});
it('combines rename-pair tokens into a single entry keyed by the new path', () => {
// `-z` rename format: `<a>\t<b>\t\0<old>\0<new>\0`.
const out = '0\t0\t\0' + 'src/old.ts\0' + 'src/new.ts\0';
const { stats, perFileStats } = parseGitNumstat(out);
expect(stats.filesCount).toBe(1);
// Keyed by the current (new) path so the single-file endpoint can address
// it; the old path is carried for display.
expect(perFileStats.has('src/new.ts')).toBe(true);
expect(perFileStats.get('src/new.ts')?.oldPath).toBe('src/old.ts');
});
});
describe('parseDeletedFromNameStatus', () => {
it('extracts D-status paths and ignores M/A entries', () => {
const out = 'D\0gone.txt\0M\0kept.txt\0A\0added.txt\0D\0also-gone.txt\0';
expect(parseDeletedFromNameStatus(out)).toEqual(
new Set(['gone.txt', 'also-gone.txt']),
);
});
it('skips both halves of rename and copy entries', () => {
// Renames/copies span three tokens: `R<score>\0<old>\0<new>\0`. Neither
// path is "deleted" in the user sense — the file still exists under
// the new name.
const out =
'R100\0old.txt\0new.txt\0' + 'C75\0src.txt\0copy.txt\0' + 'D\0gone.txt\0';
expect(parseDeletedFromNameStatus(out)).toEqual(new Set(['gone.txt']));
});
it('preserves NUL-safe paths (tabs, non-ASCII)', () => {
// -z keeps raw bytes — same guarantee as the numstat path.
const out = 'D\0tab\there.txt\0D\0日本語.txt\0';
expect(parseDeletedFromNameStatus(out)).toEqual(
new Set(['tab\there.txt', '日本語.txt']),
);
});
it('handles empty input', () => {
expect(parseDeletedFromNameStatus('')).toEqual(new Set());
});
});
describe('parseShortstat', () => {
it('parses the full form', () => {
expect(
parseShortstat(' 3 files changed, 42 insertions(+), 7 deletions(-)'),
).toEqual({ filesCount: 3, linesAdded: 42, linesRemoved: 7 });
});
it('parses additions-only and deletions-only forms', () => {
expect(parseShortstat(' 1 file changed, 5 insertions(+)')).toEqual({
filesCount: 1,
linesAdded: 5,
linesRemoved: 0,
});
expect(parseShortstat(' 2 files changed, 3 deletions(-)')).toEqual({
filesCount: 2,
linesAdded: 0,
linesRemoved: 3,
});
});
it('returns null on garbage input', () => {
expect(parseShortstat('not a shortstat')).toBeNull();
});
});
describe('parseGitDiff', () => {
const sampleDiff = `diff --git a/src/a.ts b/src/a.ts
index 1111111..2222222 100644
--- a/src/a.ts
+++ b/src/a.ts
@@ -1,3 +1,4 @@
line one
-removed
+added
+added two
line three
diff --git a/src/b.ts b/src/b.ts
new file mode 100644
index 0000000..3333333
--- /dev/null
+++ b/src/b.ts
@@ -0,0 +1,2 @@
+hello
+world
`;
it('produces structured hunks for each file', () => {
const result = parseGitDiff(sampleDiff);
expect([...result.keys()]).toEqual(['src/a.ts', 'src/b.ts']);
const aHunks = result.get('src/a.ts')!;
expect(aHunks).toHaveLength(1);
expect(aHunks[0]).toMatchObject({
oldStart: 1,
oldLines: 3,
newStart: 1,
newLines: 4,
});
expect(aHunks[0].lines).toEqual([
' line one',
'-removed',
'+added',
'+added two',
' line three',
]);
const bHunks = result.get('src/b.ts')!;
expect(bHunks[0].lines).toEqual(['+hello', '+world']);
});
it('preserves the "\\ No newline at end of file" marker', () => {
const diff = `diff --git a/f.txt b/f.txt
--- a/f.txt
+++ b/f.txt
@@ -1 +1 @@
-line
\\ No newline at end of file
+line
`;
const result = parseGitDiff(diff);
expect(result.get('f.txt')![0].lines).toEqual([
'-line',
'\\ No newline at end of file',
'+line',
]);
});
it('skips a stray no-newline marker before any hunk header without throwing', () => {
// A malformed/truncated diff could carry a `\` line before any `@@`
// header; the pre-hunk guard skips it rather than throwing on a null
// currentHunk (which would lose every subsequent file's hunks).
const diff = `diff --git a/f.txt b/f.txt
--- a/f.txt
+++ b/f.txt
\\ No newline at end of file
@@ -1 +1 @@
-line
+line
`;
const result = parseGitDiff(diff);
expect(result.get('f.txt')![0].lines).toEqual(['-line', '+line']);
});
it('returns empty map on empty input', () => {
expect(parseGitDiff('').size).toBe(0);
expect(parseGitDiff(' \n').size).toBe(0);
});
it('caps per-file lines at MAX_LINES_PER_FILE', () => {
const header = `diff --git a/big.ts b/big.ts
index 1111111..2222222 100644
--- a/big.ts
+++ b/big.ts
@@ -1,${MAX_LINES_PER_FILE + 50} +1,${MAX_LINES_PER_FILE + 50} @@
`;
const body = Array.from(
{ length: MAX_LINES_PER_FILE + 50 },
(_, i) => ` line${i}`,
).join('\n');
const result = parseGitDiff(header + body + '\n');
const hunk = result.get('big.ts')![0];
expect(hunk.lines.length).toBe(MAX_LINES_PER_FILE);
});
it('records the capped file in the provided truncatedPaths set', () => {
const header = `diff --git a/big.ts b/big.ts
index 1111111..2222222 100644
--- a/big.ts
+++ b/big.ts
@@ -1,${MAX_LINES_PER_FILE + 50} +1,${MAX_LINES_PER_FILE + 50} @@
`;
const body = Array.from(
{ length: MAX_LINES_PER_FILE + 50 },
(_, i) => ` line${i}`,
).join('\n');
const truncatedPaths = new Set<string>();
parseGitDiff(header + body + '\n', truncatedPaths);
// The caller keys its `truncated` flag off this set, so it must name the
// file that actually lost lines to the cap.
expect(truncatedPaths.has('big.ts')).toBe(true);
});
});
describe('fetchGitDiff', () => {
let repo: string;
beforeEach(async () => {
repo = await makeRepo();
});
afterEach(async () => {
await fs.rm(repo, { recursive: true, force: true });
});
it('returns null when not in a git repo', async () => {
const plain = await fs.mkdtemp(path.join(os.tmpdir(), 'qwen-plain-'));
try {
expect(await fetchGitDiff(plain)).toBeNull();
} finally {
await fs.rm(plain, { recursive: true, force: true });
}
});
it('captures tracked modifications and counts lines in untracked text files', async () => {
await fs.writeFile(path.join(repo, 'tracked.txt'), 'one\ntwo\nthree\n');
await git(repo, 'add', '.');
await git(repo, 'commit', '-q', '-m', 'init');
await fs.writeFile(
path.join(repo, 'tracked.txt'),
'one\ntwo\nthree\nfour\n',
);
await fs.writeFile(path.join(repo, 'new.txt'), 'brand new\nsecond\n');
const result = await fetchGitDiff(repo);
expect(result).not.toBeNull();
expect(result!.stats.filesCount).toBe(2);
// Tracked: +1 from adding `four`. Untracked `new.txt`: 2 lines.
expect(result!.stats.linesAdded).toBe(3);
expect(result!.perFileStats.get('tracked.txt')?.added).toBe(1);
expect(result!.perFileStats.get('new.txt')).toEqual({
added: 2,
removed: 0,
isBinary: false,
isUntracked: true,
truncated: false,
});
});
it('marks oversized untracked text files as truncated', async () => {
await fs.writeFile(path.join(repo, 'seed.txt'), 'x\n');
await git(repo, 'add', '.');
await git(repo, 'commit', '-q', '-m', 'init');
// Write a 1.5 MB text file — larger than UNTRACKED_READ_CAP_BYTES (1 MB),
// so the counter can only see part of the lines. The flag lets the UI
// mark `+N` as a lower bound instead of silently under-reporting.
const line = 'a'.repeat(99) + '\n'; // 100 bytes per line
const totalLines = 15_000; // 1.5 MB
await fs.writeFile(path.join(repo, 'big.log'), line.repeat(totalLines));
const result = await fetchGitDiff(repo);
expect(result).not.toBeNull();
const entry = result!.perFileStats.get('big.log');
expect(entry?.isUntracked).toBe(true);
expect(entry?.isBinary).toBe(false);
expect(entry?.truncated).toBe(true);
// We counted at most UNTRACKED_READ_CAP_BYTES / 100 = 10_000 lines, less
// than the file's real line count.
expect(entry?.added).toBeGreaterThan(0);
expect(entry!.added).toBeLessThan(totalLines);
});
it('flags untracked binary files without counting lines', async () => {
await fs.writeFile(path.join(repo, 'seed.txt'), 'x\n');
await git(repo, 'add', '.');
await git(repo, 'commit', '-q', '-m', 'init');
// A NUL byte in the first few bytes is git's own binary heuristic.
await fs.writeFile(
path.join(repo, 'blob.bin'),
Buffer.from([0x89, 0x00, 0xff, 0x10]),
);
const result = await fetchGitDiff(repo);
expect(result).not.toBeNull();
expect(result!.perFileStats.get('blob.bin')).toEqual({
added: 0,
removed: 0,
isBinary: true,
isUntracked: true,
truncated: false,
});
// Binary bytes must not contaminate the linesAdded total.
expect(result!.stats.linesAdded).toBe(0);
});
it('returns zero stats on a clean working tree', async () => {
await fs.writeFile(path.join(repo, 'a.txt'), 'hello\n');
await git(repo, 'add', '.');
await git(repo, 'commit', '-q', '-m', 'init');
const result = await fetchGitDiff(repo);
expect(result).not.toBeNull();
expect(result!.stats).toEqual({
filesCount: 0,
linesAdded: 0,
linesRemoved: 0,
});
expect(result!.perFileStats.size).toBe(0);
});
it('returns null during a transient merge state', async () => {
await fs.writeFile(path.join(repo, 'a.txt'), 'hello\n');
await git(repo, 'add', '.');
await git(repo, 'commit', '-q', '-m', 'init');
// Fake a merge in progress by writing MERGE_HEAD.
await fs.writeFile(
path.join(repo, '.git', 'MERGE_HEAD'),
'0000000000000000000000000000000000000000\n',
);
expect(await fetchGitDiff(repo)).toBeNull();
expect((await fetchGitDiffHunks(repo)).size).toBe(0);
});
});
describe('fetchGitDiffHunks', () => {
let repo: string;
beforeEach(async () => {
repo = await makeRepo();
});
afterEach(async () => {
await fs.rm(repo, { recursive: true, force: true });
});
it('returns hunks for modified tracked files', async () => {
await fs.writeFile(path.join(repo, 'a.txt'), 'one\ntwo\nthree\n');
await git(repo, 'add', '.');
await git(repo, 'commit', '-q', '-m', 'init');
await fs.writeFile(path.join(repo, 'a.txt'), 'one\nTWO\nthree\n');
const hunks = await fetchGitDiffHunks(repo);
const fileHunks = hunks.get('a.txt');
expect(fileHunks).toBeDefined();
expect(fileHunks![0].lines.some((l: string) => l.startsWith('-two'))).toBe(
true,
);
expect(fileHunks![0].lines.some((l: string) => l.startsWith('+TWO'))).toBe(
true,
);
});
it('preserves content lines that start with --- / +++ / index', async () => {
await fs.writeFile(
path.join(repo, 'notes.md'),
'keep\n---a/foo\n+++b/bar\nindex deadbeef\nkeep2\n',
);
await git(repo, 'add', '.');
await git(repo, 'commit', '-q', '-m', 'init');
// Remove every diff-lookalike line; the added/removed lines should still
// round-trip through parseGitDiff even though their prefixes match
// file-header sentinels.
await fs.writeFile(path.join(repo, 'notes.md'), 'keep\nkeep2\n');
const hunks = await fetchGitDiffHunks(repo);
const fileHunks = hunks.get('notes.md');
expect(fileHunks).toBeDefined();
const removed = fileHunks!.flatMap((h) =>
h.lines.filter((l: string) => l.startsWith('-')),
);
expect(removed).toEqual(
expect.arrayContaining(['----a/foo', '-+++b/bar', '-index deadbeef']),
);
});
it('keys hunks by the real path for files with tabs in the name (C-quoted in diff output)', async () => {
// Real git output for a tracked file named `tab\there.txt` looks like
// `+++ "b/tab\there.txt"` even with `core.quotepath=false` — C-quoting
// for tabs/newlines/quotes is independent of that config. Without the
// unquote step in `extractFilePath`, fetchGitDiffHunks would silently
// drop the file's hunks.
const weirdName = 'tab\there.txt';
try {
await fs.writeFile(path.join(repo, weirdName), 'x\n');
} catch {
return; // Filesystem refused tab in name (e.g. Windows NTFS).
}
await git(repo, 'add', '.');
await git(repo, 'commit', '-q', '-m', 'init');
await fs.writeFile(path.join(repo, weirdName), 'y\n');
const hunks = await fetchGitDiffHunks(repo);
expect([...hunks.keys()]).toEqual([weirdName]);
expect(hunks.get(weirdName)![0].lines.some((l) => l.startsWith('-x'))).toBe(
true,
);
expect(hunks.get(weirdName)![0].lines.some((l) => l.startsWith('+y'))).toBe(
true,
);
});
it('keys hunks by the real path for files whose name contains " b/"', async () => {
await fs.mkdir(path.join(repo, 'a b'), { recursive: true });
await fs.writeFile(path.join(repo, 'a b', 'c.txt'), 'x\n');
await git(repo, 'add', '.');
await git(repo, 'commit', '-q', '-m', 'init');
await fs.writeFile(path.join(repo, 'a b', 'c.txt'), 'y\n');
const hunks = await fetchGitDiffHunks(repo);
// `diff --git a/a b/c.txt b/a b/c.txt` is ambiguous to split; the parser
// must anchor on `+++ b/<path>\t` instead.
expect([...hunks.keys()]).toEqual(['a b/c.txt']);
});
it('handles multi-hunk diffs', async () => {
const initial = Array.from({ length: 40 }, (_, i) => `line${i}`).join('\n');
await fs.writeFile(path.join(repo, 'big.txt'), initial + '\n');
await git(repo, 'add', '.');
await git(repo, 'commit', '-q', '-m', 'init');
const lines = initial.split('\n');
lines[2] = 'CHANGED_EARLY';
lines[35] = 'CHANGED_LATE';
await fs.writeFile(path.join(repo, 'big.txt'), lines.join('\n') + '\n');
const hunks = await fetchGitDiffHunks(repo);
const fileHunks = hunks.get('big.txt');
expect(fileHunks).toBeDefined();
expect(fileHunks!.length).toBeGreaterThanOrEqual(2);
});
});
describe('fetchGitDiffHunksForFile', () => {
let repo: string;
beforeEach(async () => {
repo = await makeRepo();
});
afterEach(async () => {
await fs.rm(repo, { recursive: true, force: true });
});
it('returns hunks for a modified tracked file', async () => {
await fs.writeFile(path.join(repo, 'a.txt'), 'one\ntwo\nthree\n');
await git(repo, 'add', '.');
await git(repo, 'commit', '-q', '-m', 'init');
await fs.writeFile(path.join(repo, 'a.txt'), 'one\nTWO\nthree\n');
const result = await fetchGitDiffHunksForFile(repo, 'a.txt');
expect(result).not.toBeNull();
expect(result!.truncated).toBe(false);
expect(result!.hunks[0].lines.some((l) => l === '-two')).toBe(true);
expect(result!.hunks[0].lines.some((l) => l === '+TWO')).toBe(true);
});
it('scopes the diff to the requested file only', async () => {
await fs.writeFile(path.join(repo, 'a.txt'), 'a\n');
await fs.writeFile(path.join(repo, 'b.txt'), 'b\n');
await git(repo, 'add', '.');
await git(repo, 'commit', '-q', '-m', 'init');
await fs.writeFile(path.join(repo, 'a.txt'), 'A\n');
await fs.writeFile(path.join(repo, 'b.txt'), 'B\n');
const result = await fetchGitDiffHunksForFile(repo, 'a.txt');
expect(result!.hunks[0].lines.some((l) => l === '+A')).toBe(true);
// b.txt's change must not leak into a.txt's hunks.
expect(result!.hunks[0].lines.some((l) => l === '+B')).toBe(false);
});
it('returns null for an unchanged tracked file', async () => {
await fs.writeFile(path.join(repo, 'a.txt'), 'a\n');
await git(repo, 'add', '.');
await git(repo, 'commit', '-q', '-m', 'init');
expect(await fetchGitDiffHunksForFile(repo, 'a.txt')).toBeNull();
});
it('returns null during a transient merge state', async () => {
await fs.writeFile(path.join(repo, 'a.txt'), 'one\n');
await git(repo, 'add', '.');
await git(repo, 'commit', '-q', '-m', 'init');
await fs.writeFile(path.join(repo, 'a.txt'), 'TWO\n');
// Fake a merge in progress; the single-file endpoint must decline just
// like fetchGitDiff/fetchGitDiffHunks do.
await fs.writeFile(
path.join(repo, '.git', 'MERGE_HEAD'),
'0000000000000000000000000000000000000000\n',
);
expect(await fetchGitDiffHunksForFile(repo, 'a.txt')).toBeNull();
});
it('diffs a renamed file old→new when oldPath is provided', async () => {
await fs.writeFile(path.join(repo, 'old.txt'), 'one\ntwo\nthree\n');
await git(repo, 'add', '.');
await git(repo, 'commit', '-q', '-m', 'init');
// Rename old.txt → new.txt and edit one line.
await fs.rm(path.join(repo, 'old.txt'));
await fs.writeFile(path.join(repo, 'new.txt'), 'one\nTWO\nthree\n');
await git(repo, 'add', '-A');
// With the pre-rename path, rename detection yields the actual edit
// (-two/+TWO with one/three as context) instead of new.txt as fully added.
const result = await fetchGitDiffHunksForFile(repo, 'new.txt', 'old.txt');
expect(result).not.toBeNull();
const lines = result!.hunks.flatMap((h) => h.lines);
expect(lines).toContain('-two');
expect(lines).toContain('+TWO');
expect(lines).toContain(' one');
expect(lines).not.toContain('+one');
});
it('synthesizes an all-added hunk for an untracked file', async () => {
await fs.writeFile(path.join(repo, 'a.txt'), 'a\n');
await git(repo, 'add', '.');
await git(repo, 'commit', '-q', '-m', 'init');
await fs.writeFile(path.join(repo, 'new.txt'), 'x\ny\n');
const result = await fetchGitDiffHunksForFile(repo, 'new.txt');
expect(result).not.toBeNull();
expect(result!.truncated).toBe(false);
expect(result!.hunks).toHaveLength(1);
expect(result!.hunks[0]).toMatchObject({
oldStart: 0,
oldLines: 0,
newStart: 1,
newLines: 2,
});
expect(result!.hunks[0].lines).toEqual(['+x', '+y']);
});
it('reports truncation for an untracked file past the line cap', async () => {
await fs.writeFile(path.join(repo, 'a.txt'), 'a\n');
await git(repo, 'add', '.');
await git(repo, 'commit', '-q', '-m', 'init');
const body = Array.from(
{ length: MAX_LINES_PER_FILE + 5 },
(_, i) => `line-${i}`,
).join('\n');
await fs.writeFile(path.join(repo, 'big.txt'), body + '\n');
const result = await fetchGitDiffHunksForFile(repo, 'big.txt');
expect(result).not.toBeNull();
expect(result!.truncated).toBe(true);
expect(result!.hunks[0].lines).toHaveLength(MAX_LINES_PER_FILE);
// The capped window is the file's head, all-added.
expect(result!.hunks[0].lines[0]).toBe('+line-0');
});
it('reports truncation for a tracked diff past the parser line cap', async () => {
await fs.writeFile(path.join(repo, 'a.txt'), 'seed\n');
await git(repo, 'add', '.');
await git(repo, 'commit', '-q', '-m', 'init');
const body = Array.from(
{ length: MAX_LINES_PER_FILE + 5 },
(_, i) => `line-${i}`,
).join('\n');
await fs.writeFile(path.join(repo, 'a.txt'), body + '\n');
const result = await fetchGitDiffHunksForFile(repo, 'a.txt');
expect(result).not.toBeNull();
expect(result!.truncated).toBe(true);
const total = result!.hunks.reduce((n, h) => n + h.lines.length, 0);
expect(total).toBe(MAX_LINES_PER_FILE);
});
it('returns null for a binary untracked file', async () => {
await fs.writeFile(path.join(repo, 'a.txt'), 'a\n');
await git(repo, 'add', '.');
await git(repo, 'commit', '-q', '-m', 'init');
await fs.writeFile(path.join(repo, 'blob.bin'), Buffer.from([0, 1, 2, 3]));
expect(await fetchGitDiffHunksForFile(repo, 'blob.bin')).toBeNull();
});
it.skipIf(process.platform === 'win32')(
'returns null for an untracked FIFO without hanging',
async () => {
// `ls-files --others` can list a FIFO; open() on it blocks forever
// waiting on a writer. synthesizeUntrackedHunk must lstat-gate so
// expanding it in the diff dialog can't hang the daemon's event loop.
await fs.writeFile(path.join(repo, 'a.txt'), 'a\n');
await git(repo, 'add', '.');
await git(repo, 'commit', '-q', '-m', 'init');
await execFileAsync('mkfifo', [path.join(repo, 'pipe')]);
expect(await fetchGitDiffHunksForFile(repo, 'pipe')).toBeNull();
},
);
it('returns null for an ignored file', async () => {
await fs.writeFile(path.join(repo, 'a.txt'), 'a\n');
await fs.writeFile(path.join(repo, '.gitignore'), 'ignored.log\n');
await git(repo, 'add', '.');
await git(repo, 'commit', '-q', '-m', 'init');
await fs.writeFile(path.join(repo, 'ignored.log'), 'secret\n');
expect(await fetchGitDiffHunksForFile(repo, 'ignored.log')).toBeNull();
});
it('rejects unsafe relative paths (traversal / empty)', async () => {
expect(await fetchGitDiffHunksForFile(repo, '../outside.txt')).toBeNull();
expect(await fetchGitDiffHunksForFile(repo, 'a/../../b.txt')).toBeNull();
expect(await fetchGitDiffHunksForFile(repo, '')).toBeNull();
});
it('accepts an absolute path inside the repo and rejects one outside it', async () => {
await fs.writeFile(path.join(repo, 'a.txt'), 'one\ntwo\n');
await git(repo, 'add', '.');
await git(repo, 'commit', '-q', '-m', 'init');
await fs.writeFile(path.join(repo, 'a.txt'), 'one\nTWO\n');
const result = await fetchGitDiffHunksForFile(
repo,
path.join(repo, 'a.txt'),
);
expect(result).not.toBeNull();
expect(result!.hunks[0].lines.some((l) => l === '+TWO')).toBe(true);
// An absolute path outside the git root is rejected.
const outside = path.join(os.tmpdir(), 'elsewhere.txt');
expect(await fetchGitDiffHunksForFile(repo, outside)).toBeNull();
});
it('accepts a literal `..foo` filename at the root (not a traversal)', async () => {
// A file literally named `..foo` is not a `..` segment; the absolute-path
// normalization must allow it (a bare startsWith('..') wrongly rejected it,
// so the diff viewer could not render such a file).
await fs.writeFile(path.join(repo, '..foo'), 'one\ntwo\n');
await git(repo, 'add', '.');
await git(repo, 'commit', '-q', '-m', 'init');
await fs.writeFile(path.join(repo, '..foo'), 'one\nTWO\n');
const result = await fetchGitDiffHunksForFile(
repo,
path.join(repo, '..foo'),
);
expect(result).not.toBeNull();
expect(result!.hunks[0].lines.some((l) => l === '+TWO')).toBe(true);
});
it('returns null outside a git repo', async () => {
const plain = await fs.mkdtemp(path.join(os.tmpdir(), 'qwen-plain-'));
try {
expect(await fetchGitDiffHunksForFile(plain, 'a.txt')).toBeNull();
} finally {
await fs.rm(plain, { recursive: true, force: true });
}
});
});
describe('parseGitDiff C-quoted path support', () => {
it('decodes `+++ "b/..."` headers for files with tabs in the name', () => {
// Reproduces wenshao Critical (PR #3491 line 615): without C-quote
// decoding, `extractFilePath` rejects the quoted +++ line and the
// hunks are silently dropped.
const diff = `diff --git "a/tab\\there.txt" "b/tab\\there.txt"
index 1111111..2222222 100644
--- "a/tab\\there.txt"
+++ "b/tab\\there.txt"
@@ -1 +1,2 @@
a
+b
`;
const result = parseGitDiff(diff);
expect([...result.keys()]).toEqual(['tab\there.txt']);
expect(result.get('tab\there.txt')![0].lines).toEqual([' a', '+b']);
});
it('decodes octal escapes in quoted paths (legacy quotepath=true output)', () => {
// Even with `core.quotepath=false` set on our git invocations, callers
// could feed us output produced by a different command. \346\226\207
// is the UTF-8 byte sequence for `文`.
const diff = `diff --git "a/\\346\\226\\207.txt" "b/\\346\\226\\207.txt"
index 1111111..2222222 100644
--- "a/\\346\\226\\207.txt"
+++ "b/\\346\\226\\207.txt"
@@ -1 +1 @@
-x
+y
`;
const result = parseGitDiff(diff);
expect([...result.keys()]).toEqual(['文.txt']);
});
it('preserves non-BMP code points in quoted paths instead of splitting surrogates', () => {
// Reproduces wenshao Critical (PR #3491 line 504): the previous walker
// advanced one UTF-16 code unit at a time, so a non-BMP codepoint such
// as the rocket emoji 🚀 (U+1F680) coexisting with a forced-quoting byte
// (here a TAB) was decoded as two lone surrogates → two replacement
// characters, corrupting the hunk key.
const diff = `diff --git "a/\\t🚀.txt" "b/\\t🚀.txt"
index 1111111..2222222 100644
--- "a/\\t🚀.txt"
+++ "b/\\t🚀.txt"
@@ -1 +1 @@
-x
+y
`;
const result = parseGitDiff(diff);
expect([...result.keys()]).toEqual(['\t🚀.txt']);
});
it('decodes the remaining C-style escapes (\\a, \\b, \\f, \\v)', () => {
// Reproduces wenshao Critical (PR #3491 line 552): the previous switch
// dropped the leading backslash for these escapes, turning `\a` / `\b`
// / `\f` / `\v` into ordinary `a` / `b` / `f` / `v` and yielding a
// hunk key that did not match the real on-disk filename.
const diff = `diff --git "a/bell\\afile.txt" "b/bell\\afile.txt"
index 1111111..2222222 100644
--- "a/bell\\afile.txt"
+++ "b/bell\\afile.txt"
@@ -1 +1 @@
-x
+y
diff --git "a/back\\bspace.txt" "b/back\\bspace.txt"
index 3333333..4444444 100644
--- "a/back\\bspace.txt"
+++ "b/back\\bspace.txt"
@@ -1 +1 @@
-x
+y
diff --git "a/form\\ffeed.txt" "b/form\\ffeed.txt"
index 5555555..6666666 100644
--- "a/form\\ffeed.txt"
+++ "b/form\\ffeed.txt"
@@ -1 +1 @@
-x
+y
diff --git "a/vert\\vtab.txt" "b/vert\\vtab.txt"
index 7777777..8888888 100644
--- "a/vert\\vtab.txt"
+++ "b/vert\\vtab.txt"
@@ -1 +1 @@
-x
+y
`;
const result = parseGitDiff(diff);
expect([...result.keys()]).toEqual([
'bell\x07file.txt',
'back\x08space.txt',
'form\x0cfeed.txt',
'vert\x0btab.txt',
]);
});
});
describe('parseGitDiff path disambiguation', () => {
it('keys hunks by the real path when the filename contains " b/"', () => {
// `a b/c.txt` produces `diff --git a/a b/c.txt b/a b/c.txt`, which is
// ambiguous to split on ` b/`. Git appends a TAB on the `---`/`+++` lines
// when the path contains whitespace — that's the unambiguous anchor.
const diff = `diff --git a/a b/c.txt b/a b/c.txt
index 111..222 100644
--- a/a b/c.txt\t
+++ b/a b/c.txt\t
@@ -1 +1 @@
-x
+y
`;
const result = parseGitDiff(diff);
expect([...result.keys()]).toEqual(['a b/c.txt']);
expect(result.get('a b/c.txt')![0].lines).toEqual(['-x', '+y']);
});
it('uses `rename to` for renames, ignoring the ambiguous header', () => {
const diff = `diff --git a/old name.txt b/renamed name.txt
similarity index 100%
rename from old name.txt
rename to renamed name.txt
`;
// No hunks — nothing to key — but the extractor should still not confuse
// paths. The file block is dropped because there are no `@@` lines, which
// is the existing behavior for mode-only / rename-only changes.
const result = parseGitDiff(diff);
expect(result.size).toBe(0);
});
it('falls back to `--- a/<path>` when the file was deleted', () => {
const diff = `diff --git a/gone.txt b/gone.txt
deleted file mode 100644
index 111..000
--- a/gone.txt
+++ /dev/null
@@ -1 +0,0 @@
-bye
`;
const result = parseGitDiff(diff);
expect([...result.keys()]).toEqual(['gone.txt']);
});
it('uses `+++ b/<path>` for newly-created files', () => {
const diff = `diff --git a/new.txt b/new.txt
new file mode 100644
index 000..111
--- /dev/null
+++ b/new.txt
@@ -0,0 +1 @@
+hi
`;
const result = parseGitDiff(diff);
expect([...result.keys()]).toEqual(['new.txt']);
});
});
describe('parseGitDiff edge cases', () => {
it('drops file blocks that have no `@@` hunk header', () => {
const noHunk = `diff --git a/foo.ts b/foo.ts
old mode 100644
new mode 100755
`;
expect(parseGitDiff(noHunk).size).toBe(0);
});
it('stops collecting once MAX_FILES files have been parsed', () => {
const blocks: string[] = [];
for (let i = 0; i < MAX_FILES + 5; i++) {
blocks.push(
`diff --git a/f${i}.ts b/f${i}.ts
--- a/f${i}.ts
+++ b/f${i}.ts
@@ -1,1 +1,1 @@
-x
+y
`,
);
}
const result = parseGitDiff(blocks.join(''));
expect(result.size).toBe(MAX_FILES);
});
});
describe('parseGitDiff size/line caps', () => {
it('skips files whose raw diff exceeds MAX_DIFF_SIZE_BYTES', () => {
const header = `diff --git a/small.ts b/small.ts
--- a/small.ts
+++ b/small.ts
@@ -1,1 +1,1 @@
-a
+b
`;
const bigBody = 'x'.repeat(MAX_DIFF_SIZE_BYTES + 10);
const bigDiff = `diff --git a/big.ts b/big.ts
--- a/big.ts
+++ b/big.ts
@@ -1,1 +1,1 @@
-${bigBody}
+b
`;
const result = parseGitDiff(header + bigDiff);
expect(result.has('small.ts')).toBe(true);
expect(result.has('big.ts')).toBe(false);
});
});
describe('resolveGitDir', () => {
it('returns the .git directory for a regular repo', async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'qwen-gitdir-'));
try {
await execFileAsync('git', ['init', '-q', '-b', 'main'], { cwd: dir });
const resolved = await resolveGitDir(dir);
expect(resolved).toBe(path.join(dir, '.git'));
} finally {
await fs.rm(dir, { recursive: true, force: true });
}
});
it('follows the gitdir pointer for linked worktrees', async () => {
const main = await fs.mkdtemp(path.join(os.tmpdir(), 'qwen-gitmain-'));
try {
await execFileAsync('git', ['init', '-q', '-b', 'main'], { cwd: main });
await execFileAsync('git', ['config', 'user.email', 'test@example.com'], {
cwd: main,
});
await execFileAsync('git', ['config', 'user.name', 'Test'], {
cwd: main,
});
await execFileAsync('git', ['config', 'commit.gpgsign', 'false'], {
cwd: main,
});
await fs.writeFile(path.join(main, 'a.txt'), 'hi\n');
await execFileAsync('git', ['add', '.'], { cwd: main });
await execFileAsync('git', ['commit', '-q', '-m', 'init'], { cwd: main });
const wtPath = path.join(main, 'wt');
await execFileAsync(
'git',
['worktree', 'add', '-q', wtPath, '-b', 'side'],
{ cwd: main },
);
const resolved = await resolveGitDir(wtPath);
expect(resolved).not.toBeNull();
// Git writes the linked-worktree pointer with forward slashes even on
// Windows (`gitdir: C:/.../main/.git/worktrees/wt`), and we surface
// that string verbatim. Match either separator so the assertion is
// platform-independent.
expect(resolved).toMatch(/[/\\]\.git[/\\]worktrees[/\\]/);
// Fake a merge-in-progress inside the linked worktree's gitdir and
// confirm `fetchGitDiff` short-circuits, which would silently fail if
// transient detection only looked at `<wt>/.git/MERGE_HEAD`.
await fs.writeFile(
path.join(resolved!, 'MERGE_HEAD'),
'0000000000000000000000000000000000000000\n',
);
expect(await fetchGitDiff(wtPath)).toBeNull();