-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathgit.test.ts
More file actions
1328 lines (1137 loc) · 48.9 KB
/
Copy pathgit.test.ts
File metadata and controls
1328 lines (1137 loc) · 48.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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { execSync } from "node:child_process";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { ConfigurationError } from "./provider";
import {
assertGitAvailable,
buildPathspecArgs,
ensureCommitAvailable,
extractBranchName,
extractBranchNameFromMergeMessage,
getCommitContext,
getCommitContextsBetweenShas,
countCommitsInRange,
getCurrentGitInfo,
getCommitParents,
getRemoteUrl,
isAncestor,
normalizePathspec,
resolveFirstSyncBoundary,
} from "./git";
describe("normalizePathspec", () => {
it("should strip leading ./", () => {
expect(normalizePathspec("./android/**")).toBe("android/**");
});
it("should strip leading /", () => {
expect(normalizePathspec("/src/**")).toBe("src/**");
});
it("should strip multiple leading slashes", () => {
expect(normalizePathspec("///src/**")).toBe("src/**");
expect(normalizePathspec("/./src/**")).toBe("src/**");
});
it("should trim whitespace", () => {
expect(normalizePathspec(" android/** ")).toBe("android/**");
});
it("should preserve negation while normalizing the path", () => {
expect(normalizePathspec(" !./mobile/** ")).toBe("!mobile/**");
expect(normalizePathspec("!/desktop/**")).toBe("!desktop/**");
});
it("should trim whitespace between the negation and the path", () => {
expect(normalizePathspec("! mobile/**")).toBe("!mobile/**");
expect(normalizePathspec("! ./desktop/**")).toBe("!desktop/**");
});
it("should handle empty strings", () => {
expect(normalizePathspec("")).toBe("");
});
});
describe("buildPathspecArgs", () => {
it("should return an empty array for null", () => {
expect(buildPathspecArgs(null)).toEqual([]);
});
it("should return an empty array for an empty array", () => {
expect(buildPathspecArgs([])).toEqual([]);
});
it("should build pathspec for single pattern", () => {
expect(buildPathspecArgs(["android/**"])).toEqual(["--", ":(top,glob)android/**"]);
});
it("should build pathspec for multiple patterns", () => {
expect(buildPathspecArgs(["android/**", "shared/**"])).toEqual([
"--",
":(top,glob)android/**",
":(top,glob)shared/**",
]);
});
it("should filter out empty patterns", () => {
expect(buildPathspecArgs(["android/**", "", " "])).toEqual(["--", ":(top,glob)android/**"]);
});
it("should normalize patterns", () => {
expect(buildPathspecArgs(["./android/**", " ios/** "])).toEqual([
"--",
":(top,glob)android/**",
":(top,glob)ios/**",
]);
});
it("should build exclude pathspecs for negated patterns", () => {
expect(buildPathspecArgs(["**", "!./mobile/**", " !/desktop/** "])).toEqual([
"--",
":(top,glob)**",
":(top,glob,exclude)mobile/**",
":(top,glob,exclude)desktop/**",
]);
});
it("should reject a negation without a path", () => {
expect(() => buildPathspecArgs(["!"])).toThrow(ConfigurationError);
expect(() => buildPathspecArgs(["! "])).toThrow("a negation must include a path");
expect(() => buildPathspecArgs(["src/**", "!"])).toThrow(ConfigurationError);
});
});
describe("extractBranchName", () => {
it("should return null for empty or undefined input", () => {
expect(extractBranchName(undefined)).toBeNull();
expect(extractBranchName("")).toBeNull();
expect(extractBranchName(" ")).toBeNull();
});
it("should extract a simple branch name", () => {
expect(extractBranchName("feature/ENG-123-add-button")).toBe("feature/ENG-123-add-button");
});
it("should prefer feature branches over common branches", () => {
expect(extractBranchName("main, feature/ENG-123-fix")).toBe("feature/ENG-123-fix");
expect(extractBranchName("feature/ENG-123-fix, main")).toBe("feature/ENG-123-fix");
expect(extractBranchName("master, develop, feature/PLAT-456")).toBe("feature/PLAT-456");
});
it("should handle all common branch names (case-insensitive)", () => {
const commonBranches = ["main", "master", "develop", "dev", "staging", "production", "prod"];
for (const common of commonBranches) {
expect(extractBranchName(`${common}, feature/ABC-1`)).toBe("feature/ABC-1");
expect(extractBranchName(`${common.toUpperCase()}, feature/ABC-1`)).toBe("feature/ABC-1");
}
});
it("should fall back to common branch if no feature branches exist", () => {
expect(extractBranchName("main")).toBe("main");
expect(extractBranchName("main, master")).toBe("master"); // longer name preferred
});
it("should pick the longest branch name when multiple candidates exist", () => {
expect(extractBranchName("feat/X, feature/ENG-123-longer-name")).toBe("feature/ENG-123-longer-name");
});
it("should handle HEAD -> prefix", () => {
expect(extractBranchName("HEAD -> feature/ENG-123")).toBe("feature/ENG-123");
expect(extractBranchName("HEAD -> main, feature/ENG-123")).toBe("feature/ENG-123");
});
it("should filter out tags", () => {
expect(extractBranchName("tag: v1.0.0, feature/ENG-123")).toBe("feature/ENG-123");
expect(extractBranchName("TAG: v1.0.0, main")).toBe("main");
});
it("should filter out origin/HEAD", () => {
expect(extractBranchName("origin/HEAD, feature/ENG-123")).toBe("feature/ENG-123");
});
it("should normalize remote branch prefixes", () => {
expect(extractBranchName("remotes/origin/feature/ENG-123")).toBe("feature/ENG-123");
expect(extractBranchName("remotes/upstream/feature/ABC-1, remotes/origin/main")).toBe("feature/ABC-1");
});
it("should return null when only tags are present", () => {
expect(extractBranchName("tag: v1.0.0")).toBeNull();
expect(extractBranchName("tag: v1.0.0, tag: latest")).toBeNull();
});
});
describe("getRemoteUrl", () => {
it("should return the origin remote URL", () => {
expect(getRemoteUrl()).toMatch(/github\.com[:/]linear\/linear-release/);
});
});
describe("extractBranchNameFromMergeMessage", () => {
describe("GitHub format", () => {
it("should extract branch name from standard GitHub merge message", () => {
const message = "Merge pull request #431 from RideShareAppOrg/romain/bac-26";
expect(extractBranchNameFromMergeMessage(message)).toBe("romain/bac-26");
});
it("should extract branch name and ignore trailing text", () => {
const message = "Merge pull request #42 from owner/feature/ENG-123-fix-bug Some description";
expect(extractBranchNameFromMergeMessage(message)).toBe("feature/ENG-123-fix-bug");
});
it("should handle case insensitivity", () => {
const message = "MERGE PULL REQUEST #100 from owner/branch-name";
expect(extractBranchNameFromMergeMessage(message)).toBe("branch-name");
});
});
describe("GitLab format", () => {
it("should extract branch name from GitLab merge message with target", () => {
const message = "Merge branch 'ax/ENG-123-add-button' into 'develop'";
expect(extractBranchNameFromMergeMessage(message)).toBe("ax/ENG-123-add-button");
});
it("should extract branch name from GitLab merge message without target", () => {
const message = "Merge branch 'feature/ENG-456-fix-auth'";
expect(extractBranchNameFromMergeMessage(message)).toBe("feature/ENG-456-fix-auth");
});
it("should handle case insensitivity for GitLab format", () => {
const message = "MERGE BRANCH 'feature/LIN-100'";
expect(extractBranchNameFromMergeMessage(message)).toBe("feature/LIN-100");
});
});
describe("Bitbucket format", () => {
it("should extract branch name from standard Bitbucket merge message", () => {
const message = "Merged in romain/LIN-123-fix-auth (pull request #42)";
expect(extractBranchNameFromMergeMessage(message)).toBe("romain/LIN-123-fix-auth");
});
it("should extract branch name and ignore trailing PR title", () => {
const message = "Merged in feature/ENG-123-add-button (pull request #7) Improve button spacing";
expect(extractBranchNameFromMergeMessage(message)).toBe("feature/ENG-123-add-button");
});
});
describe("edge cases", () => {
it("should return null for non-merge messages", () => {
expect(extractBranchNameFromMergeMessage("Some regular commit")).toBeNull();
expect(extractBranchNameFromMergeMessage("Fix bug (#123)")).toBeNull();
});
it("should return null for null or undefined input", () => {
expect(extractBranchNameFromMergeMessage(null)).toBeNull();
expect(extractBranchNameFromMergeMessage(undefined)).toBeNull();
});
});
});
type TempRepo = {
cwd: string;
commits: {
first: string;
second: string;
third: string;
};
};
type ShallowCloneRepo = TempRepo & {
origin: string;
source: string;
};
type TempRepoWithMerge = {
cwd: string;
commits: {
base: string;
featureBranch: string;
mergeCommit: string;
};
};
type TempRepoWithMultipleMerges = {
cwd: string;
commits: {
base: string;
merge100: string; // Merge of feature/LIN-100 (touches frontend/)
merge200: string; // Merge of feature/LIN-200 (touches backend/)
merge300: string; // Merge of feature/LIN-300 (touches infra/ — outside includePaths)
headMerge: string; // Merge of release branch into main
};
};
type TempRepoReleaseBranch = {
cwd: string;
commits: {
base: string;
headMerge: string; // The rel-branch → main merge (HEAD)
};
};
type TempRepoStaleMerge = {
cwd: string;
commits: {
base: string;
staleMerge: string; // Merge of feat/ABC-1-stale — edited app-a/ only, merged after app-b/ landed
subjectMerge: string; // Merge of feat/XYZ-2-impl — edited app-b/, key only on the merge subject (HEAD)
};
};
type TempRepoStaleBranchDecoration = {
cwd: string;
commits: {
base: string;
downMerge: string; // Interior merge commit a stale branch was cut from; subject is not a parseable merge message
tip: string;
};
};
type TempRepoFastForwardFeature = {
cwd: string;
commits: {
base: string;
feature: string; // Fast-forwarded regular commit whose issue key lives only in the branch name
tip: string;
};
};
function runGit(command: string, cwd: string): string {
return execSync(`git ${command}`, {
cwd,
stdio: ["ignore", "pipe", "ignore"],
encoding: "utf8",
}).trim();
}
function buildFastImportMessage(index: number, messageBytes: number): string {
const header = `Merge pull request #${40000 + index} from owner/feature/PLAT-${10000 + index}-sync-pipeline\n\nPLAT-${10000 + index}: update service ${index}\n\n`;
const filler = "* chore(deps): bump internal packages and regenerate lockfile entries for the release train\n";
return (header + filler.repeat(Math.ceil((messageBytes - header.length) / filler.length))).slice(0, messageBytes);
}
function createFastImportRepo(
commitCount: number,
messageBytes: number,
): {
cwd: string;
anchor: string;
commits: string[];
head: string;
} {
const cwd = mkdtempSync(join(tmpdir(), "linear-release-fast-import-"));
runGit("init", cwd);
const records: string[] = [];
const appendCommit = (mark: number, message: string, from?: number) => {
records.push(
`commit refs/heads/main\nmark :${mark}\ncommitter Repro Bot <repro@example.com> ${1753000000 + mark * 60} +0000\ndata ${Buffer.byteLength(message)}\n${message}\n${from ? `from :${from}\n` : ""}\n`,
);
};
appendCommit(1, "chore: release anchor v20260506\n");
for (let index = 1; index <= commitCount; index++) {
appendCommit(index + 1, buildFastImportMessage(index, messageBytes), index);
}
execSync("git fast-import", {
cwd,
input: records.join(""),
stdio: ["pipe", "ignore", "pipe"],
});
const [anchor, ...commits] = runGit("rev-list --reverse main", cwd).split("\n");
return { cwd, anchor: anchor!, commits, head: commits[commits.length - 1]! };
}
/**
* Initializes a tmpdir repo, configures user, creates the listed directories,
* lands a seed commit, and renames the branch to `main`. Returns the cwd and
* base SHA.
*/
function initTempRepo(opts: { prefix: string; dirs: string[]; seedFile: { path: string; content: string } }): {
cwd: string;
base: string;
} {
const cwd = mkdtempSync(join(tmpdir(), opts.prefix));
runGit("init", cwd);
runGit('config user.email "test@example.com"', cwd);
runGit('config user.name "Test User"', cwd);
for (const dir of opts.dirs) {
mkdirSync(join(cwd, dir), { recursive: true });
}
writeFileSync(join(cwd, opts.seedFile.path), opts.seedFile.content);
runGit("add .", cwd);
runGit('commit -m "Initial"', cwd);
runGit("branch -M main", cwd);
return { cwd, base: runGit("rev-parse HEAD", cwd) };
}
/**
* Cuts `branch` off `baseBranch`, lands one file change, merges back via
* `--no-ff` with a GitHub-style PR-merge message, then deletes `branch` to
* mirror a CI checkout (merged feature branches gone). Returns the merge SHA.
*/
function mergeFeatureBranch(opts: {
cwd: string;
baseBranch: string;
branch: string;
file: string;
prNumber: number;
}): string {
const { cwd, baseBranch, branch, file, prNumber } = opts;
runGit(`checkout -b ${branch} ${baseBranch}`, cwd);
writeFileSync(join(cwd, file), "x");
runGit("add .", cwd);
runGit(`commit -m "feature work on ${branch}"`, cwd);
runGit(`checkout ${baseBranch}`, cwd);
runGit(`merge --no-ff ${branch} -m "Merge pull request #${prNumber} from owner/${branch}"`, cwd);
const sha = runGit("rev-parse HEAD", cwd);
runGit(`branch -D ${branch}`, cwd);
return sha;
}
/**
* Build a deterministic git repo for integration tests.
*
* Commit history (oldest -> newest):
* 1) src/alpha.txt
* 2) .github/workflows/ci.yml
* 3) src/beta.txt
*
* This lets tests assert includePaths behavior without depending on
* the state of the working repository.
*/
function createTempRepo(): TempRepo {
const cwd = mkdtempSync(join(tmpdir(), "linear-release-"));
runGit("init", cwd);
runGit('config user.email "test@example.com"', cwd);
runGit('config user.name "Test User"', cwd);
mkdirSync(join(cwd, "src"), { recursive: true });
writeFileSync(join(cwd, "src", "alpha.txt"), "alpha");
runGit("add .", cwd);
runGit('commit -m "feat: add src file with extra spaces"', cwd);
const first = runGit("rev-parse HEAD", cwd);
mkdirSync(join(cwd, ".github", "workflows"), { recursive: true });
writeFileSync(join(cwd, ".github", "workflows", "ci.yml"), "name: ci");
runGit("add .", cwd);
runGit('commit -m "chore: add workflow"', cwd);
const second = runGit("rev-parse HEAD", cwd);
writeFileSync(join(cwd, "src", "beta.txt"), "beta");
runGit("add .", cwd);
runGit('commit -m "feat: add beta"', cwd);
const third = runGit("rev-parse HEAD", cwd);
return { cwd, commits: { first, second, third } };
}
function createShallowCloneRepo(): ShallowCloneRepo {
const source = createTempRepo();
const origin = mkdtempSync(join(tmpdir(), "linear-release-origin-"));
runGit(`clone --bare ${source.cwd} ${origin}`, tmpdir());
const cwd = mkdtempSync(join(tmpdir(), "linear-release-shallow-"));
runGit(`clone --depth 1 file://${origin} ${cwd}`, tmpdir());
return { cwd, origin, source: source.cwd, commits: source.commits };
}
/**
* Build a deterministic git repo with a merge commit for integration tests.
*
* Structure:
* 1) base commit on main (modifies root file)
* 2) feature branch created, commits to src/feature.txt
* 3) merge commit combining main and feature branch
*
* This tests that merge commits are included even when path filtering would exclude them.
*/
function createTempRepoWithMerge(): TempRepoWithMerge {
const cwd = mkdtempSync(join(tmpdir(), "linear-release-merge-test-"));
runGit("init", cwd);
runGit('config user.email "test@example.com"', cwd);
runGit('config user.name "Test User"', cwd);
// Create initial commit on main
writeFileSync(join(cwd, "README.md"), "initial");
runGit("add .", cwd);
runGit('commit -m "Initial commit"', cwd);
// Ensure branch is named "main" regardless of git's default branch config
runGit("branch -M main", cwd);
const base = runGit("rev-parse HEAD", cwd);
// Create feature branch with commit that modifies src/
runGit("checkout -b feature/ENG-123-add-feature", cwd);
mkdirSync(join(cwd, "src"), { recursive: true });
writeFileSync(join(cwd, "src", "feature.txt"), "feature code");
runGit("add .", cwd);
runGit('commit -m "Add feature code"', cwd);
const featureBranch = runGit("rev-parse HEAD", cwd);
// Merge feature branch into main (creates a merge commit)
runGit("checkout main", cwd);
runGit(
'merge --no-ff feature/ENG-123-add-feature -m "Merge pull request #42 from owner/feature/ENG-123-add-feature"',
cwd,
);
const mergeCommit = runGit("rev-parse HEAD", cwd);
return { cwd, commits: { base, featureBranch, mergeCommit } };
}
/**
* Three feature branches merged into main, then a release branch with one
* commit merged back as HEAD. `merge300` touches `infra/` only.
*/
function createTempRepoWithMultipleMerges(): TempRepoWithMultipleMerges {
const { cwd, base } = initTempRepo({
prefix: "linear-release-multi-merge-",
dirs: ["frontend", "backend", "infra"],
seedFile: { path: "frontend/seed.txt", content: "seed" },
});
const merge100 = mergeFeatureBranch({
cwd,
baseBranch: "main",
branch: "feature/LIN-100-add-foo",
file: "frontend/foo.txt",
prNumber: 100,
});
const merge200 = mergeFeatureBranch({
cwd,
baseBranch: "main",
branch: "feature/LIN-200-fix-bar",
file: "backend/bar.txt",
prNumber: 200,
});
const merge300 = mergeFeatureBranch({
cwd,
baseBranch: "main",
branch: "feature/LIN-300-infra",
file: "infra/three.txt",
prNumber: 300,
});
// rel branch needs at least one of its own commits, otherwise --no-ff is a
// no-op when the branches are identical.
runGit("checkout -b rel/2026-05-06 main", cwd);
writeFileSync(join(cwd, "frontend", "release-notes.txt"), "notes");
runGit("add .", cwd);
runGit('commit -m "release notes"', cwd);
runGit("checkout main", cwd);
runGit('merge --no-ff rel/2026-05-06 -m "Merge pull request #324 from owner/rel/2026-05-06"', cwd);
const headMerge = runGit("rev-parse HEAD", cwd);
runGit("branch -D rel/2026-05-06", cwd);
return { cwd, commits: { base, merge100, merge200, merge300, headMerge } };
}
/**
* Release-branch workflow: features merged INTO `rel/2026-05-06`, then rel
* merged into main as HEAD. `feature/LIN-300-mobile` touches `mobile-android/`
* only.
*/
function createTempRepoReleaseBranch(): TempRepoReleaseBranch {
const { cwd, base } = initTempRepo({
prefix: "linear-release-rel-branch-",
dirs: ["frontend-nuxt3", "backend", "mobile-android"],
seedFile: { path: "frontend-nuxt3/seed.ts", content: "seed" },
});
runGit("checkout -b rel/2026-05-06 main", cwd);
mergeFeatureBranch({
cwd,
baseBranch: "rel/2026-05-06",
branch: "feature/LIN-100-foo",
file: "frontend-nuxt3/foo.ts",
prNumber: 100,
});
mergeFeatureBranch({
cwd,
baseBranch: "rel/2026-05-06",
branch: "feature/LIN-200-bar",
file: "backend/bar.ts",
prNumber: 200,
});
mergeFeatureBranch({
cwd,
baseBranch: "rel/2026-05-06",
branch: "feature/LIN-300-mobile",
file: "mobile-android/m.kt",
prNumber: 300,
});
runGit("checkout main", cwd);
runGit('merge --no-ff rel/2026-05-06 -m "Merge pull request #324 from owner/rel/2026-05-06"', cwd);
const headMerge = runGit("rev-parse HEAD", cwd);
runGit("branch -D rel/2026-05-06", cwd);
return { cwd, commits: { base, headMerge } };
}
/**
* Two PR merges into main, each carrying its issue key only in the branch name
* (no content commit carries a key):
* - feat/ABC-1-stale is rooted at `base`, edits app-a/ only, and is merged
* AFTER app-b/ appears on main — a stale branch never rebased. The merge
* differs from its first parent for app-b/ only because app-b/ advanced on
* main while the branch was open, so `--full-history` keeps it under an app-b
* pathspec even though the branch delivered nothing to app-b/.
* - feat/XYZ-2-impl is rooted at the stale merge and genuinely edits app-b/.
* Its key lives only on the merge subject, so dropping the merge would lose
* the key entirely even though the merge did deliver app-b/ changes.
*/
function createTempRepoStaleMerge(): TempRepoStaleMerge {
const { cwd, base } = initTempRepo({
prefix: "linear-release-stale-merge-",
dirs: ["app-a", "app-b"],
seedFile: { path: "app-a/file.txt", content: "a0" },
});
runGit(`checkout -b feat/ABC-1-stale ${base}`, cwd);
writeFileSync(join(cwd, "app-a", "file.txt"), "a1");
runGit("add .", cwd);
runGit('commit -m "rework app-a internals"', cwd);
runGit("checkout main", cwd);
writeFileSync(join(cwd, "app-b", "file.txt"), "b0");
runGit("add .", cwd);
runGit('commit -m "add app-b on main"', cwd);
runGit('merge --no-ff feat/ABC-1-stale -m "Merge pull request #1 from owner/feat/ABC-1-stale"', cwd);
const staleMerge = runGit("rev-parse HEAD", cwd);
runGit("branch -D feat/ABC-1-stale", cwd);
runGit(`checkout -b feat/XYZ-2-impl ${staleMerge}`, cwd);
writeFileSync(join(cwd, "app-b", "file.txt"), "b1");
runGit("add .", cwd);
runGit('commit -m "implement the thing"', cwd);
runGit("checkout main", cwd);
runGit('merge --no-ff feat/XYZ-2-impl -m "Merge pull request #2 from owner/feat/XYZ-2-impl"', cwd);
const subjectMerge = runGit("rev-parse HEAD", cwd);
runGit("branch -D feat/XYZ-2-impl", cwd);
return { cwd, commits: { base, staleMerge, subjectMerge } };
}
/**
* A stale branch cut from an interior down-merge commit and never committed onto,
* so its ref only decorates that merge. The merge subject is not a parseable merge
* message, leaving the decoration as the sole — wrong — branch-name source.
*/
function createTempRepoStaleBranchDecoration(): TempRepoStaleBranchDecoration {
const { cwd, base } = initTempRepo({
prefix: "linear-release-stale-decoration-",
dirs: ["src"],
seedFile: { path: "src/a.txt", content: "a" },
});
runGit(`checkout -b trunk ${base}`, cwd);
writeFileSync(join(cwd, "src", "b.txt"), "b");
runGit("add .", cwd);
runGit('commit -m "trunk work"', cwd);
runGit("checkout main", cwd);
writeFileSync(join(cwd, "src", "c.txt"), "c");
runGit("add .", cwd);
runGit('commit -m "release work"', cwd);
runGit('merge --no-ff trunk -m "Down merge trunk into release (#501)"', cwd);
const downMerge = runGit("rev-parse HEAD", cwd);
runGit(`branch ZED-7 ${downMerge}`, cwd);
writeFileSync(join(cwd, "src", "d.txt"), "d");
runGit("add .", cwd);
runGit('commit -m "[ARC-3]: fix worker lookup for restricted roles (#502)"', cwd);
const tip = runGit("rev-parse HEAD", cwd);
return { cwd, commits: { base, downMerge, tip } };
}
/**
* A GitLab fast-forward merge: the feature branch's commit lands verbatim on main
* with the issue key only in the branch name, and a later commit leaves it
* interior. The kept branch ref is the sole source of the key — it must survive.
*/
function createTempRepoFastForwardFeature(): TempRepoFastForwardFeature {
const { cwd, base } = initTempRepo({
prefix: "linear-release-ff-feature-",
dirs: ["src"],
seedFile: { path: "src/a.txt", content: "a" },
});
runGit(`checkout -b user/REL-9-feature ${base}`, cwd);
writeFileSync(join(cwd, "src", "b.txt"), "b");
runGit("add .", cwd);
runGit('commit -m "Add feature"', cwd);
const feature = runGit("rev-parse HEAD", cwd);
runGit("checkout main", cwd);
runGit("merge --ff-only user/REL-9-feature", cwd);
writeFileSync(join(cwd, "src", "c.txt"), "c");
runGit("add .", cwd);
runGit('commit -m "chore: follow-up"', cwd);
const tip = runGit("rev-parse HEAD", cwd);
return { cwd, commits: { base, feature, tip } };
}
describe("getCommitContextsBetweenShas", () => {
let repo: TempRepo;
beforeAll(() => {
repo = createTempRepo();
});
it("should auto-fetch deeper history for shallow clones", async () => {
const shallowRepo = createShallowCloneRepo();
try {
expect(runGit("rev-parse --is-shallow-repository", shallowRepo.cwd)).toBe("true");
ensureCommitAvailable(shallowRepo.commits.first, shallowRepo.cwd);
const result = await getCommitContextsBetweenShas(shallowRepo.commits.first, shallowRepo.commits.third, {
cwd: shallowRepo.cwd,
});
expect(result.map((commit) => commit.sha)).toEqual([shallowRepo.commits.third, shallowRepo.commits.second]);
expect(runGit("rev-parse --is-shallow-repository", shallowRepo.cwd)).toBe("false");
} finally {
rmSync(shallowRepo.cwd, { recursive: true, force: true });
rmSync(shallowRepo.origin, { recursive: true, force: true });
rmSync(shallowRepo.source, { recursive: true, force: true });
}
});
afterAll(() => {
rmSync(repo.cwd, { recursive: true, force: true });
});
it("should return empty array for invalid SHA patterns", async () => {
expect(
await getCommitContextsBetweenShas("invalid", repo.commits.third, {
cwd: repo.cwd,
}),
).toEqual([]);
expect(
await getCommitContextsBetweenShas(repo.commits.first, "invalid", {
cwd: repo.cwd,
}),
).toEqual([]);
expect(
await getCommitContextsBetweenShas("not-a-sha", "also-invalid", {
cwd: repo.cwd,
}),
).toEqual([]);
});
it("should return commits between two valid SHAs", async () => {
const result = await getCommitContextsBetweenShas(repo.commits.first, repo.commits.third, {
cwd: repo.cwd,
});
expect(result).toHaveLength(2);
expect(result[0]?.sha).toBe(repo.commits.third);
expect(result[1]?.sha).toBe(repo.commits.second);
});
it("should return single commit when fromSha equals toSha", async () => {
const result = await getCommitContextsBetweenShas(repo.commits.first, repo.commits.first, {
cwd: repo.cwd,
});
expect(result).toHaveLength(1);
expect(result[0]?.sha).toBe(repo.commits.first);
});
it("should collapse horizontal whitespace but preserve newlines", async () => {
const result = await getCommitContextsBetweenShas(repo.commits.first, repo.commits.first, {
cwd: repo.cwd,
});
expect(result).toHaveLength(1);
// Multiple spaces in the subject should be collapsed
expect(result[0]?.message).toBe("feat: add src file with extra spaces");
});
it("should preserve newlines so extractors can distinguish title from body", async () => {
// Standalone tempdir so the multiline body is independent of the shared fixture.
const cwd = mkdtempSync(join(tmpdir(), "linear-release-multiline-"));
try {
runGit("init", cwd);
runGit('config user.email "test@example.com"', cwd);
runGit('config user.name "Test User"', cwd);
writeFileSync(join(cwd, "file.txt"), "x");
runGit("add .", cwd);
runGit('commit -m "Add feature (#100)" -m "Closes LIN-200" -m "Co-authored-by: Other <other@example.com>"', cwd);
const sha = runGit("rev-parse HEAD", cwd);
const result = await getCommitContextsBetweenShas(sha, sha, { cwd });
expect(result).toHaveLength(1);
expect(result[0]?.message).toBe(
"Add feature (#100)\n\nCloses LIN-200\n\nCo-authored-by: Other <other@example.com>",
);
// First line is the actual title (not the entire flattened body)
expect(result[0]!.message!.split("\n")[0]).toBe("Add feature (#100)");
} finally {
rmSync(cwd, { recursive: true, force: true });
}
});
it("should return empty array when no commits in range", async () => {
// third..first is empty because first is an ancestor of third
const result = await getCommitContextsBetweenShas(repo.commits.third, repo.commits.first, {
cwd: repo.cwd,
});
expect(result).toEqual([]);
});
it("should filter commits by includePaths patterns", async () => {
const withSrcFilter = await getCommitContextsBetweenShas(repo.commits.first, repo.commits.third, {
includePaths: ["src/**"],
cwd: repo.cwd,
});
expect(withSrcFilter).toHaveLength(1);
expect(withSrcFilter[0]?.sha).toBe(repo.commits.third);
const withGithubFilter = await getCommitContextsBetweenShas(repo.commits.first, repo.commits.third, {
includePaths: [".github/**"],
cwd: repo.cwd,
});
expect(withGithubFilter).toHaveLength(1);
expect(withGithubFilter[0]?.sha).toBe(repo.commits.second);
});
it("should exclude commits matching negated path patterns", async () => {
const result = await getCommitContextsBetweenShas(repo.commits.first, repo.commits.third, {
includePaths: ["**", "!.github/**"],
cwd: repo.cwd,
});
expect(result.map((commit) => commit.sha)).toEqual([repo.commits.third]);
});
it("should support exclusion-only path patterns", async () => {
const result = await getCommitContextsBetweenShas(repo.commits.first, repo.commits.third, {
includePaths: ["!.github/**"],
cwd: repo.cwd,
});
expect(result.map((commit) => commit.sha)).toEqual([repo.commits.third]);
});
it("should reject a negation without a path instead of scanning unfiltered", async () => {
await expect(
getCommitContextsBetweenShas(repo.commits.first, repo.commits.third, {
includePaths: ["!"],
cwd: repo.cwd,
}),
).rejects.toThrow(ConfigurationError);
});
it("should resolve paths relative to repo root even when process.cwd() is a subdirectory", async () => {
// Simulates running the CLI from a subdirectory (e.g., mobile-ios/ci_scripts)
// while using paths relative to the repo root (e.g., src/**)
const originalCwd = process.cwd();
try {
process.chdir(join(repo.cwd, "src"));
// The `:(top,...)` magic prefix in buildPathspecArgs anchors the glob
// at the repo root regardless of cwd; without it git would resolve
// "src/**" against the subdirectory (i.e., src/src/**).
const result = await getCommitContextsBetweenShas(
repo.commits.first,
repo.commits.third,
{ includePaths: ["src/**"] }, // no cwd passed — uses process.cwd()
);
expect(result).toHaveLength(1);
expect(result[0]?.sha).toBe(repo.commits.third);
} finally {
process.chdir(originalCwd);
}
});
it("should not resolve paths relative to cwd", async () => {
// Companion test to the above: verifies that paths are resolved from repo root, not cwd.
// From within src/, looking for "*.txt" would match src/alpha.txt and src/beta.txt
// if paths were relative to cwd. With :(top), it looks for <repo>/*.txt which doesn't exist.
const originalCwd = process.cwd();
try {
process.chdir(join(repo.cwd, "src"));
const result = await getCommitContextsBetweenShas(repo.commits.first, repo.commits.third, {
includePaths: ["*.txt"],
});
expect(result).toHaveLength(0);
} finally {
process.chdir(originalCwd);
}
});
it("should parse large commit messages incrementally with intact fields", async () => {
const fastImportRepo = createFastImportRepo(3, 1024 * 1024);
try {
const result = await getCommitContextsBetweenShas(fastImportRepo.anchor, fastImportRepo.head, {
cwd: fastImportRepo.cwd,
});
expect(result).toHaveLength(3);
for (let resultIndex = 0; resultIndex < result.length; resultIndex++) {
const commitIndex = 3 - resultIndex;
const expectedSha = fastImportRepo.commits[commitIndex - 1]!;
const expectedParent = commitIndex === 1 ? fastImportRepo.anchor : fastImportRepo.commits[commitIndex - 2]!;
expect(result[resultIndex]).toEqual({
sha: expectedSha,
branchName: `feature/PLAT-${10000 + commitIndex}-sync-pipeline`,
message: buildFastImportMessage(commitIndex, 1024 * 1024).trim(),
parents: [expectedParent],
});
}
} finally {
rmSync(fastImportRepo.cwd, { recursive: true, force: true });
}
});
it("should stream git log output larger than 256 MiB", async () => {
const fastImportRepo = createFastImportRepo(270, 1024 * 1024);
try {
const result = await getCommitContextsBetweenShas(fastImportRepo.anchor, fastImportRepo.head, {
cwd: fastImportRepo.cwd,
});
expect(result).toHaveLength(270);
expect(result[0]?.sha).toBe(fastImportRepo.head);
expect(result[result.length - 1]?.sha).toBe(fastImportRepo.commits[0]);
} finally {
rmSync(fastImportRepo.cwd, { recursive: true, force: true });
}
}, 120_000);
});
describe("getCurrentGitInfo", () => {
it("should preserve branch and commit for a large HEAD message", () => {
const repo = initTempRepo({
prefix: "linear-release-large-head-",
dirs: ["src"],
seedFile: { path: "src/file.txt", content: "content" },
});
try {
execSync("git commit --amend -F -", {
cwd: repo.cwd,
input: "Large HEAD\n\n" + "x".repeat(2 * 1024 * 1024),
stdio: ["pipe", "ignore", "pipe"],
});
const info = getCurrentGitInfo(repo.cwd);
expect(info.branch).not.toBeNull();
expect(info.commit).not.toBeNull();
} finally {
rmSync(repo.cwd, { recursive: true, force: true });
}
});
});
describe("merge commit handling", () => {
let mergeRepo: TempRepoWithMerge;
beforeAll(() => {
mergeRepo = createTempRepoWithMerge();
});
afterAll(() => {
rmSync(mergeRepo.cwd, { recursive: true, force: true });
});
describe("getCommitContext", () => {
it("should return commit context for a valid SHA", async () => {
const context = await getCommitContext(mergeRepo.commits.mergeCommit, mergeRepo.cwd);
expect(context).not.toBeNull();
expect(context?.sha).toBe(mergeRepo.commits.mergeCommit);
expect(context?.message).toContain("Merge pull request #42");
});
it("should extract branch name from merge commit message when decorations are empty", async () => {
// Delete the feature branch so decorations won't include it
runGit("branch -d feature/ENG-123-add-feature", mergeRepo.cwd);
const context = await getCommitContext(mergeRepo.commits.mergeCommit, mergeRepo.cwd);
expect(context?.branchName).toBe("feature/ENG-123-add-feature");
});
it("should return null for invalid SHA", async () => {
expect(await getCommitContext("invalid-sha", mergeRepo.cwd)).toBeNull();
});
});
describe("getCommitParents", () => {
it("returns 2 parents for a merge commit", () => {
const parents = getCommitParents(mergeRepo.commits.mergeCommit, mergeRepo.cwd);
expect(parents).toEqual([mergeRepo.commits.base, mergeRepo.commits.featureBranch]);
});
it("returns 1 parent for a regular commit", () => {
expect(getCommitParents(mergeRepo.commits.featureBranch, mergeRepo.cwd)).toEqual([mergeRepo.commits.base]);
});
it("returns [] for the root commit", () => {
expect(getCommitParents(mergeRepo.commits.base, mergeRepo.cwd)).toEqual([]);
});
it("returns [] for an unknown SHA", () => {
expect(getCommitParents("0000000000000000000000000000000000000000", mergeRepo.cwd)).toEqual([]);
});
});
describe("resolveFirstSyncBoundary", () => {
it("expands to HEAD^1 when HEAD is a merge commit", () => {
expect(resolveFirstSyncBoundary(mergeRepo.commits.mergeCommit, mergeRepo.cwd)).toBe(mergeRepo.commits.base);
});
it("returns the commit itself when HEAD is a regular commit", () => {
expect(resolveFirstSyncBoundary(mergeRepo.commits.featureBranch, mergeRepo.cwd)).toBe(
mergeRepo.commits.featureBranch,
);
});
it("returns the commit itself when HEAD is the root commit", () => {