-
Notifications
You must be signed in to change notification settings - Fork 498
Expand file tree
/
Copy pathgit_helpers.test.cjs
More file actions
723 lines (595 loc) · 29.9 KB
/
Copy pathgit_helpers.test.cjs
File metadata and controls
723 lines (595 loc) · 29.9 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
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
describe("git_helpers.cjs", () => {
let originalCore;
beforeEach(() => {
// Save existing core and provide a minimal no-op stub if not already set,
// matching the guarantee that shim.cjs provides in production.
originalCore = global.core;
if (!global.core) {
global.core = {
debug: () => {},
info: () => {},
warning: () => {},
error: () => {},
setFailed: () => {},
};
}
});
afterEach(() => {
global.core = originalCore;
});
function mockCoreWarning() {
global.core.warning = vi.fn();
return global.core.warning;
}
describe("execGitSync", () => {
it("should export execGitSync function", async () => {
const { execGitSync } = await import("./git_helpers.cjs");
expect(typeof execGitSync).toBe("function");
});
it("should execute git commands safely", async () => {
const { execGitSync } = await import("./git_helpers.cjs");
// Test with a simple git command that should work
const result = execGitSync(["--version"]);
expect(result).toContain("git version");
});
it("should handle git command failures", async () => {
const { execGitSync } = await import("./git_helpers.cjs");
// Test with an invalid git command
expect(() => {
execGitSync(["invalid-command"]);
}).toThrow();
});
it("should prevent shell injection in branch names", async () => {
const { execGitSync } = await import("./git_helpers.cjs");
// Test with malicious branch name
const maliciousBranch = "feature; rm -rf /";
// This should fail because the branch doesn't exist,
// but importantly, it should NOT execute "rm -rf /"
expect(() => {
execGitSync(["rev-parse", maliciousBranch]);
}).toThrow();
});
it("should treat special characters as literals", async () => {
const { execGitSync } = await import("./git_helpers.cjs");
const specialBranches = ["feature && echo hacked", "feature | cat /etc/passwd", "feature$(whoami)", "feature`whoami`"];
for (const branch of specialBranches) {
// All should fail with git error, not execute shell commands
expect(() => {
execGitSync(["rev-parse", branch]);
}).toThrow();
}
});
it("should pass options to spawnSync", async () => {
const { execGitSync } = await import("./git_helpers.cjs");
// Test that options are properly passed through
const result = execGitSync(["--version"], { encoding: "utf8" });
expect(typeof result).toBe("string");
expect(result).toContain("git version");
});
it("should throw actionable ENOBUFS error when maxBuffer is exceeded", async () => {
const { execGitSync } = await import("./git_helpers.cjs");
// Use a tiny maxBuffer to trigger ENOBUFS on any git output
expect(() => {
execGitSync(["--version"], { maxBuffer: 1 });
}).toThrow(/ENOBUFS|buffer limit/i);
});
it("should return stdout from successful commands", async () => {
const { execGitSync } = await import("./git_helpers.cjs");
// Use git --version which always succeeds
const result = execGitSync(["--version"]);
expect(typeof result).toBe("string");
expect(result).toContain("git version");
});
it("should not call core.error when suppressLogs is true", async () => {
const { execGitSync } = await import("./git_helpers.cjs");
const errorLogs = [];
const debugLogs = [];
const originalCore = global.core;
global.core = {
debug: msg => debugLogs.push(msg),
error: msg => errorLogs.push(msg),
};
try {
// Use an invalid git command that will fail
try {
execGitSync(["rev-parse", "nonexistent-branch-that-does-not-exist"], { suppressLogs: true });
} catch (e) {
// Expected to fail
}
// core.error should NOT have been called
expect(errorLogs).toHaveLength(0);
// core.debug should have captured the failure details including exit status
expect(debugLogs.some(log => log.includes("Git command failed (expected)"))).toBe(true);
expect(debugLogs.some(log => log.includes("Exit status:"))).toBe(true);
} finally {
global.core = originalCore;
}
});
it("should call core.error when suppressLogs is false (default)", async () => {
const { execGitSync } = await import("./git_helpers.cjs");
const errorLogs = [];
const originalCore = global.core;
global.core = {
debug: () => {},
error: msg => errorLogs.push(msg),
};
try {
try {
execGitSync(["rev-parse", "nonexistent-branch-that-does-not-exist"]);
} catch (e) {
// Expected to fail
}
// core.error should have been called
expect(errorLogs.length).toBeGreaterThan(0);
} finally {
global.core = originalCore;
}
});
it("should redact credentials from logged commands", async () => {
const { execGitSync } = await import("./git_helpers.cjs");
// Mock core.debug to capture logged output
const debugLogs = [];
const originalCore = global.core;
global.core = {
debug: msg => debugLogs.push(msg),
error: () => {},
};
try {
// Use a git command that doesn't require network access
// We'll use 'ls-remote' with --exit-code and a URL with credentials
// This will fail quickly without attempting network access
try {
execGitSync(["config", "--get", "remote.https://user:token@github.com/repo.git.url"]);
} catch (e) {
// Expected to fail, we're just checking the logging
}
// Check that credentials were redacted in the log
const configLog = debugLogs.find(log => log.includes("git config"));
expect(configLog).toBeDefined();
expect(configLog).toContain("https://***@github.com/repo.git");
expect(configLog).not.toContain("user:token");
} finally {
global.core = originalCore;
}
});
});
describe("getGitAuthEnv", () => {
let originalEnv;
beforeEach(() => {
originalEnv = { ...process.env };
});
afterEach(() => {
for (const key of Object.keys(process.env)) {
if (!(key in originalEnv)) {
delete process.env[key];
}
}
Object.assign(process.env, originalEnv);
});
it("should export getGitAuthEnv function", async () => {
const { getGitAuthEnv } = await import("./git_helpers.cjs");
expect(typeof getGitAuthEnv).toBe("function");
});
it("should return GIT_CONFIG_* env vars when token is provided", async () => {
const { getGitAuthEnv } = await import("./git_helpers.cjs");
const env = getGitAuthEnv("my-test-token");
expect(env).toHaveProperty("GIT_CONFIG_COUNT", "1");
expect(env).toHaveProperty("GIT_CONFIG_KEY_0");
expect(env).toHaveProperty("GIT_CONFIG_VALUE_0");
expect(env.GIT_CONFIG_VALUE_0).toContain("Authorization: basic");
});
it("should use GITHUB_TOKEN env var when no token is passed", async () => {
const { getGitAuthEnv } = await import("./git_helpers.cjs");
process.env.GITHUB_TOKEN = "env-test-token";
const env = getGitAuthEnv();
expect(env).toHaveProperty("GIT_CONFIG_COUNT", "1");
expect(env.GIT_CONFIG_VALUE_0).toBeDefined();
// Value should be base64 of "x-access-token:env-test-token"
const expected = Buffer.from("x-access-token:env-test-token").toString("base64");
expect(env.GIT_CONFIG_VALUE_0).toContain(expected);
});
it("should prefer the provided token over GITHUB_TOKEN", async () => {
const { getGitAuthEnv } = await import("./git_helpers.cjs");
process.env.GITHUB_TOKEN = "env-token";
const env = getGitAuthEnv("override-token");
const expectedBase64 = Buffer.from("x-access-token:override-token").toString("base64");
expect(env.GIT_CONFIG_VALUE_0).toContain(expectedBase64);
// Should NOT contain the env token
const envBase64 = Buffer.from("x-access-token:env-token").toString("base64");
expect(env.GIT_CONFIG_VALUE_0).not.toContain(envBase64);
});
it("should return empty object when no token is available", async () => {
const { getGitAuthEnv } = await import("./git_helpers.cjs");
delete process.env.GITHUB_TOKEN;
const env = getGitAuthEnv();
expect(env).toEqual({});
});
it("should scope extraheader to GITHUB_SERVER_URL", async () => {
const { getGitAuthEnv } = await import("./git_helpers.cjs");
process.env.GITHUB_SERVER_URL = "https://github.example.com";
const env = getGitAuthEnv("test-token");
expect(env.GIT_CONFIG_KEY_0).toBe("http.https://github.example.com/.extraheader");
});
it("should default server URL to https://github.com", async () => {
const { getGitAuthEnv } = await import("./git_helpers.cjs");
delete process.env.GITHUB_SERVER_URL;
const env = getGitAuthEnv("test-token");
expect(env.GIT_CONFIG_KEY_0).toBe("http.https://github.com/.extraheader");
});
it("should strip trailing slash from server URL", async () => {
const { getGitAuthEnv } = await import("./git_helpers.cjs");
process.env.GITHUB_SERVER_URL = "https://github.example.com/";
const env = getGitAuthEnv("test-token");
expect(env.GIT_CONFIG_KEY_0).toBe("http.https://github.example.com/.extraheader");
});
});
describe("ensureFullHistoryForBundle", () => {
it("should unshallow the repository when the repository is shallow", async () => {
const { ensureFullHistoryForBundle } = await import("./git_helpers.cjs");
const execApi = {
getExecOutput: vi.fn().mockResolvedValue({ stdout: "true\n" }),
exec: vi.fn().mockResolvedValue(0),
};
const options = { cwd: "/tmp/repo" };
await ensureFullHistoryForBundle(execApi, options);
expect(execApi.getExecOutput).toHaveBeenCalledWith("git", ["rev-parse", "--is-shallow-repository"], options);
expect(execApi.exec).toHaveBeenCalledWith("git", ["fetch", "--unshallow", "origin"], options);
});
it("should not fetch full history when the repository is not shallow", async () => {
const { ensureFullHistoryForBundle } = await import("./git_helpers.cjs");
const execApi = {
getExecOutput: vi.fn().mockResolvedValue({ stdout: "false\n" }),
exec: vi.fn().mockResolvedValue(0),
};
await ensureFullHistoryForBundle(execApi);
expect(execApi.exec).not.toHaveBeenCalled();
});
it("should skip history probing when shallow status cannot be determined", async () => {
const { ensureFullHistoryForBundle } = await import("./git_helpers.cjs");
const warning = mockCoreWarning();
const execApi = {
getExecOutput: vi.fn().mockRejectedValue(new Error("not a git repository")),
exec: vi.fn().mockResolvedValue(0),
};
await ensureFullHistoryForBundle(execApi);
expect(execApi.exec).not.toHaveBeenCalled();
expect(warning).toHaveBeenCalledTimes(1);
expect(warning).toHaveBeenCalledWith("Could not determine shallow repository status; skipping full-history fetch probe: not a git repository");
});
it("should warn with stringified non-error shallow status failures", async () => {
const { ensureFullHistoryForBundle } = await import("./git_helpers.cjs");
const warning = mockCoreWarning();
const execApi = {
getExecOutput: vi.fn().mockRejectedValue("unknown failure"),
exec: vi.fn().mockResolvedValue(0),
};
await ensureFullHistoryForBundle(execApi);
expect(execApi.exec).not.toHaveBeenCalled();
expect(warning).toHaveBeenCalledTimes(1);
expect(warning).toHaveBeenCalledWith("Could not determine shallow repository status; skipping full-history fetch probe: unknown failure");
});
it("should iteratively deepen origin/<base> when bundle prereqs are known and shallow", async () => {
const { ensureFullHistoryForBundle } = await import("./git_helpers.cjs");
const prereq = "a".repeat(40);
let deepenCalls = 0;
const execApi = {
getExecOutput: vi.fn().mockImplementation((cmd, args) => {
if (args[0] === "rev-parse" && args[1] === "--is-shallow-repository") {
return Promise.resolve({ stdout: "true\n" });
}
if (args[0] === "bundle" && args[1] === "verify") {
return Promise.resolve({
stdout: "",
stderr: `The bundle requires this ref:\n${prereq}\n`,
exitCode: 1,
});
}
if (args[0] === "merge-base" && args[1] === "--is-ancestor") {
// Become reachable only after the second deepen fetch.
return Promise.resolve({ exitCode: deepenCalls >= 2 ? 0 : 1, stdout: "", stderr: "" });
}
return Promise.resolve({ exitCode: 0, stdout: "", stderr: "" });
}),
exec: vi.fn().mockImplementation((cmd, args) => {
if (args && args[0] === "fetch" && args[1] && args[1].startsWith("--deepen=")) {
deepenCalls++;
}
return Promise.resolve(0);
}),
};
await ensureFullHistoryForBundle(execApi, {}, { baseRef: "main", bundleFilePath: "/tmp/test.bundle" });
// Two deepen fetches before ancestry succeeds; no --unshallow.
const fetchCalls = execApi.exec.mock.calls.filter(c => c[1] && c[1][0] === "fetch");
expect(fetchCalls.length).toBe(2);
expect(fetchCalls[0][1]).toEqual(["fetch", "--deepen=50", "origin", "main"]);
expect(fetchCalls[1][1]).toEqual(["fetch", "--deepen=100", "origin", "main"]);
expect(execApi.exec).not.toHaveBeenCalledWith("git", ["fetch", "--unshallow", "origin"], expect.anything());
});
it("should skip deepening when bundle declares no prerequisites", async () => {
const { ensureFullHistoryForBundle } = await import("./git_helpers.cjs");
const execApi = {
getExecOutput: vi.fn().mockImplementation((cmd, args) => {
if (args[0] === "rev-parse") return Promise.resolve({ stdout: "true\n" });
if (args[0] === "bundle" && args[1] === "verify") {
return Promise.resolve({ stdout: "The bundle contains this ref:\ndeadbeef refs/heads/x\n", stderr: "", exitCode: 0 });
}
return Promise.resolve({ exitCode: 0, stdout: "", stderr: "" });
}),
exec: vi.fn().mockResolvedValue(0),
};
await ensureFullHistoryForBundle(execApi, {}, { baseRef: "main", bundleFilePath: "/tmp/test.bundle" });
expect(execApi.exec).not.toHaveBeenCalled();
});
it("should skip deepening when prereqs are already reachable from origin/<base>", async () => {
const { ensureFullHistoryForBundle } = await import("./git_helpers.cjs");
const prereq = "b".repeat(40);
const execApi = {
getExecOutput: vi.fn().mockImplementation((cmd, args) => {
if (args[0] === "rev-parse") return Promise.resolve({ stdout: "true\n" });
if (args[0] === "bundle" && args[1] === "verify") {
return Promise.resolve({ stdout: `The bundle requires this ref:\n${prereq}\n`, stderr: "", exitCode: 0 });
}
if (args[0] === "merge-base" && args[1] === "--is-ancestor") {
return Promise.resolve({ exitCode: 0, stdout: "", stderr: "" });
}
return Promise.resolve({ exitCode: 0, stdout: "", stderr: "" });
}),
exec: vi.fn().mockResolvedValue(0),
};
await ensureFullHistoryForBundle(execApi, {}, { baseRef: "main", bundleFilePath: "/tmp/test.bundle" });
expect(execApi.exec).not.toHaveBeenCalled();
});
});
describe("isShallowOrSparseCheckout", () => {
const buildExecApi = handler => ({
getExecOutput: vi.fn().mockImplementation((cmd, args) => Promise.resolve(handler(cmd, args))),
});
it("should return true when repository is shallow", async () => {
const { isShallowOrSparseCheckout } = await import("./git_helpers.cjs");
const execApi = buildExecApi((cmd, args) => {
if (args[0] === "rev-parse" && args[1] === "--is-shallow-repository") {
return { exitCode: 0, stdout: "true\n", stderr: "" };
}
return { exitCode: 1, stdout: "", stderr: "" };
});
await expect(isShallowOrSparseCheckout(execApi)).resolves.toBe(true);
// Sparse probe must not run when shallow probe already returned true.
expect(execApi.getExecOutput).toHaveBeenCalledTimes(1);
});
it("should return true when sparse-checkout is enabled", async () => {
const { isShallowOrSparseCheckout } = await import("./git_helpers.cjs");
const execApi = buildExecApi((cmd, args) => {
if (args[0] === "rev-parse" && args[1] === "--is-shallow-repository") {
return { exitCode: 0, stdout: "false\n", stderr: "" };
}
if (args[0] === "config" && args[1] === "--get" && args[2] === "core.sparseCheckout") {
return { exitCode: 0, stdout: "true\n", stderr: "" };
}
return { exitCode: 1, stdout: "", stderr: "" };
});
await expect(isShallowOrSparseCheckout(execApi)).resolves.toBe(true);
});
it("should return false for a full, non-sparse clone", async () => {
const { isShallowOrSparseCheckout } = await import("./git_helpers.cjs");
const execApi = buildExecApi((cmd, args) => {
if (args[0] === "rev-parse" && args[1] === "--is-shallow-repository") {
return { exitCode: 0, stdout: "false\n", stderr: "" };
}
if (args[0] === "config" && args[1] === "--get" && args[2] === "core.sparseCheckout") {
// git config exits 1 when the key is not set.
return { exitCode: 1, stdout: "", stderr: "" };
}
return { exitCode: 0, stdout: "", stderr: "" };
});
await expect(isShallowOrSparseCheckout(execApi)).resolves.toBe(false);
});
it("should return false when both probes throw", async () => {
const { isShallowOrSparseCheckout } = await import("./git_helpers.cjs");
const execApi = {
getExecOutput: vi.fn().mockRejectedValue(new Error("git missing")),
};
await expect(isShallowOrSparseCheckout(execApi)).resolves.toBe(false);
});
it("should treat sparse-checkout value case-insensitively", async () => {
const { isShallowOrSparseCheckout } = await import("./git_helpers.cjs");
const execApi = buildExecApi((cmd, args) => {
if (args[0] === "rev-parse") {
return { exitCode: 0, stdout: "false\n", stderr: "" };
}
if (args[0] === "config") {
return { exitCode: 0, stdout: "True\n", stderr: "" };
}
return { exitCode: 1, stdout: "", stderr: "" };
});
await expect(isShallowOrSparseCheckout(execApi)).resolves.toBe(true);
});
});
describe("extractBundlePrerequisiteCommits", () => {
it("should return empty array for empty string", async () => {
const { extractBundlePrerequisiteCommits } = await import("./git_helpers.cjs");
expect(extractBundlePrerequisiteCommits("")).toEqual([]);
});
it("should return empty array when message does not mention prerequisite commits", async () => {
const { extractBundlePrerequisiteCommits } = await import("./git_helpers.cjs");
expect(extractBundlePrerequisiteCommits("fatal: failed to read bundle")).toEqual([]);
});
it("should return single SHA when one prerequisite commit is missing", async () => {
const { extractBundlePrerequisiteCommits } = await import("./git_helpers.cjs");
const message = "error: Repository lacks these prerequisite commits:\nerror: 172f87a830f57a29470efe7646d141069434a893";
expect(extractBundlePrerequisiteCommits(message)).toEqual(["172f87a830f57a29470efe7646d141069434a893"]);
});
it("should return multiple SHAs when multiple prerequisite commits are missing", async () => {
const { extractBundlePrerequisiteCommits } = await import("./git_helpers.cjs");
const message = ["error: Repository lacks these prerequisite commits:", "error: 172f87a830f57a29470efe7646d141069434a893", "error: aabbccddee1122334455667788990011aabbccdd"].join("\n");
const result = extractBundlePrerequisiteCommits(message);
expect(result).toEqual(["172f87a830f57a29470efe7646d141069434a893", "aabbccddee1122334455667788990011aabbccdd"]);
});
it("should deduplicate repeated SHAs", async () => {
const { extractBundlePrerequisiteCommits } = await import("./git_helpers.cjs");
const sha = "172f87a830f57a29470efe7646d141069434a893";
const message = `error: Repository lacks these prerequisite commits:\nerror: ${sha}\nerror: ${sha}`;
expect(extractBundlePrerequisiteCommits(message)).toEqual([sha]);
});
it("should be case-insensitive for the prerequisite header text", async () => {
const { extractBundlePrerequisiteCommits } = await import("./git_helpers.cjs");
const message = "ERROR: REPOSITORY LACKS THESE PREREQUISITE COMMITS:\nerror: 172f87a830f57a29470efe7646d141069434a893";
expect(extractBundlePrerequisiteCommits(message)).toEqual(["172f87a830f57a29470efe7646d141069434a893"]);
});
it("should ignore short (non-SHA) hex strings that are not 40 characters", async () => {
const { extractBundlePrerequisiteCommits } = await import("./git_helpers.cjs");
const message = "error: Repository lacks these prerequisite commits:\nerror: deadbeef";
// "deadbeef" is only 8 chars — not a full 40-char SHA so it should not be captured
// (The exact filtering depends on implementation; test that a real SHA is captured)
const fullSha = "172f87a830f57a29470efe7646d141069434a893";
const message2 = `error: Repository lacks these prerequisite commits:\nerror: ${fullSha} deadbeef`;
const result = extractBundlePrerequisiteCommits(message2);
expect(result).toContain(fullSha);
});
});
describe("linearizeRangeAsCommit", () => {
const ORIGINAL_HEAD = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
const NEW_HEAD = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
function makeExecApi({ originalHead = ORIGINAL_HEAD, newHead = NEW_HEAD, stagedFiles = "README.md\n" } = {}) {
let headCallCount = 0;
return {
getExecOutput: vi.fn().mockImplementation((_cmd, args) => {
if (args[0] === "rev-parse" && args[1] === "HEAD") {
headCallCount += 1;
// First call returns originalHead; subsequent calls return newHead
return Promise.resolve({ stdout: headCallCount === 1 ? `${originalHead}\n` : `${newHead}\n` });
}
if (args[0] === "diff" && args[1] === "--cached") {
return Promise.resolve({ stdout: stagedFiles });
}
return Promise.resolve({ stdout: "" });
}),
exec: vi.fn().mockResolvedValue(0),
};
}
it("should return the new HEAD SHA after successful linearization", async () => {
const { linearizeRangeAsCommit } = await import("./git_helpers.cjs");
const execApi = makeExecApi();
const result = await linearizeRangeAsCommit("origin/main", "Squash commit", execApi);
expect(result).toBe(NEW_HEAD);
expect(execApi.exec).toHaveBeenCalledWith("git", ["reset", "--soft", "origin/main"]);
expect(execApi.exec).toHaveBeenCalledWith("git", ["commit", "-m", "Squash commit"]);
});
it("should prepend commitFlags before -m in the git commit call", async () => {
const { linearizeRangeAsCommit } = await import("./git_helpers.cjs");
const execApi = makeExecApi();
await linearizeRangeAsCommit("origin/main", "Squash commit", execApi, {
commitFlags: ["--allow-empty", "--no-verify"],
});
expect(execApi.exec).toHaveBeenCalledWith("git", ["commit", "--allow-empty", "--no-verify", "-m", "Squash commit"]);
});
it("should pass gitOpts to every exec and getExecOutput call", async () => {
const { linearizeRangeAsCommit } = await import("./git_helpers.cjs");
const execApi = makeExecApi();
const gitOpts = { cwd: "/tmp/repo" };
await linearizeRangeAsCommit("origin/main", "Squash commit", execApi, { gitOpts });
// Every call should have received gitOpts as the trailing argument
for (const [, , opts] of execApi.exec.mock.calls) {
expect(opts).toEqual(gitOpts);
}
for (const [, , opts] of execApi.getExecOutput.mock.calls) {
expect(opts).toEqual(gitOpts);
}
});
it("should not append a third argument when gitOpts is not provided", async () => {
const { linearizeRangeAsCommit } = await import("./git_helpers.cjs");
const execApi = makeExecApi();
await linearizeRangeAsCommit("origin/main", "Squash commit", execApi);
// exec and getExecOutput should each be called with exactly 2 arguments
for (const callArgs of execApi.exec.mock.calls) {
expect(callArgs.length).toBe(2);
}
for (const callArgs of execApi.getExecOutput.mock.calls) {
expect(callArgs.length).toBe(2);
}
});
it("should throw immediately when HEAD cannot be resolved (empty stdout)", async () => {
const { linearizeRangeAsCommit } = await import("./git_helpers.cjs");
const execApi = {
getExecOutput: vi.fn().mockResolvedValue({ stdout: " \n" }),
exec: vi.fn(),
};
await expect(linearizeRangeAsCommit("origin/main", "msg", execApi)).rejects.toThrow("Could not resolve current HEAD before linearizing range");
expect(execApi.exec).not.toHaveBeenCalled();
});
it("should roll back to originalHead and throw when no staged changes exist after soft reset", async () => {
const { linearizeRangeAsCommit } = await import("./git_helpers.cjs");
const warning = mockCoreWarning();
const execApi = makeExecApi({ stagedFiles: "" });
await expect(linearizeRangeAsCommit("origin/main", "msg", execApi)).rejects.toThrow(/Failed to linearize origin\/main\.\.HEAD/);
// Should have rolled back to the original HEAD
expect(execApi.exec).toHaveBeenCalledWith("git", ["reset", "--hard", ORIGINAL_HEAD]);
// Should have emitted a warning about restoring the original HEAD
expect(warning).toHaveBeenCalledWith(expect.stringContaining(`restored original HEAD ${ORIGINAL_HEAD}`));
});
it("should roll back to originalHead and throw when soft reset fails", async () => {
const { linearizeRangeAsCommit } = await import("./git_helpers.cjs");
const warning = mockCoreWarning();
const execApi = {
getExecOutput: vi.fn().mockResolvedValue({ stdout: `${ORIGINAL_HEAD}\n` }),
exec: vi.fn().mockImplementation((_cmd, args) => {
// Soft reset fails; hard reset (rollback) succeeds
if (args[0] === "reset" && args[1] === "--soft") return Promise.reject(new Error("reset failed"));
return Promise.resolve(0);
}),
};
await expect(linearizeRangeAsCommit("origin/main", "msg", execApi)).rejects.toThrow(/Failed to linearize origin\/main\.\.HEAD.*reset failed/s);
// Should have attempted rollback (reset --hard)
expect(execApi.exec).toHaveBeenCalledWith("git", ["reset", "--hard", ORIGINAL_HEAD]);
expect(warning).toHaveBeenCalledWith(expect.stringContaining(`restored original HEAD ${ORIGINAL_HEAD}`));
});
it("should roll back to originalHead and throw when git commit fails", async () => {
const { linearizeRangeAsCommit } = await import("./git_helpers.cjs");
const warning = mockCoreWarning();
const execApi = {
getExecOutput: vi.fn().mockImplementation((_cmd, args) => {
if (args[0] === "rev-parse") return Promise.resolve({ stdout: `${ORIGINAL_HEAD}\n` });
if (args[0] === "diff") return Promise.resolve({ stdout: "file.txt\n" });
return Promise.resolve({ stdout: "" });
}),
exec: vi.fn().mockImplementation((_cmd, args) => {
if (args[0] === "commit") return Promise.reject(new Error("commit failed"));
return Promise.resolve(0);
}),
};
await expect(linearizeRangeAsCommit("origin/main", "msg", execApi)).rejects.toThrow(/Failed to linearize origin\/main\.\.HEAD.*commit failed/s);
expect(execApi.exec).toHaveBeenCalledWith("git", ["reset", "--hard", ORIGINAL_HEAD]);
expect(warning).toHaveBeenCalledWith(expect.stringContaining(`restored original HEAD ${ORIGINAL_HEAD}`));
});
it("should emit a rollback-failure warning when reset --hard also fails", async () => {
const { linearizeRangeAsCommit } = await import("./git_helpers.cjs");
const warning = mockCoreWarning();
const execApi = {
getExecOutput: vi.fn().mockImplementation((_cmd, args) => {
if (args[0] === "rev-parse") return Promise.resolve({ stdout: `${ORIGINAL_HEAD}\n` });
if (args[0] === "diff") return Promise.resolve({ stdout: "" });
return Promise.resolve({ stdout: "" });
}),
exec: vi.fn().mockRejectedValue(new Error("disk failure")),
};
await expect(linearizeRangeAsCommit("origin/main", "msg", execApi)).rejects.toThrow(/Failed to linearize/);
// Should have warned about the rollback failure
expect(warning).toHaveBeenCalledWith(expect.stringContaining("rollback also failed"));
});
it("should carry the original error as the cause on failure", async () => {
const { linearizeRangeAsCommit } = await import("./git_helpers.cjs");
mockCoreWarning();
const cause = new Error("inner error");
const execApi = {
getExecOutput: vi.fn().mockImplementation((_cmd, args) => {
if (args[0] === "rev-parse") return Promise.resolve({ stdout: `${ORIGINAL_HEAD}\n` });
if (args[0] === "diff") return Promise.resolve({ stdout: "" });
return Promise.resolve({ stdout: "" });
}),
exec: vi.fn().mockRejectedValue(cause),
};
const err = await linearizeRangeAsCommit("origin/main", "msg", execApi).catch(e => e);
expect(err.cause).toBe(cause);
});
});
});