-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.test.ts
More file actions
867 lines (716 loc) · 39.3 KB
/
index.test.ts
File metadata and controls
867 lines (716 loc) · 39.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
import {readFileSync} from "node:fs";
import {readFile, writeFile, rm, mkdir, mkdtemp} from "node:fs/promises";
import {tmpdir} from "node:os";
import {join} from "node:path";
import {
isSemver, incrementSemver, replaceTokens, esc,
joinStrings, findUp, getFileChanges, write,
readVersionFromPackageJson, readVersionFromPyprojectToml,
removeIgnoredFiles, getGithubTokens, getGiteaTokens,
getRepoInfo, writeResult, createForgeRelease,
type RepoInfo,
} from "./index.ts";
import {exec, tomlGetString, SubprocessError} from "./utils.ts";
const distPath = join(process.cwd(), "dist/index.js");
afterEach(() => {
vi.unstubAllGlobals();
});
async function createBareRemote(tmpDir: string): Promise<string> {
const bareDir = join(tmpDir, "remote.git");
await exec("git", ["init", "--bare", bareDir]);
return bareDir;
}
function getIsolatedGitEnv(tmpDir: string) {
const isolatedHome = join(tmpDir, ".home");
return {
HOME: isolatedHome,
GIT_CONFIG_GLOBAL: join(isolatedHome, ".gitconfig"),
GIT_CONFIG_NOSYSTEM: "1",
};
}
async function initGitRepo(tmpDir: string): Promise<void> {
const env = getIsolatedGitEnv(tmpDir);
await mkdir(env.HOME, {recursive: true});
await exec("git", ["init"], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["config", "--local", "user.email", "test@test.com"], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["config", "--local", "user.name", "Test User"], {cwd: tmpDir, env: {...process.env, ...env}});
}
async function withTmpDir(fn: (tmpDir: string) => Promise<void>): Promise<void> {
const tmpDir = await mkdtemp(join(tmpdir(), "versions-test-"));
try {
await fn(tmpDir);
} finally {
await rm(tmpDir, {recursive: true, force: true});
}
}
test("version", async () => {
const {version: expected} = JSON.parse(readFileSync(new URL("package.json", import.meta.url), "utf8"));
const {stdout} = await exec("node", [distPath, "-v"]);
expect(stdout).toEqual(expected);
});
test("semver", () => {
expect(isSemver("1.0.0")).toEqual(true);
expect(isSemver("1.0.0-pre-1.0.0")).toEqual(true);
expect(isSemver("1.2.3-0123")).toEqual(false);
expect(incrementSemver("1.0.0", "patch")).toEqual("1.0.1");
expect(incrementSemver("1.0.0", "minor")).toEqual("1.1.0");
expect(incrementSemver("1.0.0", "major")).toEqual("2.0.0");
expect(incrementSemver("2.0.0", "patch")).toEqual("2.0.1");
expect(incrementSemver("2.0.1", "minor")).toEqual("2.1.0");
expect(incrementSemver("2.1.1", "major")).toEqual("3.0.0");
expect(incrementSemver("10.10.10", "patch")).toEqual("10.10.11");
expect(incrementSemver("10.10.10", "minor")).toEqual("10.11.0");
expect(incrementSemver("10.10.10", "major")).toEqual("11.0.0");
expect(incrementSemver("1.0.0-pre-1.0.0", "patch")).toEqual("1.0.1");
expect(incrementSemver("1.0.0-pre-1.0.0", "minor")).toEqual("1.1.0");
expect(incrementSemver("1.0.0-pre-1.0.0", "major")).toEqual("2.0.0");
expect(incrementSemver("10.10.10-pre-1.0.0", "patch")).toEqual("10.10.11");
expect(incrementSemver("10.10.10-pre-1.0.0", "minor")).toEqual("10.11.0");
expect(incrementSemver("10.10.10-pre-1.0.0", "major")).toEqual("11.0.0");
});
test("versions", () => withTmpDir(async (tmpDir) => {
const pkgStr = readFileSync(new URL("package.json", import.meta.url), "utf8");
let {version} = JSON.parse(pkgStr);
await writeFile(join(tmpDir, "package.json"), pkgStr);
await writeFile(join(tmpDir, "testfile"), `testfile v${version} (1999-01-01)`);
const run = (args: string) => exec(`node ${distPath} ${args}`, [], {shell: true, cwd: tmpDir});
const verify = async (ver: string) => {
expect(await readFile(join(tmpDir, "testfile"), "utf8")).toEqual(
`testfile v${ver} (${(new Date()).toISOString().substring(0, 10)})`
);
return ver;
};
await run(`--date --base ${version} --gitless patch testfile`);
version = await verify(incrementSemver(version, "patch"));
await run(`--date --base ${version} --gitless minor testfile`);
version = await verify(incrementSemver(version, "minor"));
await run(`--date --base ${version} --gitless major testfile`);
version = await verify(incrementSemver(version, "major"));
await run(`--date --base ${version} --gitless major testfile`);
version = await verify(incrementSemver(version, "major"));
await run(`--date --base ${version} --gitless major testfile testfile`);
version = await verify(incrementSemver(version, "major"));
await run(`--date --base ${version} --gitless minor testfile`);
version = await verify(incrementSemver(version, "minor"));
}));
test("poetry", () => withTmpDir(async (tmpDir) => {
const str = await readFile(new URL("fixtures/poetry/pyproject.toml", import.meta.url), "utf8");
const versionBefore = tomlGetString(str, "tool.poetry", "version")!;
expect(tomlGetString(str, "tool.poetry.dependencies", "flask")).toEqual(versionBefore);
await writeFile(join(tmpDir, "pyproject.toml"), str);
await exec(`node ${distPath} minor --gitless --date --base ${versionBefore} pyproject.toml`, [], {shell: true, cwd: tmpDir});
const afterStr = await readFile(join(tmpDir, "pyproject.toml"), "utf8");
const versionAfter = incrementSemver(versionBefore, "minor");
expect(tomlGetString(afterStr, "tool.poetry", "version")).toEqual(versionAfter);
expect(tomlGetString(afterStr, "tool.poetry.dependencies", "flask")).toEqual(versionBefore);
}));
test("uv", () => withTmpDir(async (tmpDir) => {
const pyproject = await readFile(new URL("fixtures/uv/pyproject.toml", import.meta.url), "utf8");
const lock = await readFile(new URL("fixtures/uv/uv.lock", import.meta.url), "utf8");
const name = tomlGetString(pyproject, "project", "name")!;
const versionBefore = tomlGetString(pyproject, "project", "version")!;
await writeFile(join(tmpDir, "pyproject.toml"), pyproject);
await writeFile(join(tmpDir, "uv.lock"), lock);
await exec(`node ${distPath} minor --gitless --date --base ${versionBefore} pyproject.toml uv.lock`, [], {shell: true, cwd: tmpDir});
const afterStr = await readFile(join(tmpDir, "pyproject.toml"), "utf8");
const versionAfter = incrementSemver(versionBefore, "minor");
expect(tomlGetString(afterStr, "project", "version")).toEqual(versionAfter);
const lockStr = await readFile(join(tmpDir, "uv.lock"), "utf8");
const lockMatch = new RegExp(`\\[\\[package\\]\\]\nname = "${name}"\nversion = "([^"]+)"`).exec(lockStr);
expect(lockMatch![1]).toEqual(versionAfter);
}));
test("fallback to package.json when no git tags exist", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "package.json"), JSON.stringify({name: "test-pkg", version: "2.5.0"}, null, 2));
await writeFile(join(tmpDir, "testfile.txt"), "version 2.5.0");
await exec("node", [distPath, "--gitless", "patch", "testfile.txt"], {cwd: tmpDir});
expect(await readFile(join(tmpDir, "testfile.txt"), "utf8")).toEqual("version 2.5.1");
}));
test("fallback to pyproject.toml when no git tags exist", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "pyproject.toml"), `[project]
name = "test-project"
version = "3.2.1"
`);
await writeFile(join(tmpDir, "testfile.txt"), "version 3.2.1");
await exec("node", [distPath, "--gitless", "minor", "testfile.txt"], {cwd: tmpDir});
expect(await readFile(join(tmpDir, "testfile.txt"), "utf8")).toEqual("version 3.3.0");
}));
test("fallback behavior with git repo but no tags", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "package.json"), JSON.stringify({name: "test-package", version: "5.1.0"}, null, 2));
await writeFile(join(tmpDir, "testfile.txt"), "version 5.1.0");
await exec("node", [distPath, "--gitless", "major", "testfile.txt"], {cwd: tmpDir});
expect(await readFile(join(tmpDir, "testfile.txt"), "utf8")).toEqual("version 6.0.0");
}));
test("poetry-style pyproject.toml fallback", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "pyproject.toml"), `[tool.poetry]
name = "poetry-test"
version = "0.5.2"
`);
await writeFile(join(tmpDir, "testfile.txt"), "version 0.5.2");
await exec("node", [distPath, "--gitless", "patch", "testfile.txt"], {cwd: tmpDir});
expect(await readFile(join(tmpDir, "testfile.txt"), "utf8")).toEqual("version 0.5.3");
}));
test("package.json takes precedence over pyproject.toml", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "package.json"), JSON.stringify({name: "test-pkg", version: "1.0.0"}, null, 2));
await writeFile(join(tmpDir, "pyproject.toml"), `[project]
name = "test-project"
version = "2.0.0"
`);
await writeFile(join(tmpDir, "testfile.txt"), "version 1.0.0");
await exec("node", [distPath, "--gitless", "patch", "testfile.txt"], {cwd: tmpDir});
expect(await readFile(join(tmpDir, "testfile.txt"), "utf8")).toEqual("version 1.0.1");
}));
test("fallback to pyproject.toml when package.json has invalid semver", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "package.json"), JSON.stringify({name: "test-pkg", version: "invalid"}, null, 2));
await writeFile(join(tmpDir, "pyproject.toml"), `[project]
name = "test-project"
version = "3.0.0"
`);
await writeFile(join(tmpDir, "testfile.txt"), "version 3.0.0");
await exec("node", [distPath, "--gitless", "minor", "testfile.txt"], {cwd: tmpDir});
expect(await readFile(join(tmpDir, "testfile.txt"), "utf8")).toEqual("version 3.1.0");
}));
test("prerelease from stable version", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "package.json"), JSON.stringify({name: "test-pkg", version: "1.0.0"}, null, 2));
await writeFile(join(tmpDir, "testfile.txt"), "version 1.0.0");
await exec("node", [distPath, "--gitless", "--preid=alpha", "prerelease", "testfile.txt"], {cwd: tmpDir});
expect(await readFile(join(tmpDir, "testfile.txt"), "utf8")).toEqual("version 1.0.1-alpha.0");
}));
test("prerelease increment with same preid", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "package.json"), JSON.stringify({name: "test-pkg", version: "1.0.1-beta.0"}, null, 2));
await writeFile(join(tmpDir, "testfile.txt"), "version 1.0.1-beta.0");
await exec("node", [distPath, "--gitless", "--preid=beta", "prerelease", "testfile.txt"], {cwd: tmpDir});
expect(await readFile(join(tmpDir, "testfile.txt"), "utf8")).toEqual("version 1.0.1-beta.1");
}));
test("prerelease with different preid", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "package.json"), JSON.stringify({name: "test-pkg", version: "2.0.0-alpha.5"}, null, 2));
await writeFile(join(tmpDir, "testfile.txt"), "version 2.0.0-alpha.5");
await exec("node", [distPath, "--gitless", "--preid=rc", "prerelease", "testfile.txt"], {cwd: tmpDir});
expect(await readFile(join(tmpDir, "testfile.txt"), "utf8")).toEqual("version 2.0.0-rc.0");
}));
test("prerelease without preid fails", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "package.json"), JSON.stringify({name: "test-pkg", version: "1.0.0"}, null, 2));
await writeFile(join(tmpDir, "testfile.txt"), "version 1.0.0");
let error;
try {
await exec("node", [distPath, "--gitless", "prerelease", "testfile.txt"], {cwd: tmpDir});
} catch (err) {
error = err;
}
expect(error).toBeDefined();
}));
test("patch with preid creates prerelease", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "package.json"), JSON.stringify({name: "test-pkg", version: "1.0.0"}, null, 2));
await writeFile(join(tmpDir, "testfile.txt"), "version 1.0.0");
await exec("node", [distPath, "--gitless", "--preid=alpha", "patch", "testfile.txt"], {cwd: tmpDir});
expect(await readFile(join(tmpDir, "testfile.txt"), "utf8")).toEqual("version 1.0.1-alpha.0");
}));
test("minor with preid creates prerelease", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "package.json"), JSON.stringify({name: "test-pkg", version: "1.0.0"}, null, 2));
await writeFile(join(tmpDir, "testfile.txt"), "version 1.0.0");
await exec("node", [distPath, "--gitless", "--preid=beta", "minor", "testfile.txt"], {cwd: tmpDir});
expect(await readFile(join(tmpDir, "testfile.txt"), "utf8")).toEqual("version 1.1.0-beta.0");
}));
test("major with preid creates prerelease", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "package.json"), JSON.stringify({name: "test-pkg", version: "1.0.0"}, null, 2));
await writeFile(join(tmpDir, "testfile.txt"), "version 1.0.0");
await exec("node", [distPath, "--gitless", "--preid=rc", "major", "testfile.txt"], {cwd: tmpDir});
expect(await readFile(join(tmpDir, "testfile.txt"), "utf8")).toEqual("version 2.0.0-rc.0");
}));
test("patch with preid on prerelease version strips old prerelease", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "package.json"), JSON.stringify({name: "test-pkg", version: "1.0.0-alpha.5"}, null, 2));
await writeFile(join(tmpDir, "testfile.txt"), "version 1.0.0-alpha.5");
await exec("node", [distPath, "--gitless", "--preid=beta", "patch", "testfile.txt"], {cwd: tmpDir});
expect(await readFile(join(tmpDir, "testfile.txt"), "utf8")).toEqual("version 1.0.1-beta.0");
}));
test("package.json with non-matching base version", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "package.json"), JSON.stringify({name: "test-pkg", version: "1.0.0"}, null, 2));
await exec("node", [distPath, "--gitless", "--base", "8.16.3", "patch", "package.json"], {cwd: tmpDir});
const result = JSON.parse(await readFile(join(tmpDir, "package.json"), "utf8"));
expect(result.version).toEqual("8.16.4");
}));
test("pyproject.toml with non-matching base version", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "pyproject.toml"), `[project]
name = "test-project"
version = "2.0.0"
`);
await exec("node", [distPath, "--gitless", "--base", "5.3.1", "minor", "pyproject.toml"], {cwd: tmpDir});
const resultStr = await readFile(join(tmpDir, "pyproject.toml"), "utf8");
expect(tomlGetString(resultStr, "project", "version")).toEqual("5.4.0");
}));
test("lockfiles are not corrupted by version replacement", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "package.json"), JSON.stringify({name: "test-pkg", version: "2.3.0"}, null, 2));
const lockContent = `lockfileVersion: '9.0'
packages:
some-dep@2.3.0:
resolution: {integrity: sha512-abc123}
engines: {node: '>=8'}
snapshots:
some-dep@2.3.0:
dependencies:
other-dep: 1.0.0
`;
await writeFile(join(tmpDir, "pnpm-lock.yaml"), lockContent);
await exec("node", [distPath, "--gitless", "--base", "2.3.0", "patch", "package.json", "pnpm-lock.yaml"], {cwd: tmpDir});
const pkgAfter = JSON.parse(await readFile(join(tmpDir, "package.json"), "utf8"));
expect(pkgAfter.version).toEqual("2.3.1");
expect(await readFile(join(tmpDir, "pnpm-lock.yaml"), "utf8")).toEqual(lockContent);
}));
test("createForgeRelease github success", async () => {
const mock = vi.fn(() => Promise.resolve(Response.json({html_url: "https://github.com/o/r/releases/tag/1.0.1"}, {status: 201})));
vi.stubGlobal("fetch", mock);
const info: RepoInfo = {owner: "o", repo: "r", host: "github.com", type: "github"};
await createForgeRelease(info, "1.0.1", "changelog", ["gh-token"]);
expect(mock).toHaveBeenCalledOnce();
const [url, init] = mock.mock.calls[0] as unknown as [string, any];
expect(url).toEqual("https://api.github.com/repos/o/r/releases");
expect(init.headers.Authorization).toEqual("Bearer gh-token");
const body = JSON.parse(init.body);
expect(body.tag_name).toEqual("1.0.1");
expect(body.name).toEqual("1.0.1");
expect(body.body).toEqual("changelog");
expect(body.draft).toEqual(false);
expect(body.prerelease).toEqual(false);
});
test("createForgeRelease gitea success", async () => {
const mock = vi.fn(() => Promise.resolve(Response.json({html_url: "https://gitea.example.com/o/r/releases/tag/2.0.0"}, {status: 201})));
vi.stubGlobal("fetch", mock);
const info: RepoInfo = {owner: "o", repo: "r", host: "gitea.example.com", type: "gitea"};
await createForgeRelease(info, "2.0.0", "notes", ["gitea-tok"]);
expect(mock).toHaveBeenCalledOnce();
const [url, init] = mock.mock.calls[0] as unknown as [string, any];
expect(url).toEqual("https://gitea.example.com/api/v1/repos/o/r/releases");
expect(init.headers.Authorization).toEqual("token gitea-tok");
});
test("createForgeRelease prerelease tag", async () => {
const mock = vi.fn(() => Promise.resolve(Response.json({}, {status: 201})));
vi.stubGlobal("fetch", mock);
const info: RepoInfo = {owner: "o", repo: "r", host: "github.com", type: "github"};
await createForgeRelease(info, "1.0.0-beta.1", "body", ["tok"]);
expect(JSON.parse((mock.mock.calls[0] as unknown as [string, any])[1].body).prerelease).toEqual(true);
});
test.each([[401, "Unauthorized"], [403, "Forbidden"]])("createForgeRelease token fallback on %i", async (status, text) => {
const mock = vi.fn()
.mockResolvedValueOnce(new Response(text, {status}))
.mockImplementation(() => Promise.resolve(Response.json({html_url: "https://github.com/o/r/releases/tag/1.0.0"}, {status: 201})));
vi.stubGlobal("fetch", mock);
const info: RepoInfo = {owner: "o", repo: "r", host: "github.com", type: "github"};
await createForgeRelease(info, "1.0.0", "body", ["bad-token", "good-token"]);
expect(mock).toHaveBeenCalledTimes(2);
});
test("createForgeRelease throws on non-auth error", async () => {
vi.stubGlobal("fetch", vi.fn(() => Promise.resolve(new Response("Validation failed", {status: 422, statusText: "Unprocessable Entity"}))));
const info: RepoInfo = {owner: "o", repo: "r", host: "github.com", type: "github"};
await expect(createForgeRelease(info, "1.0.0", "body", ["tok"])).rejects.toThrow("422");
});
test("createForgeRelease throws when all tokens fail", async () => {
vi.stubGlobal("fetch", vi.fn(() => Promise.resolve(new Response("Unauthorized", {status: 401, statusText: "Unauthorized"}))));
const info: RepoInfo = {owner: "o", repo: "r", host: "github.com", type: "github"};
await expect(createForgeRelease(info, "1.0.0", "body", ["tok1", "tok2"])).rejects.toThrow("401");
});
test("createForgeRelease network error includes cause", async () => {
vi.stubGlobal("fetch", vi.fn().mockRejectedValue(
Object.assign(new TypeError("fetch failed"), {cause: new Error("getaddrinfo ENOTFOUND example.com")}),
));
const info: RepoInfo = {owner: "o", repo: "r", host: "example.com", type: "gitea"};
await expect(createForgeRelease(info, "1.0.0", "body", ["tok"])).rejects.toThrow("getaddrinfo ENOTFOUND example.com");
});
test("createForgeRelease no html_url in response", async () => {
vi.stubGlobal("fetch", vi.fn(() => Promise.resolve(Response.json({id: 1}, {status: 201}))));
const info: RepoInfo = {owner: "o", repo: "r", host: "github.com", type: "github"};
await createForgeRelease(info, "1.0.0", "body", ["tok"]);
});
test("release rejects detached HEAD", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "package.json"), JSON.stringify({name: "test-pkg", version: "1.0.0"}, null, 2));
await initGitRepo(tmpDir);
const env = getIsolatedGitEnv(tmpDir);
const bareDir = await createBareRemote(tmpDir);
await exec("git", ["add", "."], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["commit", "-m", "Initial commit"], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["remote", "add", "origin", "https://github.com/o/r.git"], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["remote", "set-url", "--push", "origin", bareDir], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["push", "origin", "master"], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["tag", "1.0.0"], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["checkout", "--detach"], {cwd: tmpDir, env: {...process.env, ...env}});
try {
await exec("node", [distPath, "--release", "patch", "package.json"], {
cwd: tmpDir,
env: {...process.env, GITHUB_TOKEN: "tok", ...env},
});
throw new Error("should have thrown");
} catch (err: any) {
expect(err).toBeInstanceOf(SubprocessError);
expect(err.exitCode).toEqual(1);
}
}));
test("--gitless and --release are mutually exclusive", async () => {
try {
await exec("node", [distPath, "--gitless", "--release", "--base", "1.0.0", "patch"]);
throw new Error("should have thrown");
} catch (err: any) {
expect(err).toBeInstanceOf(SubprocessError);
expect(err.exitCode).toEqual(1);
}
});
test("release integration - github push and tag", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "package.json"), JSON.stringify({name: "test-pkg", version: "1.0.0"}, null, 2));
await initGitRepo(tmpDir);
const env = getIsolatedGitEnv(tmpDir);
const bareDir = await createBareRemote(tmpDir);
await exec("git", ["add", "."], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["commit", "-m", "Initial commit"], {cwd: tmpDir, env: {...process.env, ...env}});
// github.com fetch URL for type detection, local bare for push
await exec("git", ["remote", "add", "origin", "https://github.com/owner/repo.git"], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["remote", "set-url", "--push", "origin", bareDir], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["push", "origin", "master"], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["tag", "1.0.0"], {cwd: tmpDir, env: {...process.env, ...env}});
// versions will push to local bare (via push URL) then try api.github.com (which fails with fake token)
try {
await exec("node", [distPath, "--release", "patch", "package.json"], {
cwd: tmpDir,
env: {...process.env, GITHUB_TOKEN: "fake-token", ...env},
});
} catch (err: any) {
expect(err).toBeInstanceOf(SubprocessError);
expect(err.exitCode).toEqual(1);
}
// verify local tag was created
const {stdout: tags} = await exec("git", ["tag", "--list"], {cwd: tmpDir, env: {...process.env, ...env}});
expect(tags.trim().split("\n").filter(Boolean).sort()).toEqual(["1.0.0", "1.0.1"]);
// verify tag was pushed to bare remote
const {stdout: remoteTags} = await exec("git", ["tag", "--list"], {cwd: bareDir});
expect(remoteTags.trim().split("\n").filter(Boolean)).toContain("1.0.1");
// verify commit was pushed
const {stdout: localHead} = await exec("git", ["rev-parse", "HEAD"], {cwd: tmpDir, env: {...process.env, ...env}});
const {stdout: remoteHead} = await exec("git", ["rev-parse", "HEAD"], {cwd: bareDir});
expect(remoteHead.trim()).toEqual(localHead.trim());
}));
test("release integration - gitea push and tag", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "package.json"), JSON.stringify({name: "test-pkg", version: "1.0.0"}, null, 2));
await initGitRepo(tmpDir);
const env = getIsolatedGitEnv(tmpDir);
const bareDir = await createBareRemote(tmpDir);
await exec("git", ["add", "."], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["commit", "-m", "Initial commit"], {cwd: tmpDir, env: {...process.env, ...env}});
// gitea fetch URL for type detection, local bare for push
await exec("git", ["remote", "add", "origin", "https://gitea.example.com/owner/repo.git"], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["remote", "set-url", "--push", "origin", bareDir], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["push", "origin", "master"], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["tag", "1.0.0"], {cwd: tmpDir, env: {...process.env, ...env}});
// versions will push to local bare then try gitea API (which fails - no such host)
try {
await exec("node", [distPath, "--release", "patch", "package.json"], {
cwd: tmpDir,
env: {...process.env, GITEA_TOKEN: "fake-token", ...env},
});
} catch (err: any) {
expect(err).toBeInstanceOf(SubprocessError);
expect(err.exitCode).toEqual(1);
}
// verify local tag was created
const {stdout: tags} = await exec("git", ["tag", "--list"], {cwd: tmpDir, env: {...process.env, ...env}});
expect(tags.trim().split("\n").filter(Boolean).sort()).toEqual(["1.0.0", "1.0.1"]);
// verify tag was pushed to bare remote
const {stdout: remoteTags} = await exec("git", ["tag", "--list"], {cwd: bareDir});
expect(remoteTags.trim().split("\n").filter(Boolean)).toContain("1.0.1");
}));
test("release integration - tag already exists on remote (different commit)", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "package.json"), JSON.stringify({name: "test-pkg", version: "1.0.0"}, null, 2));
await initGitRepo(tmpDir);
const env = getIsolatedGitEnv(tmpDir);
const bareDir = await createBareRemote(tmpDir);
await exec("git", ["add", "."], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["commit", "-m", "Initial commit"], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["remote", "add", "origin", "https://github.com/o/r.git"], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["remote", "set-url", "--push", "origin", bareDir], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["push", "origin", "master"], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["tag", "1.0.0"], {cwd: tmpDir, env: {...process.env, ...env}});
// pre-create tag 1.0.1 on bare remote pointing to a DIFFERENT commit (simulates immutable/conflicting tag)
const {stdout: oldHead} = await exec("git", ["rev-parse", "HEAD"], {cwd: bareDir});
await exec("git", ["tag", "1.0.1", oldHead.trim()], {cwd: bareDir});
// versions creates a new commit then tries to push tag 1.0.1 which conflicts
try {
await exec("node", [distPath, "--release", "patch", "package.json"], {
cwd: tmpDir,
env: {...process.env, GITHUB_TOKEN: "tok", ...env},
});
throw new Error("should have thrown");
} catch (err: any) {
expect(err).toBeInstanceOf(SubprocessError);
expect(err.exitCode).toEqual(1);
}
}));
test("incrementSemver prerelease", () => {
expect(incrementSemver("1.0.0", "prerelease", "alpha")).toEqual("1.0.1-alpha.0");
expect(incrementSemver("1.0.1-beta.0", "prerelease", "beta")).toEqual("1.0.1-beta.1");
expect(incrementSemver("2.0.0-alpha.5", "prerelease", "rc")).toEqual("2.0.0-rc.0");
expect(incrementSemver("1.0.0", "patch", "alpha")).toEqual("1.0.1-alpha.0");
expect(incrementSemver("1.0.0", "minor", "beta")).toEqual("1.1.0-beta.0");
expect(incrementSemver("1.0.0", "major", "rc")).toEqual("2.0.0-rc.0");
expect(() => incrementSemver("1.0.0", "prerelease")).toThrow("prerelease requires --preid option");
expect(() => incrementSemver("invalid", "patch")).toThrow("Invalid semver");
});
test("replaceTokens", () => {
expect(replaceTokens("version _VER_", "2.3.4")).toEqual("version 2.3.4");
expect(replaceTokens("v_MAJOR_._MINOR_._PATCH_", "2.3.4")).toEqual("v2.3.4");
expect(replaceTokens("_VER_ _MAJOR_ _MINOR_ _PATCH_", "10.20.30")).toEqual("10.20.30 10 20 30");
expect(replaceTokens("no tokens", "1.0.0")).toEqual("no tokens");
});
test("esc", () => {
expect(esc("1.0.0")).toEqual("1\\.0\\.0");
expect(esc("a|b")).toEqual("a\\|b");
expect(esc("abc")).toEqual("abc");
expect(esc("")).toEqual("");
});
test("joinStrings", () => {
expect(joinStrings(["a", "b", "c"], "\n")).toEqual("a\nb\nc");
expect(joinStrings(["a", undefined, "c"], "\n")).toEqual("a\nc");
expect(joinStrings([undefined, undefined], "\n")).toEqual("");
expect(joinStrings([" a "], "\n")).toEqual("a");
});
test("findUp", () => withTmpDir(async (tmpDir) => {
const subDir = join(tmpDir, "a", "b");
await mkdir(subDir, {recursive: true});
await writeFile(join(tmpDir, "target.txt"), "found");
expect(findUp("target.txt", subDir)).toEqual(join(tmpDir, "target.txt"));
expect(findUp("nonexistent.txt", subDir, tmpDir)).toBeNull();
}));
test("help", async () => {
const {stdout} = await exec("node", [distPath, "--help"]);
expect(stdout).toContain("usage: versions");
expect(stdout).toContain("--replace");
});
test("no args prints help", async () => {
const {stdout} = await exec("node", [distPath]);
expect(stdout).toContain("usage: versions");
});
test("dry mode", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "package.json"), JSON.stringify({name: "test", version: "1.0.0"}, null, 2));
await writeFile(join(tmpDir, "testfile.txt"), "version 1.0.0");
await initGitRepo(tmpDir);
const env = getIsolatedGitEnv(tmpDir);
await exec("git", ["add", "."], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["commit", "-m", "init"], {cwd: tmpDir, env: {...process.env, ...env}});
const {stdout} = await exec("node", [distPath, "--dry", "patch", "testfile.txt"], {
cwd: tmpDir, env: {...process.env, ...env},
});
expect(stdout).toContain("Would create new tag and commit: 1.0.1");
expect(await readFile(join(tmpDir, "testfile.txt"), "utf8")).toEqual("version 1.0.1");
}));
test("prefix", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "package.json"), JSON.stringify({name: "test", version: "1.0.0"}, null, 2));
await writeFile(join(tmpDir, "testfile.txt"), "version 1.0.0");
await initGitRepo(tmpDir);
const env = getIsolatedGitEnv(tmpDir);
await exec("git", ["add", "."], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["commit", "-m", "init"], {cwd: tmpDir, env: {...process.env, ...env}});
const {stdout} = await exec("node", [distPath, "--dry", "--prefix", "patch", "testfile.txt"], {
cwd: tmpDir, env: {...process.env, ...env},
});
expect(stdout).toContain("Would create new tag and commit: v1.0.1");
}));
test("replace", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "testfile.txt"), "version 1.0.0\ncopyright YEAR_PLACEHOLDER");
await exec("node", [distPath, "--gitless", "--base", "1.0.0", "-r", "s#YEAR_PLACEHOLDER#_VER_#", "patch", "testfile.txt"], {cwd: tmpDir});
expect(await readFile(join(tmpDir, "testfile.txt"), "utf8")).toEqual("version 1.0.1\ncopyright 1.0.1");
}));
test("command", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "testfile.txt"), "version 1.0.0");
await exec("node", [distPath, "--gitless", "--base", "1.0.0", "-c", "echo hello > marker.txt", "patch", "testfile.txt"], {cwd: tmpDir});
expect(await readFile(join(tmpDir, "testfile.txt"), "utf8")).toEqual("version 1.0.1");
expect(await readFile(join(tmpDir, "marker.txt"), "utf8")).toContain("hello");
}));
test("package-lock.json", () => withTmpDir(async (tmpDir) => {
const lockData = {
name: "test",
version: "1.0.0",
lockfileVersion: 3,
packages: {"": {name: "test", version: "1.0.0"}, "node_modules/dep": {version: "2.0.0"}},
};
await writeFile(join(tmpDir, "package-lock.json"), JSON.stringify(lockData, null, 2));
await exec("node", [distPath, "--gitless", "--base", "1.0.0", "patch", "package-lock.json"], {cwd: tmpDir});
const result = JSON.parse(await readFile(join(tmpDir, "package-lock.json"), "utf8"));
expect(result.version).toEqual("1.0.1");
expect(result.packages[""].version).toEqual("1.0.1");
expect(result.packages["node_modules/dep"].version).toEqual("2.0.0");
}));
test("go.sum is skipped", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "go.sum"), "content with 1.0.0");
await exec("node", [distPath, "--gitless", "--base", "1.0.0", "patch", "go.sum"], {cwd: tmpDir});
expect(await readFile(join(tmpDir, "go.sum"), "utf8")).toEqual("content with 1.0.0");
}));
test("arbitrary lock file is skipped", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "Gemfile.lock"), "gem 1.0.0");
await exec("node", [distPath, "--gitless", "--base", "1.0.0", "patch", "Gemfile.lock"], {cwd: tmpDir});
expect(await readFile(join(tmpDir, "Gemfile.lock"), "utf8")).toEqual("gem 1.0.0");
}));
test("SubprocessError", () => {
const err = new SubprocessError("failed", "out", "err", 1);
expect(err.message).toEqual("failed");
expect(err.stdout).toEqual("out");
expect(err.stderr).toEqual("err");
expect(err.output).toEqual("err\nout");
expect(err.name).toEqual("SubprocessError");
expect(err.exitCode).toEqual(1);
const errNoOutput = new SubprocessError("failed");
expect(errNoOutput.output).toEqual("");
expect(errNoOutput.exitCode).toBeNull();
});
test("exec error", async () => {
await expect(exec("false", [])).rejects.toThrow();
try {
await exec("false", []);
} catch (err) {
expect(err).toBeInstanceOf(SubprocessError);
}
});
test("tomlGetString edge cases", () => {
expect(tomlGetString("", "project", "version")).toBeUndefined();
expect(tomlGetString("# comment\n[project]\nversion = '1.0.0'", "project", "version")).toEqual("1.0.0");
expect(tomlGetString("[project]\nname = 'test'", "project", "version")).toBeUndefined();
expect(tomlGetString("[other]\nversion = '1.0.0'", "project", "version")).toBeUndefined();
});
test("incrementSemver unknown level throws", () => {
expect(() => incrementSemver("1.0.0", "unknown")).toThrow("Invalid semver level");
});
test("readVersionFromPackageJson", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "package.json"), JSON.stringify({name: "test", version: "3.2.1"}, null, 2));
expect(readVersionFromPackageJson(tmpDir)).toEqual("3.2.1");
const subDir = join(tmpDir, "sub");
await mkdir(subDir);
expect(readVersionFromPackageJson(subDir)).toEqual("3.2.1");
}));
test("readVersionFromPackageJson returns null", () => withTmpDir(async (tmpDir) => {
expect(readVersionFromPackageJson(tmpDir)).toBeNull();
await writeFile(join(tmpDir, "package.json"), JSON.stringify({name: "test"}, null, 2));
expect(readVersionFromPackageJson(tmpDir)).toBeNull();
}));
test("readVersionFromPyprojectToml", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "pyproject.toml"), `[project]\nname = "test"\nversion = "1.5.0"\n`);
expect(readVersionFromPyprojectToml(tmpDir)).toEqual("1.5.0");
}));
test("readVersionFromPyprojectToml poetry", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "pyproject.toml"), `[tool.poetry]\nname = "test"\nversion = "2.0.0"\n`);
expect(readVersionFromPyprojectToml(tmpDir)).toEqual("2.0.0");
}));
test("readVersionFromPyprojectToml returns null", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "pyproject.toml"), `[project]\nname = "test"\n`);
expect(readVersionFromPyprojectToml(tmpDir)).toBeNull();
}));
test("getFileChanges package.json", () => withTmpDir(async (tmpDir) => {
const file = join(tmpDir, "package.json");
await writeFile(file, JSON.stringify({name: "test", version: "1.0.0"}, null, 2));
const [, content] = getFileChanges({file, baseVersion: "1.0.0", newVersion: "1.0.1"});
expect(JSON.parse(content!).version).toEqual("1.0.1");
}));
test("getFileChanges package-lock.json", () => withTmpDir(async (tmpDir) => {
const file = join(tmpDir, "package-lock.json");
const data = {name: "test", version: "1.0.0", lockfileVersion: 3, packages: {"": {version: "1.0.0"}}};
await writeFile(file, JSON.stringify(data, null, 2));
const [, content] = getFileChanges({file, baseVersion: "1.0.0", newVersion: "2.0.0"});
const result = JSON.parse(content!);
expect(result.version).toEqual("2.0.0");
expect(result.packages[""].version).toEqual("2.0.0");
}));
test("getFileChanges pyproject.toml", () => withTmpDir(async (tmpDir) => {
const file = join(tmpDir, "pyproject.toml");
await writeFile(file, `[project]\nname = "test"\nversion = "1.0.0"\n`);
const [, content] = getFileChanges({file, baseVersion: "1.0.0", newVersion: "1.1.0"});
expect(content).toContain(`version = "1.1.0"`);
}));
test("getFileChanges uv.lock", () => withTmpDir(async (tmpDir) => {
await writeFile(join(tmpDir, "pyproject.toml"), `[project]\nname = "myapp"\nversion = "1.0.0"\n`);
const file = join(tmpDir, "uv.lock");
await writeFile(file, `[[package]]\nname = "myapp"\nversion = "1.0.0"\n`);
const [, content] = getFileChanges({file, baseVersion: "1.0.0", newVersion: "1.1.0"});
expect(content).toContain(`version = "1.1.0"`);
}));
test("getFileChanges generic file", () => withTmpDir(async (tmpDir) => {
const file = join(tmpDir, "version.txt");
await writeFile(file, "version 1.0.0 here");
const [, content] = getFileChanges({file, baseVersion: "1.0.0", newVersion: "2.0.0"});
expect(content).toEqual("version 2.0.0 here");
}));
test("getFileChanges lockfile skip", () => withTmpDir(async (tmpDir) => {
const file = join(tmpDir, "yarn.lock");
await writeFile(file, "content 1.0.0");
const [, content] = getFileChanges({file, baseVersion: "1.0.0", newVersion: "2.0.0"});
expect(content).toBeNull();
}));
test("getFileChanges with date", () => withTmpDir(async (tmpDir) => {
const file = join(tmpDir, "changelog.txt");
await writeFile(file, "version 1.0.0 released 2020-01-01");
const [, content] = getFileChanges({file, baseVersion: "1.0.0", newVersion: "1.0.1", date: "2025-06-15"});
expect(content).toEqual("version 1.0.1 released 2025-06-15");
}));
test("getFileChanges with replacements", () => withTmpDir(async (tmpDir) => {
const file = join(tmpDir, "file.txt");
await writeFile(file, "version 1.0.0 FOO");
const [, content] = getFileChanges({
file, baseVersion: "1.0.0", newVersion: "1.0.1",
replacements: [{re: /FOO/, replacement: "BAR"}],
});
expect(content).toEqual("version 1.0.1 BAR");
}));
test("write", () => withTmpDir(async (tmpDir) => {
const file = join(tmpDir, "out.txt");
await writeFile(file, "old");
write(file, "new");
expect(await readFile(file, "utf8")).toEqual("new");
}));
test("getGithubTokens", async () => {
const saved = {...process.env};
delete process.env.VERSIONS_FORGE_TOKEN;
delete process.env.GITHUB_API_TOKEN;
delete process.env.GITHUB_TOKEN;
delete process.env.GH_TOKEN;
delete process.env.HOMEBREW_GITHUB_API_TOKEN;
await getGithubTokens(); // may contain gh auth token if gh is installed
process.env.GH_TOKEN = "test-token";
expect(await getGithubTokens()).toContain("test-token");
Object.assign(process.env, saved);
});
test("getGiteaTokens", () => {
const saved = {...process.env};
delete process.env.VERSIONS_FORGE_TOKEN;
delete process.env.GITEA_API_TOKEN;
delete process.env.GITEA_AUTH_TOKEN;
delete process.env.GITEA_TOKEN;
expect(getGiteaTokens()).toEqual([]);
process.env.GITEA_TOKEN = "gitea-tok";
expect(getGiteaTokens()).toContain("gitea-tok");
Object.assign(process.env, saved);
});
test("getRepoInfo", async () => {
const info = await getRepoInfo();
expect(info).toBeTruthy();
expect(info!.type).toEqual("github");
expect(info!.owner).toBeTruthy();
expect(info!.repo).toBeTruthy();
expect(info!.host).toEqual("github.com");
});
test("getRepoInfo returns null without git", () => withTmpDir(async (tmpDir) => {
expect(await getRepoInfo(tmpDir)).toBeNull();
}));
test("removeIgnoredFiles", () => withTmpDir(async (tmpDir) => {
await initGitRepo(tmpDir);
const env = getIsolatedGitEnv(tmpDir);
await writeFile(join(tmpDir, ".gitignore"), "ignored.txt\n");
await writeFile(join(tmpDir, "kept.txt"), "");
await writeFile(join(tmpDir, "ignored.txt"), "");
await exec("git", ["add", "."], {cwd: tmpDir, env: {...process.env, ...env}});
await exec("git", ["commit", "-m", "init"], {cwd: tmpDir, env: {...process.env, ...env}});
const result = await removeIgnoredFiles(["kept.txt", "ignored.txt"], tmpDir);
expect(result).toEqual(["kept.txt"]);
}));
test("writeResult", () => {
let output = "";
const origWrite = process.stdout.write;
process.stdout.write = ((chunk: any) => { output += chunk; return true; }) as any;
try {
writeResult({stdout: "hello", stderr: "warn"});
expect(output).toContain("hello");
expect(output).toContain("warn");
} finally {
process.stdout.write = origWrite;
}
});