-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathgitDiff.ts
More file actions
1663 lines (1561 loc) · 57.3 KB
/
Copy pathgitDiff.ts
File metadata and controls
1663 lines (1561 loc) · 57.3 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';
// Namespace import (vs `import { constants }`) so vitest tests that
// `vi.mock('node:fs', ...)` without supplying every named export don't
// blow up in strict-mock mode just because they transitively load this
// file via `@qwen-code/qwen-code-core`. The `constants?.X ?? 0` accesses
// below absorb a missing `constants` field by falling through to plain
// `O_RDONLY` (= 0 on POSIX) — harmless in mock environments where no
// real `open()` ever runs.
import * as nodeFs from 'node:fs';
import { access, lstat, open, readFile, stat } from 'node:fs/promises';
import * as path from 'node:path';
import { promisify } from 'node:util';
import type { Hunk } from 'diff';
import { findGitRoot, readFirstLineNoFollow } from './gitUtils.js';
/** Re-export so consumers don't need to depend on `diff` directly. */
export type GitDiffHunk = Hunk;
/**
* A single file's diff hunks plus whether the per-file caps
* (`MAX_DIFF_SIZE_BYTES` / `MAX_LINES_PER_FILE`) actually cut content — so the
* viewer can label the diff as incomplete instead of silently under-reporting.
*/
export interface GitDiffFileHunks {
hunks: Hunk[];
truncated: boolean;
}
const execFileAsync = promisify(execFile);
export interface GitDiffStats {
filesCount: number;
linesAdded: number;
linesRemoved: number;
}
export interface PerFileStats {
added: number;
removed: number;
isBinary: boolean;
isUntracked?: boolean;
/** `true` when the file is removed in the worktree relative to HEAD.
* Mutually exclusive with `isUntracked`. Detected via
* `git diff HEAD --name-status -z` (status letter `D`); a row like
* `0\t10\tfoo.ts` from numstat alone is not enough to distinguish
* "deleted" from "heavy edit that drops 10 lines". */
isDeleted?: boolean;
/** Only meaningful for untracked files: `true` when the file exceeded the
* line-counting read cap and `added` is therefore a lower bound. */
truncated?: boolean;
/** For a rename detected by `git diff --numstat -z`, the pre-rename path.
* The map key (and wire `path`) is the current post-rename path so the
* single-file endpoint can address it; this carries the old path for display. */
oldPath?: string;
}
export interface GitDiffResult {
stats: GitDiffStats;
perFileStats: Map<string, PerFileStats>;
}
const GIT_TIMEOUT_MS = 5000;
/** Maximum files retained in per-file results. Matches issue #2997 "50 files" cap. */
export const MAX_FILES = 50;
/** Per-file diff content cap. Matches issue #2997 "1MB" cap. */
export const MAX_DIFF_SIZE_BYTES = 1_000_000;
/** Per-file diff line cap (GitHub's auto-load threshold). */
export const MAX_LINES_PER_FILE = 400;
/** Skip per-file parsing when the diff touches more than this many files. */
export const MAX_FILES_FOR_DETAILS = 500;
/** Sentinel used when `git diff --shortstat` returns nothing — most often
* because there are no tracked changes at all. The fast-path threshold
* is then driven entirely by the untracked count. */
const EMPTY_STATS: GitDiffStats = {
filesCount: 0,
linesAdded: 0,
linesRemoved: 0,
};
/** How much of an untracked file to read when counting its lines. */
const UNTRACKED_READ_CAP_BYTES = MAX_DIFF_SIZE_BYTES;
/** Per-file read buffer for line counting. With up to MAX_FILES (=50) files
* reading concurrently, the worst-case heap footprint is ~3.2 MB instead of
* the ~50 MB a single full-cap allocation per file would cost. */
const UNTRACKED_READ_CHUNK_BYTES = 64 * 1024;
/** Scan the first N bytes for NUL to detect binary files (matches git's heuristic). */
const BINARY_SNIFF_BYTES = 8 * 1024;
/** Memoized open flags for line counting. `O_NOFOLLOW` closes the TOCTOU
* window between the `lstat` symlink check and `open` — if the path is
* replaced with a symlink in that gap, `open` rejects with `ELOOP` instead
* of silently dereferencing it. Falls back to plain `O_RDONLY` on platforms
* that don't expose the flag (Windows constants omit `O_NOFOLLOW`).
*
* Computed lazily on first call (rather than at module load) so test files
* that `vi.mock('node:fs', ...)` without supplying `constants` can still
* load this module transitively via `@qwen-code/qwen-code-core` without
* vitest's strict-mock proxy throwing on the property access. Tests that
* do not actually exercise `countUntrackedLines` never trigger the lookup. */
let untrackedOpenFlagsCache: number | undefined;
function getUntrackedOpenFlags(): number {
if (untrackedOpenFlagsCache === undefined) {
untrackedOpenFlagsCache =
(nodeFs.constants?.O_RDONLY ?? 0) | (nodeFs.constants?.O_NOFOLLOW ?? 0);
}
return untrackedOpenFlagsCache;
}
/**
* Fetch numstat-based git diff stats (files changed, lines added/removed) and
* per-file summaries comparing the working tree to HEAD. Structured hunks are
* available separately via `fetchGitDiffHunks`.
*
* Returns `null` when not inside a git repo, when git itself fails, or when
* the working tree is in a transient state (merge, rebase, cherry-pick,
* revert) — those states carry incoming changes that weren't intentionally
* made by the user.
*/
export async function fetchGitDiff(cwd: string): Promise<GitDiffResult | null> {
// Walk ancestors once to find the worktree root; reuse the result for the
// transient-state probe and every git invocation below. `findGitRoot`
// doubles as the "is this a git repo" check — a non-null return implies a
// repo. `git diff` already emits repo-root-relative paths regardless of
// cwd, but `git ls-files --others` is scoped to cwd, so pinning everything
// to the same root keeps the path keys consistent and ensures untracked
// files in sibling directories aren't silently dropped when /diff is
// invoked from a subdirectory of the worktree.
const gitRoot = findGitRoot(cwd);
if (!gitRoot) return null;
if (await isInTransientGitState(gitRoot)) return null;
// Shortstat probe + untracked scan run in parallel — both are needed
// regardless of which path we take, and shortstat is O(1) memory so it can
// short-circuit huge generated workspaces before we pay the per-file
// numstat cost. For untracked we hold the raw stdout rather than the parsed
// list so the fast path only has to count NUL bytes instead of allocating
// a full path array.
// Every `git diff` invocation passes both `--no-ext-diff` AND
// `--no-textconv` so the worktree's config can never run user-supplied
// commands while /diff is only inspecting changes. The two flags cover
// independent attack surfaces: `--no-ext-diff` blocks `GIT_EXTERNAL_DIFF`
// and `diff.<name>.command`, while `--no-textconv` blocks the textconv
// filter that .gitattributes + `diff.<name>.textconv` register (e.g.
// `pdftotext` to render PDFs). In practice the stats variants
// (`--shortstat`, `--numstat`, `--name-status`) do not invoke either
// mechanism, but pinning both flags everywhere is defense-in-depth —
// git's behavior around these drivers has shifted between versions
// before.
const [shortstatOut, untrackedOut] = await Promise.all([
runGit(
[
'--no-optional-locks',
'diff',
'--no-ext-diff',
'--no-textconv',
'HEAD',
'--shortstat',
],
gitRoot,
),
runGit(
[
'--no-optional-locks',
'ls-files',
'-z',
'--others',
'--exclude-standard',
],
gitRoot,
),
]);
const untrackedCount = countNulDelimited(untrackedOut);
// Apply the >500-file fast path on tracked + untracked, treating "no
// shortstat output" (no tracked changes) and "shortstat unparseable"
// both as zero tracked stats. Without this fall-through, a workspace
// with 0 tracked + 501 untracked files would slip past the guardrail:
// shortstat would be empty, parseShortstat would return null, and the
// slow path would only line-count the first MAX_FILES untracked
// entries — leaving `filesCount: 501` paired with a `linesAdded` that
// missed the other 451 files.
const quickStats =
(shortstatOut != null && parseShortstat(shortstatOut)) || EMPTY_STATS;
if (quickStats.filesCount + untrackedCount > MAX_FILES_FOR_DETAILS) {
return {
stats: {
...quickStats,
filesCount: quickStats.filesCount + untrackedCount,
},
perFileStats: new Map(),
};
}
// Numstat gives us +/- counts; name-status tells us *why* a row exists
// (D = deleted, M = modified, R<score> = rename, etc.). We need both
// because numstat alone can't distinguish a delete (`0\tN\tpath`) from
// a heavy edit that drops N lines.
const [numstatOut, nameStatusOut] = await Promise.all([
runGit(
[
'--no-optional-locks',
'diff',
'--no-ext-diff',
'--no-textconv',
'HEAD',
'--numstat',
'-z',
],
gitRoot,
),
runGit(
[
'--no-optional-locks',
'diff',
'--no-ext-diff',
'--no-textconv',
'HEAD',
'--name-status',
'-z',
],
gitRoot,
),
]);
if (numstatOut == null) return null;
const { stats, perFileStats } = parseGitNumstat(numstatOut);
const deletedPaths =
nameStatusOut != null ? parseDeletedFromNameStatus(nameStatusOut) : null;
if (deletedPaths && deletedPaths.size > 0) {
for (const [filename, s] of perFileStats) {
if (deletedPaths.has(filename)) s.isDeleted = true;
}
}
if (untrackedCount > 0) {
// Count every untracked file in the totals, even if the per-file map is
// already full. Otherwise `filesCount` under-reports whenever tracked
// changes already fill the `MAX_FILES` slot.
stats.filesCount += untrackedCount;
const untrackedPaths = splitNulDelimited(untrackedOut);
// Read line counts for *every* untracked path that survived the
// `>MAX_FILES_FOR_DETAILS` fast-path filter (so up to ~500 files at the
// outer cap, not just the first MAX_FILES). Otherwise a workspace with
// 51-500 untracked files would surface in the header as e.g. "60 files
// changed, +50 lines" — the +50 only covering the first 50 files,
// bypassing the contributions of the remaining 10. Concurrency is
// bounded to MAX_FILES so peak heap stays around
// `MAX_FILES * UNTRACKED_READ_CHUNK_BYTES` (~3.2 MB) regardless of how
// many untracked files are in the slow-path window.
const lineStats = await mapWithConcurrency(
untrackedPaths,
MAX_FILES,
(relPath) => countUntrackedLines(path.join(gitRoot, relPath)),
);
for (const s of lineStats) stats.linesAdded += s.added;
// Per-file rendering still caps at MAX_FILES — only the first
// `remainingSlots` untracked entries become visible rows. The rest are
// already folded into `linesAdded` above and into `filesCount`, so
// `hiddenCount` covers them faithfully on the renderer side.
const remainingSlots = Math.max(0, MAX_FILES - perFileStats.size);
const visibleCount = Math.min(remainingSlots, untrackedPaths.length);
for (let i = 0; i < visibleCount; i++) {
const relPath = untrackedPaths[i] ?? '';
const u = lineStats[i] ?? {
added: 0,
isBinary: false,
truncated: false,
};
perFileStats.set(relPath, {
added: u.added,
removed: 0,
isBinary: u.isBinary,
isUntracked: true,
truncated: u.truncated,
});
}
}
return { stats, perFileStats };
}
/**
* Fetch structured hunks for the current working tree vs HEAD. Separate
* from `fetchGitDiff` so callers that only need stats do not pay the full
* diff cost.
*
* NOTE on memory: this reads the full `git diff HEAD` stdout via `execFile`
* before applying parser caps (`MAX_FILES`, `MAX_DIFF_SIZE_BYTES`,
* `MAX_LINES_PER_FILE`). For very large diffs we can buffer up to the
* `runGit` `maxBuffer` (64 MB) before dropping content. Streaming the
* parser would let us terminate `git` early at `MAX_FILES`; that's a
* reasonable follow-up but out of scope for this utility's first cut.
*/
export async function fetchGitDiffHunks(
cwd: string,
): Promise<Map<string, Hunk[]>> {
// Walk ancestors once; reuse for the transient-state probe and the diff
// call. Running from the repo root also keeps hunk keys repo-root-relative
// regardless of which subdirectory the caller is in.
const gitRoot = findGitRoot(cwd);
if (!gitRoot) return new Map();
if (await isInTransientGitState(gitRoot)) return new Map();
// Plain `git diff` honors both `GIT_EXTERNAL_DIFF` / `diff.<name>.command`
// (blocked by `--no-ext-diff`) AND .gitattributes-driven textconv filters
// like `diff.<name>.textconv` (blocked by `--no-textconv`) — independent
// command-execution surfaces, both of which we have to disable on this
// read-only utility. The stats variants in `fetchGitDiff` already bypass
// both, but plain diff fires both unless told not to.
const diffOut = await runGit(
['--no-optional-locks', 'diff', '--no-ext-diff', '--no-textconv', 'HEAD'],
gitRoot,
);
if (diffOut == null) return new Map();
return parseGitDiff(diffOut);
}
/**
* Fetch structured hunks for a single file (working tree vs HEAD). Cheaper than
* `fetchGitDiffHunks`, which diffs the whole tree — this is for on-demand
* rendering of one file in the diff viewer.
*
* `filePath` may be a repo-root-relative path or an absolute path inside the
* repo (the daemon passes the workspace-sandboxed absolute path). Relative
* inputs reject absolute prefixes, drive letters, and `..` traversal; absolute
* inputs are rejected when they fall outside the git root. Both forms are
* normalized to a git-root-relative path before any git call, so the path can
* never escape the repository.
*
* Untracked files (which `git diff HEAD` omits) are synthesized as a single
* all-added hunk by reading the file, so the viewer can show new files like any
* other addition. `truncated` is set whenever the per-file caps cut content on
* either path (parser cap for tracked diffs, byte/line caps for synthesized
* untracked ones). Returns `null` for non-repos, transient states, paths
* outside the repo, binary or unreadable untracked files, and tracked files
* with no changes.
*/
export async function fetchGitDiffHunksForFile(
cwd: string,
filePath: string,
oldPath?: string,
): Promise<GitDiffFileHunks | null> {
const gitRoot = findGitRoot(cwd);
if (!gitRoot) return null;
const relPath = toRepoRelativePath(gitRoot, filePath);
if (relPath === null) return null;
if (await isInTransientGitState(gitRoot)) return null;
// For a rename, include the pre-rename path with rename detection so git
// diffs old→new content instead of reporting the new path as fully added
// (a single-path pathspec defeats rename detection).
const oldRelPath =
oldPath != null ? toRepoRelativePath(gitRoot, oldPath) : null;
const diffArgs = [
'--no-optional-locks',
'diff',
'--no-ext-diff',
'--no-textconv',
];
if (oldRelPath != null) diffArgs.push('-M');
diffArgs.push('HEAD', '--');
if (oldRelPath != null) diffArgs.push(oldRelPath);
diffArgs.push(relPath);
const diffOut = await runGit(diffArgs, gitRoot);
if (diffOut == null) return null;
const truncatedPaths = new Set<string>();
const parsed = parseGitDiff(diffOut, truncatedPaths);
// A single-file diff yields at most one entry; return its hunks regardless of
// the exact header key (which may carry rename / C-style-quote formatting).
if (parsed.size > 0) {
const [key, hunks] = parsed.entries().next().value as [string, Hunk[]];
return { hunks: hunks ?? [], truncated: truncatedPaths.has(key) };
}
// No tracked diff: synthesize an all-added hunk only for a genuinely
// untracked (and not ignored) file, matching the `--exclude-standard` listing
// that drives the diff file list. A tracked-but-unchanged or ignored file
// yields nothing here and returns null.
const untrackedOut = await runGit(
[
'--no-optional-locks',
'ls-files',
'--others',
'--exclude-standard',
'--',
relPath,
],
gitRoot,
);
if (untrackedOut && untrackedOut.trim().length > 0) {
return synthesizeUntrackedHunk(gitRoot, relPath);
}
return null;
}
/**
* Normalize a caller-supplied path (relative or absolute) to a git-root-relative
* path, or `null` when it escapes the repo. Relative inputs reject absolute
* prefixes, drive letters, and `..` segments; absolute inputs are mapped through
* `path.relative` and rejected when the result climbs out of the root.
*/
function toRepoRelativePath(gitRoot: string, filePath: string): string | null {
if (!path.isAbsolute(filePath)) {
if (filePath.length === 0) return null;
if (filePath.startsWith('/') || filePath.startsWith('\\')) return null;
if (/^[A-Za-z]:/.test(filePath)) return null;
if (filePath.split(/[\\/]/).some((segment) => segment === '..'))
return null;
return filePath;
}
const rel = path.relative(gitRoot, filePath);
// Reject only a real climb-out (`..` or `../…`), not a literal `..foo`
// filename at the root, which a bare `startsWith('..')` would over-reject.
if (
rel === '' ||
rel === '..' ||
rel.startsWith(`..${path.sep}`) ||
path.isAbsolute(rel)
)
return null;
return rel;
}
/**
* Build a single all-added hunk from an untracked file's content, capped by
* `MAX_DIFF_SIZE_BYTES` / `MAX_LINES_PER_FILE` — `truncated` reports when
* either cap actually cut content, so the caller can say so instead of
* presenting a silently incomplete file. Binary or unreadable files return
* `null` so the caller surfaces them without an inline diff.
*/
async function synthesizeUntrackedHunk(
gitRoot: string,
filePath: string,
): Promise<GitDiffFileHunks | null> {
const absPath = path.join(gitRoot, filePath);
// lstat before open: `ls-files --others` can list FIFOs whose open() blocks
// forever waiting on a writer. Gate on regular files (as countUntrackedLines
// does) so expanding an untracked FIFO can't hang the daemon's event loop.
try {
const lst = await lstat(absPath);
if (!lst.isFile()) return null;
} catch {
return null;
}
let fh;
try {
fh = await open(absPath, getUntrackedOpenFlags());
} catch {
return null;
}
try {
const st = await fh.stat();
if (!st.isFile()) return null;
const cap = Math.min(st.size, MAX_DIFF_SIZE_BYTES);
const buf = Buffer.allocUnsafe(cap);
let offset = 0;
while (offset < cap) {
const { bytesRead } = await fh.read(buf, offset, cap - offset, offset);
if (bytesRead === 0) break;
offset += bytesRead;
}
// Binary sniff on the same window git uses (a NUL in the first 8 KB).
const sniffEnd = Math.min(offset, BINARY_SNIFF_BYTES);
for (let i = 0; i < sniffEnd; i++) {
if (buf[i] === 0) return null;
}
const lines = buf.toString('utf8', 0, offset).split('\n');
// Drop the trailing empty element produced by a final newline.
if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();
const capped = lines.slice(0, MAX_LINES_PER_FILE);
const truncated =
st.size > MAX_DIFF_SIZE_BYTES || lines.length > capped.length;
if (capped.length === 0) return { hunks: [], truncated };
return {
hunks: [
{
oldStart: 0,
oldLines: 0,
newStart: 1,
newLines: capped.length,
lines: capped.map((line) => '+' + line),
},
],
truncated,
};
} catch {
return null;
} finally {
await fh.close().catch(() => {});
}
}
/**
* Parse `git diff --numstat -z` output.
*
* Wire format (stable per `git-diff(1)`):
* - Non-rename: `<added>\t<removed>\t<path>\0`
* - Rename: `<added>\t<removed>\t\0<oldpath>\0<newpath>\0`
*
* Using `-z` (vs the default newline-delimited form) keeps paths byte-accurate:
* tabs, newlines, and non-ASCII characters all round-trip without git's
* C-style quoting, so `perFileStats` keys match the real on-disk filenames.
*
* Binary files use `-` for both counts. Only the first `MAX_FILES` entries are
* retained in `perFileStats`; totals account for every entry.
*/
interface NumstatEntry {
path: string;
oldPath?: string;
added: number;
removed: number;
isBinary: boolean;
}
function forEachNumstatEntry(
stdout: string,
visit: (entry: NumstatEntry) => void,
): void {
const tokens = stdout.split('\0');
if (tokens.length > 0 && tokens[tokens.length - 1] === '') tokens.pop();
let pending: Omit<NumstatEntry, 'path' | 'oldPath'> | null = null;
let renameOld: string | null = null;
for (const token of tokens) {
if (pending) {
if (renameOld === null) {
renameOld = token;
continue;
}
visit({ ...pending, path: token, oldPath: renameOld });
pending = null;
renameOld = null;
continue;
}
const firstTab = token.indexOf('\t');
if (firstTab < 0) continue;
const secondTab = token.indexOf('\t', firstTab + 1);
if (secondTab < 0) continue;
const addStr = token.slice(0, firstTab);
const remStr = token.slice(firstTab + 1, secondTab);
const path = token.slice(secondTab + 1);
const isBinary = addStr === '-' || remStr === '-';
const added = isBinary ? 0 : parseInt(addStr, 10) || 0;
const removed = isBinary ? 0 : parseInt(remStr, 10) || 0;
if (path === '') {
pending = { added, removed, isBinary };
continue;
}
visit({ path, added, removed, isBinary });
}
}
export function parseGitNumstat(stdout: string): GitDiffResult {
let added = 0;
let removed = 0;
let validFileCount = 0;
const perFileStats = new Map<string, PerFileStats>();
forEachNumstatEntry(stdout, (entry) => {
commitEntry(
entry.path,
entry.added,
entry.removed,
entry.isBinary,
entry.oldPath,
);
});
function commitEntry(
filePath: string,
fileAdded: number,
fileRemoved: number,
isBinary: boolean,
oldPath?: string,
): void {
validFileCount++;
added += fileAdded;
removed += fileRemoved;
if (perFileStats.size < MAX_FILES) {
perFileStats.set(filePath, {
added: fileAdded,
removed: fileRemoved,
isBinary,
...(oldPath ? { oldPath } : {}),
});
}
}
return {
stats: {
filesCount: validFileCount,
linesAdded: added,
linesRemoved: removed,
},
perFileStats,
};
}
/**
* Parse unified diff output into per-file hunks.
*
* Limits applied:
* - Stop once `MAX_FILES` files have been collected.
* - Skip files whose raw diff exceeds `MAX_DIFF_SIZE_BYTES`.
* - Truncate per-file content at `MAX_LINES_PER_FILE` lines; when
* `truncatedPaths` is provided, every file that actually lost lines to that
* cap is recorded there so callers can surface the truncation instead of
* presenting a silently incomplete diff.
*/
export function parseGitDiff(
stdout: string,
truncatedPaths?: Set<string>,
): Map<string, Hunk[]> {
const result = new Map<string, Hunk[]>();
if (!stdout.trim()) return result;
const fileDiffs = stdout.split(/^diff --git /m).filter(Boolean);
for (const fileDiff of fileDiffs) {
if (result.size >= MAX_FILES) break;
// Use UTF-8 byte length (not JS string .length, which counts UTF-16 code
// units) so the cap matches the documented `MAX_DIFF_SIZE_BYTES` semantic
// on non-ASCII diffs.
if (Buffer.byteLength(fileDiff, 'utf8') > MAX_DIFF_SIZE_BYTES) continue;
const lines = fileDiff.split('\n');
// The `diff --git a/X b/Y` header is ambiguous for paths that contain
// ` b/` (e.g. `a b/c.txt` yields `diff --git a/a b/c.txt b/a b/c.txt`).
// Prefer the unambiguous metadata that follows: `rename to`, `copy to`,
// or the `+++ b/<path>` / `--- a/<path>` lines. Git appends a trailing
// TAB to those paths when they contain whitespace — that's our real
// end-of-path marker.
const filePath = extractFilePath(lines);
if (filePath === null) continue;
const fileHunks: Hunk[] = [];
let currentHunk: Hunk | null = null;
let lineCount = 0;
for (let i = 1; i < lines.length; i++) {
const line = lines[i] ?? '';
const hunkMatch = line.match(
/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/,
);
if (hunkMatch) {
if (currentHunk) fileHunks.push(currentHunk);
currentHunk = {
oldStart: parseInt(hunkMatch[1] ?? '0', 10),
oldLines: parseInt(hunkMatch[2] ?? '1', 10),
newStart: parseInt(hunkMatch[3] ?? '0', 10),
newLines: parseInt(hunkMatch[4] ?? '1', 10),
lines: [],
};
continue;
}
// Pre-hunk metadata is only skipped before the first `@@` header. Once
// inside a hunk, a line like `---foo` is a removed source line whose
// content happens to start with `---`, and must not be dropped.
if (!currentHunk) {
continue;
}
if (
line.startsWith('+') ||
line.startsWith('-') ||
line.startsWith(' ')
) {
if (lineCount >= MAX_LINES_PER_FILE) {
// A content line exists beyond the cap, so this file's hunks are
// genuinely incomplete (an exactly-at-cap diff never reaches here).
truncatedPaths?.add(filePath);
break;
}
// Force a flat string copy to break V8 sliced-string references so the
// whole raw diff can be GC'd once parsing finishes.
currentHunk.lines.push('' + line);
lineCount++;
} else if (line.startsWith('\\')) {
// "\ No newline at end of file" — metadata the viewer renders as a
// marker. Keep it so a trailing-newline-only edit isn't shown as
// identical removed/added lines. Not counted against the content cap.
currentHunk.lines.push('' + line);
}
}
if (currentHunk) fileHunks.push(currentHunk);
if (fileHunks.length > 0) result.set(filePath, fileHunks);
}
return result;
}
/**
* Decode a path field from a `diff --git` header — handles both unquoted
* (`b/foo.txt`) and C-style quoted (`"b/tab\there.txt"`) forms.
*
* Git wraps a path in `"..."` and applies C-style escaping (`\t`, `\n`,
* `\r`, `\"`, `\\`, plus octal `\NNN` for non-ASCII bytes) whenever the
* raw path contains a character that breaks the simple space-delimited
* format. `core.quotepath=false` disables ONLY the octal escaping for
* non-ASCII bytes; control chars and quotes are still escaped, so we
* must decode them ourselves to preserve the real on-disk filename.
*
* Octal escapes are decoded as raw byte values then UTF-8-decoded en
* masse so multi-byte sequences like `\346\226\207` (文) round-trip
* correctly even though we never set quotepath=true ourselves.
*/
export function unquoteCStylePath(s: string): string {
if (!s.startsWith('"') || !s.endsWith('"') || s.length < 2) return s;
const inner = s.slice(1, -1);
// Build raw bytes first so octal `\NNN` sequences (each one byte of a
// potentially multi-byte UTF-8 character) reassemble correctly. We walk by
// Unicode code points (not UTF-16 code units), so non-BMP characters such as
// emoji that may appear inside a quoted path under `core.quotepath=false`
// round-trip through UTF-8 instead of being split into lone surrogates.
const bytes: number[] = [];
let i = 0;
while (i < inner.length) {
const c = inner.charCodeAt(i);
if (c !== 0x5c /* '\' */) {
const cp = inner.codePointAt(i);
if (cp === undefined) {
i++;
continue;
}
const ch = String.fromCodePoint(cp);
bytes.push(...Buffer.from(ch, 'utf8'));
i += ch.length;
continue;
}
const next = inner[i + 1];
if (next === undefined) {
bytes.push(0x5c);
i++;
continue;
}
switch (next) {
case 'a':
bytes.push(0x07);
i += 2;
break;
case 'b':
bytes.push(0x08);
i += 2;
break;
case 'f':
bytes.push(0x0c);
i += 2;
break;
case 'v':
bytes.push(0x0b);
i += 2;
break;
case 't':
bytes.push(0x09);
i += 2;
break;
case 'n':
bytes.push(0x0a);
i += 2;
break;
case 'r':
bytes.push(0x0d);
i += 2;
break;
case '"':
bytes.push(0x22);
i += 2;
break;
case '\\':
bytes.push(0x5c);
i += 2;
break;
default:
if (next >= '0' && next <= '7') {
let octal = '';
while (
octal.length < 3 &&
i + 1 + octal.length < inner.length &&
(inner[i + 1 + octal.length] ?? '') >= '0' &&
(inner[i + 1 + octal.length] ?? '') <= '7'
) {
octal += inner[i + 1 + octal.length];
}
bytes.push(parseInt(octal, 8) & 0xff);
i += 1 + octal.length;
} else {
bytes.push(...Buffer.from(next, 'utf8'));
i += 2;
}
}
}
return Buffer.from(bytes).toString('utf8');
}
/**
* Extract the real filename from a `diff --git` file block, avoiding the
* ambiguity of `diff --git a/X b/Y` when `X` itself contains ` b/`.
*
* Preference order:
* 1. `rename to <path>` / `copy to <path>` — the authoritative new name.
* 2. `+++ b/<path>` — the new-side path for in-place modifications. When
* the file was deleted the line reads `+++ /dev/null`; we then fall back
* to `--- a/<path>` for the old name.
* 3. `--- a/<path>` alone — for the rare case where `+++` is absent.
*
* Each candidate path goes through `stripTab` (cut at the trailing TAB git
* appends after whitespace-containing paths) and `unquoteCStylePath`
* (decode `"..."` C-quoted form for paths whose raw bytes include tabs,
* newlines, quotes, or non-ASCII characters that core.quotepath does not
* suppress). Without the unquote step, fetchGitDiffHunks would silently
* drop hunks for any tracked file whose name contains those characters.
*
* Returns `null` when the block has no hunks or no recognizable path line
* (mode-only changes, for example).
*/
function extractFilePath(lines: string[]): string | null {
let plus: string | null = null;
let minus: string | null = null;
let renameTo: string | null = null;
let copyTo: string | null = null;
for (const line of lines) {
if (line.startsWith('@@ ')) break;
if (line.startsWith('+++ ')) plus = line.slice(4);
else if (line.startsWith('--- ')) minus = line.slice(4);
else if (line.startsWith('rename to ')) renameTo = line.slice(10);
else if (line.startsWith('copy to ')) copyTo = line.slice(8);
}
const stripTab = (s: string): string => {
const t = s.indexOf('\t');
return t >= 0 ? s.slice(0, t) : s;
};
// Strip the TAB-end-of-path marker first, then C-unquote — git emits the
// TAB AFTER the closing quote on quoted paths.
const normalize = (s: string): string => unquoteCStylePath(stripTab(s));
if (renameTo !== null) return normalize(renameTo);
if (copyTo !== null) return normalize(copyTo);
if (plus !== null) {
const p = normalize(plus);
if (p !== '/dev/null' && p.startsWith('b/')) return p.slice(2);
// Deleted file — fall back to the old path.
if (minus !== null) {
const m = normalize(minus);
if (m !== '/dev/null' && m.startsWith('a/')) return m.slice(2);
}
return null;
}
if (minus !== null) {
const m = normalize(minus);
if (m !== '/dev/null' && m.startsWith('a/')) return m.slice(2);
}
return null;
}
/**
* Parse `git diff --shortstat` output, e.g.
* ` 3 files changed, 42 insertions(+), 7 deletions(-)`.
*
* The regex is anchored (line start/end with the `m` flag) and uses single
* literal spaces plus bounded `\d{1,10}` digit runs. This closes CodeQL alert
* #137: the previous unanchored form with `\s+` and `\d+` in nested optional
* groups could backtrack polynomially on crafted strings of `0`s.
*/
export function parseShortstat(stdout: string): GitDiffStats | null {
const match = stdout.match(
/^ ?(\d{1,10}) files? changed(?:, (\d{1,10}) insertions?\(\+\))?(?:, (\d{1,10}) deletions?\(-\))?$/m,
);
if (!match) return null;
return {
filesCount: parseInt(match[1] ?? '0', 10),
linesAdded: parseInt(match[2] ?? '0', 10),
linesRemoved: parseInt(match[3] ?? '0', 10),
};
}
/**
* Parse `git diff HEAD --name-status -z` output and return the paths whose
* status is `D` (deleted in the worktree).
*
* Wire format with `-z`: `<status>\0<path>\0` per entry, except renames and
* copies which span three tokens: `R<score>\0<oldpath>\0<newpath>\0` (and
* `C<score>\0...`). We only care about deletions here, so renames/copies
* are walked past — neither half of a rename pair is "deleted" in the
* user-facing sense (the file still exists under the new name).
*/
export function parseDeletedFromNameStatus(stdout: string): Set<string> {
const tokens = stdout.split('\0');
if (tokens.length > 0 && tokens[tokens.length - 1] === '') tokens.pop();
const deleted = new Set<string>();
let i = 0;
while (i < tokens.length) {
const status = tokens[i] ?? '';
i++;
if (status === '') continue;
const head = status[0];
// Rename / copy entries are followed by TWO path tokens.
if (head === 'R' || head === 'C') {
i += 2;
continue;
}
const path = tokens[i] ?? '';
i++;
if (head === 'D' && path !== '') deleted.add(path);
}
return deleted;
}
function countNulDelimited(stdout: string | null): number {
if (!stdout) return 0;
let count = 0;
for (let i = 0; i < stdout.length; i++) {
if (stdout.charCodeAt(i) === 0) count++;
}
return count;
}
function splitNulDelimited(stdout: string | null): string[] {
if (!stdout) return [];
return stdout.split('\0').filter(Boolean);
}
interface UntrackedLineStats {
added: number;
isBinary: boolean;
/** `true` when the file was larger than the read cap so `added` is a lower
* bound (the caller is expected to surface this so the user knows). */
truncated: boolean;
}
/**
* Count lines in an untracked file so the /diff totals include it. Reads up
* to `UNTRACKED_READ_CAP_BYTES`, bails on NUL in the first `BINARY_SNIFF_BYTES`
* (git's own heuristic), and swallows read errors into a zero-result so one
* unreadable file can't block the whole command. `truncated` is set when
* `fstat(size) > bytesRead`, so the UI can mark partial counts honestly
* instead of silently under-reporting a 10 MB log as `+20k`.
*
* Uses `lstat` before `open` to gate on regular files only — git's
* `ls-files --others` can list FIFOs (whose `open()` would block forever
* waiting on a writer) and symlinks (whose target may live outside the
* worktree). Symlinks and non-regular files render as binary `~` rows.
*/
async function countUntrackedLines(
absPath: string,
): Promise<UntrackedLineStats> {
let st;
try {
st = await lstat(absPath);
} catch {
// File raced out from under ls-files (deleted, permission revoked, etc.).
// Surface it as a binary row to be consistent with the open-failure /
// non-regular-file branches below — `+0 (new)` would lie about it being
// an empty text file when we genuinely have no signal.
return { added: 0, isBinary: true, truncated: false };
}
if (!st.isFile()) {
return { added: 0, isBinary: true, truncated: false };
}
let fh;
try {
fh = await open(absPath, getUntrackedOpenFlags());
} catch {
// ELOOP from O_NOFOLLOW (path raced into a symlink between lstat and
// open) and any other open error all collapse to a binary row so the
// file appears once in the listing without contributing line counts.
return { added: 0, isBinary: true, truncated: false };
}
try {
// Stream the file in fixed-size chunks instead of allocating one full
// `UNTRACKED_READ_CAP_BYTES` buffer per call. With up to MAX_FILES
// line-counts running concurrently the heap footprint stays around
// `MAX_FILES * UNTRACKED_READ_CHUNK_BYTES` (~3.2 MB) rather than the
// ~50 MB a one-shot full-cap alloc would have cost on a constrained
// host. Behavior (line count, binary sniff, truncation flag) is
// identical to the single-shot path.
const buf = Buffer.allocUnsafe(UNTRACKED_READ_CHUNK_BYTES);
let totalRead = 0;
let lines = 0;
let lastByte = -1;
let sniffedBytes = 0;
while (totalRead < UNTRACKED_READ_CAP_BYTES) {
const remaining = UNTRACKED_READ_CAP_BYTES - totalRead;
const toRead = Math.min(buf.length, remaining);
const { bytesRead } = await fh.read(buf, 0, toRead, totalRead);
if (bytesRead === 0) break;
// Binary sniff on the first BINARY_SNIFF_BYTES across cumulative reads.
// Almost always completes inside the first chunk because chunk size
// (64 KB) is much larger than the sniff window (8 KB).
if (sniffedBytes < BINARY_SNIFF_BYTES) {