Repository navigation
Expand file tree
/
Copy pathindex.test.ts
More file actions
1736 lines (1627 loc) · 112 KB
/
Copy pathindex.test.ts
File metadata and controls
1736 lines (1627 loc) · 112 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 {execFile} from "node:child_process";
import {AsyncLocalStorage} from "node:async_hooks";
import {createServer, type IncomingMessage} from "node:http";
import {basename, dirname, join, parse, relative} from "node:path";
import {
appendFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, statSync, symlinkSync,
writeFileSync,
} from "node:fs";
import {readFile, rm} from "node:fs/promises";
import {pathToFileURL} from "node:url";
import {tmpdir} from "node:os";
import {env, platform, versions} from "node:process";
import {gzip, gzipSync, constants} from "node:zlib";
import {format, promisify} from "node:util";
import {Readable} from "node:stream";
import type {AddressInfo} from "node:net";
import {satisfies} from "./utils/semver.ts";
import {forgeDirs, getOrSet} from "./utils/utils.ts";
import {updates} from "./api.ts";
import {parseCliArgs, resolveConfig, runCli} from "./cli.ts";
import type {UpdatesOptions} from "./api.ts";
import {rejection, sequential, withEnv} from "./utils/testing.ts";
const execFileAsync = promisify(execFile);
const cliStderr = new AsyncLocalStorage<(text: string) => void>();
const realConsoleError = console.error;
console.error = (...args) => {
const write = cliStderr.getStore();
if (write) write(`${format(...args)}\n`);
else realConsoleError(...args);
};
const realFetch = globalThis.fetch;
const gzipOptions = {level: constants.Z_BEST_SPEED};
const fixture = (path: string) => join(import.meta.dirname, "fixtures", path);
const read = (...paths: Array<string>) => readFileSync(join(...paths), "utf8");
const lines = (...rows: Array<string>) => `${rows.join("\n")}\n`;
const testFile = fixture("npm-test/package.json");
const emptyFile = fixture("npm-empty/package.json");
const uvFile = fixture("uv/pyproject.toml");
const goFile = fixture("go/go.mod");
const goPreFile = fixture("go-prerelease/go.mod");
const actionsDir = fixture("actions/.github/workflows");
const composeFixture = fixture("docker/docker-compose.yaml");
const dockerActionsDir = fixture("docker-actions/.github/workflows");
const pnpmWorkspaceFile = fixture("pnpm-workspace/pnpm-workspace.yaml");
const testPkg = JSON.parse(read(testFile));
const testDir = mkdtempSync(join(tmpdir(), "updates-"));
const originalXdgConfigHome = env.XDG_CONFIG_HOME;
const sourceScript = join(import.meta.dirname, "index.ts");
const script = join(import.meta.dirname, "dist/index.js");
type RouteHandler = (req: any, res: any) => void;
const routes = new Map<string, RouteHandler>();
const requestedUrls: Array<string> = [];
const mockServer = createServer((req, res) => {
requestedUrls.push(req.url!);
(res as any).send = (data: Buffer) => {
res.setHeader("Content-Encoding", "gzip");
res.end(data);
};
try {
const handler = routes.get(req.url!.split("?")[0]);
if (!handler) res.writeHead(404).end();
else if (handler(req, res) as unknown) throw new Error("route handler returned a promise; it must be synchronous");
} catch (err) {
res.statusCode = 500;
res.end(String(err));
}
});
await new Promise<void>(resolve => mockServer.listen(0, "127.0.0.1", resolve));
const mockUrl = `http://127.0.0.1:${(mockServer.address() as AddressInfo).port}`;
const [npmUrl, githubUrl, pypiUrl, jsrUrl, goProxyUrl, cargoUrl, dockerUrl] =
["npm", "github", "pypi", "jsr", "go", "cargo", "docker"].map(prefix => `${mockUrl}/${prefix}/`);
const apiUrls = {registry: npmUrl, forgeapi: githubUrl, pypiapi: pypiUrl, jsrapi: jsrUrl, goproxy: goProxyUrl, cargoapi: cargoUrl, dockerapi: dockerUrl};
globalThis.fetch = ((input: any, init?: any) => {
const url = String(input?.url ?? input);
const mockedUrl = url.replace("https://api.github.com/repos/o/", () => `${githubUrl}repos/o/`)
.replace("https://code.forgejo.org/", () => `${mockUrl}/forgejo/`)
.replace("https://[2001:db8::1]:5000/", () => `${mockUrl}/ipv6/`);
if (!/^http:\/\/(?:127\.0\.0\.1|localhost)[:/]/.test(mockedUrl)) throw new Error(`test attempted a non-mocked network request to ${url}`);
return realFetch(mockedUrl === url ? input : mockedUrl, init);
}) as typeof fetch;
const apiArgs = ["--no-cache", ...Object.entries(apiUrls).flatMap(([name, url]) => [`--${name}`, url])];
const apiOpts = (options: UpdatesOptions = {}): UpdatesOptions => ({files: [testFile], noCache: true, ...apiUrls, ...options});
const npmUpdates = async (options: UpdatesOptions = {}) => (await updates(apiOpts(options))).results.npm.dependencies;
writeFileSync(join(testDir, ".npmrc"), `registry=${npmUrl}\nsave-exact=false`);
writeFileSync(join(testDir, "package.json"), JSON.stringify(testPkg, null, 2));
function lazyRoute(path: string, body: () => unknown) {
let gz: Buffer | undefined;
routes.set(path, (_, res) => res.send(gz ??= gzipSync(JSON.stringify(body()), gzipOptions)));
}
beforeAll(async () => {
env.XDG_CONFIG_HOME = join(testDir, "xdg");
const fixtureText = (path: string) => readFile(fixture(path), "utf8");
await Promise.all(readdirSync(fixture("npm")).map(async file => {
const urlName = parse(file).name;
const doc = JSON.parse(await fixtureText(`npm/${file}`));
const gzips = new Map<string, Buffer>();
routes.set(`/npm/${urlName}`, (req, res) => {
const flavor = req.headers.accept?.includes("application/vnd.npm.install-v1+json") ? "abbrev" : "full";
res.send(getOrSet(gzips, flavor, () => gzipSync(JSON.stringify({...doc, time: flavor === "abbrev" ? undefined : doc.time}), gzipOptions)));
});
for (const [version, versionDoc] of Object.entries(doc.versions || {})) {
lazyRoute(`/npm/${urlName}/${version}`, () => urlName === "noty" && version === "3.1.4" ? versionDoc : {
...versionDoc as object, _npmOperationalInternal: {tmp: `tmp/${urlName}_${version}_${Date.parse(doc.time?.[version] || "2024-01-01") || 0}_0`},
});
}
}));
const goLatest = (version: string, time: string) => JSON.stringify({Version: version, Time: time});
const cargoIndex = (name: string, vers: string) => JSON.stringify({name, vers, yanked: false, pubtime: "2025-01-15T12:00:00Z"});
const dockerTags = (...tags: Array<[string, string]>) =>
JSON.stringify({count: tags.length, results: tags.map(([name, pushed]) => ({name, tag_last_pushed: pushed}))});
const staticRoutes: Array<[string, string | Promise<string>]> = [
...readdirSync(fixture("pypi")).map((file): [string, Promise<string>] =>
[`/pypi/pypi/${parse(file).name.toLowerCase().replace(/[-_.]+/g, "-")}/json`, fixtureText(`pypi/${file}`)]),
...readdirSync(fixture("jsr")).map((file): [string, Promise<string>] =>
[`/jsr/${parse(file).name.replace("__", "/")}/meta.json`, fixtureText(`jsr/${file}`)]),
["/github/repos/silverwind/updates/commits", fixtureText("github/updates-commits.json")],
["/github/repos/actions/checkout/tags", fixtureText("github/actions-checkout-tags.json")],
["/github/repos/actions/setup-node/tags", fixtureText("github/actions-setup-node-tags.json")],
["/github/repos/actions/checkout/git/commits/cccc000000000000000000000000000000000011", fixtureText("github/actions-checkout-commit-v10.0.1.json")],
["/github/repos/actions/setup-node/git/commits/bbbb000000000000000000000000000000000010", fixtureText("github/actions-setup-node-commit-v10.json")],
["/github/repos/actions/checkout/branches/main", JSON.stringify({commit: {sha: "aaaa000000000000000000000000000000000001"}})],
["/github/repos/actions/checkout/branches/release", JSON.stringify({commit: {sha: "bbbb000000000000000000000000000000000002"}})],
["/github/repos/tj-actions/changed-files/tags", "[]"],
["/docker/v2/repositories/library/node/tags", fixtureText("docker/node-tags.json")],
["/docker/v2/repositories/library/noty/tags", fixtureText("docker/node-tags.json")],
["/docker/v2/repositories/library/postgres/tags", fixtureText("docker/postgres-tags.json")],
["/docker/v2/repositories/library/redis/tags", fixtureText("docker/redis-tags.json")],
["/docker/v2/repositories/koalaman/shellcheck/tags", dockerTags(["v0.11.0", "2025-01-01T00:00:00Z"], ["v0.12.0", "2025-06-01T00:00:00Z"])],
["/docker/v2/repositories/koalaman/shellcheck/tags/v0.12.0", JSON.stringify({digest: "sha256:list-new"})],
["/docker/v2/repositories/example/image/tags", dockerTags(["1.0", "2025-01-01T00:00:00Z"], ["1.1", "2025-06-01T00:00:00Z"])],
["/docker/v2/repositories/example/makeallowed/tags",
dockerTags(["1.0", "2025-01-01T00:00:00Z"], ["1.1", "2025-03-01T00:00:00Z"], ["2.0", "2025-06-01T00:00:00Z"])],
["/cargo/se/rd/serde", fixtureText("cargo/serde-index.ndjson")],
["/cargo/to/ki/tokio", cargoIndex("tokio", "1.35.0")],
["/cargo/ra/nd/rand", cargoIndex("rand", "0.9.0")],
["/cargo/se/rd/serde_json", cargoIndex("serde_json", "1.0.120")],
["/go/github.com/google/uuid/@latest", goLatest("v1.6.0", "2024-06-13T02:52:04Z")],
["/go/github.com/google/uuid/v2/@latest", goLatest("v2.0.0-20260217135312-8c5a7de9ffa1", "2026-02-17T13:53:12Z")],
["/go/github.com/google/go-github/v70/@latest", goLatest("v70.0.0", "2024-11-29T00:00:00Z")],
...Array.from({length: 12}, (_, index): [string, string] =>
[`/go/github.com/google/go-github/v${index + 71}/@latest`, goLatest(`v${index + 71}.0.0`, "2025-01-01T00:00:00Z")]),
["/go/github.com/example/testpkg/@latest", goLatest("v1.0.0", "2024-01-01T00:00:00Z")],
["/go/github.com/example/testpkg/v2/@latest", goLatest("v2.0.0", "2025-01-01T00:00:00Z")],
["/go/github.com/example/prerelpkg/@latest", goLatest("v1.1.0-rc.1", "2025-06-01T00:00:00Z")],
["/go/gitea.com/gitea/act/@latest", goLatest("v0.261.7", "2025-06-01T00:00:00Z")],
["/go/github.com/example/pseudopkg/@latest", goLatest("v0.4.1", "2023-06-01T00:00:00Z")],
["/go/github.com/example/pseudoupd/@latest", goLatest("v1.5.0", "2025-06-01T00:00:00Z")],
["/go/github.com/example/makeallowed/@latest", goLatest("v1.1.0", "2025-01-01T00:00:00Z")],
["/go/github.com/example/makeallowed/v2/@latest", goLatest("v2.0.0", "2025-06-01T00:00:00Z")],
["/go/github.com/example/listonly/@v/list", "v1.0.0\nv1.2.0\nv1.3.0-rc.1\n"],
["/go/github.com/example/listonly/@v/v1.2.0.info", goLatest("v1.2.0", "2025-03-01T00:00:00Z")],
["/go/github.com/example/listtime/@v/list", "v1.0.0 2024-01-01T00:00:00Z\nv1.1.0 2024-06-01T00:00:00Z\n"],
];
await Promise.all(staticRoutes.map(async ([path, body]) => {
const gz = await promisify(gzip)(await body, gzipOptions);
routes.set(path, (_, res) => res.send(gz));
}));
routes.set("/docker/v2/repositories/example/broken/tags", (_, res) => { res.writeHead(500).end(); });
routes.set("/github/user", (req, res) => {
res.writeHead(req.headers.authorization === "Bearer tok" ? 200 : 401).end(JSON.stringify({login: "someone"}));
});
});
afterAll(async () => {
globalThis.fetch = realFetch;
console.error = realConsoleError;
if (originalXdgConfigHome === undefined) delete env.XDG_CONFIG_HOME;
else env.XDG_CONFIG_HOME = originalXdgConfigHome;
await Promise.all([rm(testDir, {recursive: true}), new Promise(resolve => mockServer.close(resolve))]);
});
async function runCliExec(argv: Array<string>): Promise<Record<string, any>> {
const {args, positionals} = parseCliArgs(argv);
const output = await updates({...await resolveConfig(args, positionals), noCache: true});
return {...(output.message ? {message: output.message} : {results: output.results}), ...(output.errors?.length && {errors: output.errors})};
}
async function captureCli(argv: Array<string>, stdin?: Readable, moduleUrl = pathToFileURL(sourceScript).href) {
let stdout = "";
let stderr = "";
const exitCode = await cliStderr.run(text => { stderr += text; }, () =>
runCli(argv, {stdout: text => { stdout += text; }, stdoutIsTTY: false, stdin, moduleUrl}, false));
return {stdout, stderr, exitCode};
}
type Row = [mode: string, type: string, name: string, dependency: Record<string, string>];
const dep = (info: string, newVersion: string, old: string) => ({info, new: newVersion, old});
function dependencyRows(results: Record<string, Record<string, Record<string, Record<string, string>>>>): Array<Row> {
const key = ([mode, type, name]: Row) => `${mode}\0${type}\0${name}`;
return Object.entries(results).flatMap(([mode, types]) => Object.entries(types).flatMap(([type, dependencies]) =>
Object.entries(dependencies).map(([name, {age: _age, ...dependency}]): Row => [mode, type, name, dependency])))
.sort((left, right) => key(left) < key(right) ? -1 : 1);
}
async function makeTest(args: string) {
const argv = args.split(" ");
const {results} = await runCliExec([...argv, "-c", ...apiArgs, ...(argv.includes("-f") ? [] : ["-f", join(testDir, "package.json")])]);
return results && dependencyRows(results);
}
function writeTree(name: string, files: Record<string, string>) {
const dir = mkdtempSync(join(testDir, `${name}-`));
for (const [path, content] of Object.entries(files)) {
mkdirSync(dirname(join(dir, path)), {recursive: true});
writeFileSync(join(dir, path), content);
}
return dir;
}
function copyFixture(name: string) {
const dir = mkdtempSync(join(testDir, `${name}-`));
cpSync(fixture(name), dir, {recursive: true});
return dir;
}
sequential("login verifies and stores tokens, logout removes them", {concurrent: false}, async () => {
const path = join(env.XDG_CONFIG_HOME!, "updates", "tokens.json");
const login = (token: string) => captureCli(["--login", "github.com", "--forgeapi", githubUrl], Readable.from([`${token}\n`]));
expect(await login("bad")).toEqual({stdout: "token for github.com was rejected\n", stderr: "", exitCode: 1});
expect(existsSync(path)).toBe(false);
expect(await login("tok")).toEqual({stdout: "stored token for github.com (someone)\n", stderr: "", exitCode: 0});
expect(JSON.parse(read(path))).toEqual({"github.com": "tok"});
expect(statSync(path).mode & 0o777).toBe(platform === "win32" ? 0o666 : 0o600);
expect(await captureCli(["--logout", "github.com"])).toEqual({stdout: "removed token for github.com\n", stderr: "", exitCode: 0});
expect(await captureCli(["--logout", "github.com"])).toEqual({stdout: "no stored token for github.com\n", stderr: "", exitCode: 1});
});
test("text output lists every dep, one row per version across sections", async () => {
const {stdout, stderr} = await captureCli(["-n", ...apiArgs, "-f", testFile]);
expect(stderr).toEqual("");
expect(stdout).toContain("prismjs");
expect(stdout).toContain("https://github.com/silverwind/updates");
expect(stdout.split("\n").filter(line => line.includes("@babel/preset-env"))).toHaveLength(3);
expect(stdout).toContain("~6.0.0 || ~7.11.5");
});
test("version info fallback", async () => {
const {noty} = (await runCliExec(["-j", "-n", ...apiArgs, "-f", testFile, "-i", "noty"])).results.npm.dependencies;
expect(noty.new).toBe("3.1.4");
expect(noty.age).toBeTruthy();
});
test("version resolves the source and built package layouts", async () => {
const dir = writeTree("version-layouts", {
"package.json": JSON.stringify({version: "wrong"}),
"updates/package.json": JSON.stringify({version: "1.2.3", type: "module"}),
});
for (const entry of [join(dir, "updates", "index.ts"), join(dir, "updates", "dist", "index.ts")]) {
expect(await captureCli(["--version"], undefined, pathToFileURL(entry).href)).toMatchObject({stdout: "1.2.3\n", stderr: ""});
}
});
test("empty", async () => {
const {stdout, stderr} = await captureCli(["-n", ...apiArgs, "-f", emptyFile]);
expect(stderr).toEqual("");
expect(stdout).toContain("No dependencies");
});
test("npm alias resolves the aliased package, and a second run is a no-op", async () => {
const dir = writeTree("npm-alias", {
"package.json": JSON.stringify({dependencies: {
"package-matched": "npm:gulp-sourcemaps@^2.0.0",
"dep-matched": "npm:gulp-sourcemaps@^2.0.0",
"tagged": "npm:gulp-sourcemaps@latest",
}}, null, 2),
"renovate.json": JSON.stringify({packageRules: [
{matchPackageNames: ["gulp-sourcemaps"], allowedVersions: "<=2.5.2"},
{matchDepNames: ["dep-matched"], allowedVersions: "<=2.4.1"},
]}),
});
const run = () => updates({files: [join(dir, "package.json")], registry: npmUrl, update: true, color: false, noCache: true,
cooldown: "999999d", overrides: [{include: ["gulp-sourcemaps"], cooldown: 0}]});
const {dependencies} = (await run()).results.npm;
expect(dependencies["package-matched"]).toMatchObject({old: "npm:gulp-sourcemaps@^2.0.0", new: "npm:gulp-sourcemaps@^2.5.2"});
expect(dependencies["dep-matched"]).toMatchObject({old: "npm:gulp-sourcemaps@^2.0.0", new: "npm:gulp-sourcemaps@^2.4.1"});
expect(dependencies.tagged).toBeUndefined();
const written = read(dir, "package.json");
expect(JSON.parse(written).dependencies).toMatchObject({
"package-matched": "npm:gulp-sourcemaps@^2.5.2",
"dep-matched": "npm:gulp-sourcemaps@^2.4.1",
});
await run();
expect(read(dir, "package.json")).toBe(written);
});
test.each([
["@std/semver", "npm:@jsr/std__semver@^0.224.0"],
["@std/semver", "jsr:^0.224.0"],
["semver", "npm:@jsr/std__semver@^0.224.0"],
])("JSR %s at %s keeps its range operator", async (name, value) => {
const file = join(writeTree("jsr-range", {"package.json": JSON.stringify({dependencies: {[name]: value}})}), "package.json");
expect((await updates(apiOpts({files: [file], exclude: ["@std/semver"]}))).results).toEqual({});
const output = await updates(apiOpts({files: [file], update: true}));
expect(output.errors).toBeUndefined();
expect(output.results.npm.dependencies[name]).toMatchObject({old: "^0.224.0", new: "^1.0.8"});
expect(JSON.parse(read(file)).dependencies[name]).toBe(value.replace("^0.224.0", "^1.0.8"));
});
test("piped output stays colored with -c, on stdout and on -V stderr, and parseable with -u -j", async () => {
const pkgPath = join(writeTree("stdout-flags", {"package.json": JSON.stringify({dependencies: {prismjs: "1.0.0"}})}), "package.json");
const {stdout: colored, stderr: verbose} = await captureCli(["-c", "-V", ...apiArgs, "-f", pkgPath]);
expect(colored).toContain("\u001b[");
expect(verbose).toContain("\u001b[");
const {stdout: json} = await captureCli(["-u", "-j", ...apiArgs, "-f", pkgPath]);
expect(JSON.parse(json).results.npm.dependencies.prismjs.new).toBe("1.17.1");
});
test("npm override paths printing alike share a row", async () => {
const file = join(writeTree("override-labels", {"package.json": JSON.stringify({overrides: {"a.b": {prismjs: "1.0.0"}, a: {b: {prismjs: "1.0.0"}}}})}),
"package.json");
expect(Object.keys((await updates(apiOpts({files: [file]}))).results.npm.overrides)).toEqual(["prismjs:overrides.a.b.prismjs"]);
});
test.skipIf(Boolean(versions.bun))("global", async () => {
const bin = join(testDir, "global", ...(platform === "win32" ? ["updates.cmd"] : ["bin", "updates"]));
mkdirSync(dirname(bin), {recursive: true});
if (platform === "win32") writeFileSync(bin, `@node "${script}" %*\r\n`);
else symlinkSync(script, bin);
const {stdout, stderr} = await execFileAsync(bin, ["-n", ...apiArgs, "-f", testFile], {shell: platform === "win32"});
expect(stderr).toEqual("");
expect(stdout).toContain("prismjs");
expect(stdout).toContain("https://github.com/silverwind/updates");
});
const latestRows: Array<Row> = [
["npm", "dependencies", "@babel/preset-env", dep("https://github.com/babel/babel/tree/HEAD/packages/babel-preset-env", "7.11.5", "7.0.0")],
["npm", "dependencies", "eslint-plugin-storybook", dep("https://github.com/storybookjs/storybook/tree/HEAD/code/lib/eslint-plugin", "10.0.0-beta.6", "10.0.0-beta.5")],
["npm", "dependencies", "gulp-sourcemaps", dep("https://github.com/gulp-sourcemaps/gulp-sourcemaps", "2.6.5", "2.0.0")],
["npm", "dependencies", "html-webpack-plugin", dep("https://github.com/jantimon/html-webpack-plugin", "4.0.0-beta.11", "4.0.0-alpha.2")],
["npm", "dependencies", "jpeg-buffer-orientation", dep("https://github.com/fisker/jpeg-buffer-orientation", "2.0.3", "0.0.0")],
["npm", "dependencies", "noty", dep("https://github.com/needim/noty", "3.1.4", "3.1.0")],
["npm", "dependencies", "prismjs", dep("https://github.com/LeaVerou/prism", "1.17.1", "1.0.0")],
["npm", "dependencies", "react", dep("https://github.com/facebook/react/tree/HEAD/packages/react", "18.2", "18.0")],
["npm", "dependencies", "styled-components", dep("https://github.com/styled-components/styled-components", "4.4.1", "2.5.0-1")],
["npm", "dependencies", "updates", dep("https://github.com/silverwind/updates", "537ccb7", "6941e05")],
["npm", "overrides", "noty", dep("https://github.com/needim/noty", "3.1.4", "3.1.0")],
["npm", "overrides", "prismjs:overrides.@babel/preset-env.prismjs", dep("https://github.com/LeaVerou/prism", "1.17.1", "1.0.0")],
["npm", "overrides", "prismjs:overrides.prismjs", dep("https://github.com/LeaVerou/prism", "1.17.1", "1.0.0")],
["npm", "packageManager", "npm", dep("https://github.com/npm/cli", "11.6.2", "11.6.0")],
["npm", "peerDependencies", "@babel/preset-env", dep("https://github.com/babel/babel/tree/HEAD/packages/babel-preset-env", "~6.0.0 || ~7.11.5", "~6.0.0")],
["npm", "peerDependencies", "typescript", dep("https://github.com/Microsoft/TypeScript", "^4 || ^5", "^4")],
["npm", "resolutions", "versions/updates", dep("https://github.com/silverwind/updates", "^10.0.0", "^1.0.0")],
];
const prereleaseRows: Array<Row> = [
["npm", "dependencies", "@babel/preset-env", dep("https://github.com/babel/babel/tree/HEAD/packages/babel-preset-env", "7.11.5", "7.0.0")],
["npm", "dependencies", "eslint-plugin-storybook", dep("https://github.com/storybookjs/storybook/tree/HEAD/code/lib/eslint-plugin", "10.0.0-beta.6", "10.0.0-beta.5")],
["npm", "dependencies", "gulp-sourcemaps", dep("https://github.com/gulp-sourcemaps/gulp-sourcemaps", "2.6.5", "2.0.0")],
["npm", "dependencies", "html-webpack-plugin", dep("https://github.com/jantimon/html-webpack-plugin", "4.0.0-beta.11", "4.0.0-alpha.2")],
["npm", "dependencies", "jpeg-buffer-orientation", dep("https://github.com/fisker/jpeg-buffer-orientation", "2.0.3", "0.0.0")],
["npm", "dependencies", "noty", dep("https://github.com/needim/noty", "3.2.0-beta", "3.1.0")],
["npm", "dependencies", "prismjs", dep("https://github.com/LeaVerou/prism", "1.17.1", "1.0.0")],
["npm", "dependencies", "react", dep("https://github.com/facebook/react/tree/HEAD/packages/react", "18.3.0-next-fecc288b7-20221025", "18.0")],
["npm", "dependencies", "styled-components", dep("https://github.com/styled-components/styled-components", "5.0.0-regexrehydrate", "2.5.0-1")],
["npm", "dependencies", "updates", dep("https://github.com/silverwind/updates", "537ccb7", "6941e05")],
["npm", "overrides", "noty", dep("https://github.com/needim/noty", "3.2.0-beta", "3.1.0")],
["npm", "overrides", "prismjs:overrides.@babel/preset-env.prismjs", dep("https://github.com/LeaVerou/prism", "1.17.1", "1.0.0")],
["npm", "overrides", "prismjs:overrides.prismjs", dep("https://github.com/LeaVerou/prism", "1.17.1", "1.0.0")],
["npm", "packageManager", "npm", dep("https://github.com/npm/cli", "11.6.2", "11.6.0")],
["npm", "peerDependencies", "@babel/preset-env", dep("https://github.com/babel/babel/tree/HEAD/packages/babel-preset-env", "~6.0.0 || ~7.11.5", "~6.0.0")],
["npm", "peerDependencies", "noty", dep("https://github.com/needim/noty", ">= 3.1 || >= 3.2.0-beta", ">= 3.1")],
["npm", "peerDependencies", "svgstore", dep("https://github.com/svgstore/svgstore", "^1.0.0 || ^2.0.0 || ^3.0.0-2", "^1.0.0 || ^2.0.0")],
["npm", "peerDependencies", "typescript", dep("https://github.com/Microsoft/TypeScript", "^4 || ^5.5.0-dev.20240601", "^4")],
["npm", "resolutions", "versions/updates", dep("https://github.com/silverwind/updates", "^10.0.0", "^1.0.0")],
];
const pick = (rows: Array<Row>, ...names: Array<string>) => rows.filter(row => names.includes(row[2]));
const goRows: Array<Row> = [
["go", "deps", "github.com/example/listonly", dep("https://github.com/example/listonly", "1.2.0", "1.0.0")],
["go", "deps", "github.com/example/listtime", dep("https://github.com/example/listtime", "1.1.0", "1.0.0")],
["go", "deps", "github.com/google/go-github/v70", dep("https://github.com/google/go-github", "82.0.0", "70.0.0")],
["go", "deps", "github.com/google/uuid", dep("https://github.com/google/uuid", "2.0.0-2026021", "1.5.0")],
];
const goPrereleaseRows: Array<Row> = [["go", "deps", "github.com/example/prerelpkg", dep("https://github.com/example/prerelpkg", "1.1.0-rc.1", "1.0.0")]];
test.each([
["latest", "-j", latestRows],
["prerelease", "-j -g -p", prereleaseRows],
["release", "-j -R", latestRows.filter(row => !["eslint-plugin-storybook", "html-webpack-plugin"].includes(row[2]))],
["release with allow-downgrade", "-j -R -d -i eslint-plugin-storybook", [
["npm", "dependencies", "eslint-plugin-storybook", dep("https://github.com/storybookjs/storybook/tree/HEAD/code/lib/eslint-plugin", "9.1.7", "10.0.0-beta.5")],
]],
["patch", "-j -P", [
["npm", "dependencies", "eslint-plugin-storybook", dep("https://github.com/storybookjs/storybook/tree/HEAD/code/lib/eslint-plugin", "10.0.0-beta.6", "10.0.0-beta.5")],
["npm", "dependencies", "gulp-sourcemaps", dep("https://github.com/floridoo/gulp-sourcemaps", "2.0.1", "2.0.0")],
["npm", "dependencies", "html-webpack-plugin", dep("https://github.com/jantimon/html-webpack-plugin", "4.0.0-beta.11", "4.0.0-alpha.2")],
["npm", "dependencies", "noty", dep("https://github.com/needim/noty", "3.1.4", "3.1.0")],
["npm", "dependencies", "updates", dep("https://github.com/silverwind/updates", "537ccb7", "6941e05")],
["npm", "overrides", "noty", dep("https://github.com/needim/noty", "3.1.4", "3.1.0")],
["npm", "packageManager", "npm", dep("https://github.com/npm/cli", "11.6.2", "11.6.0")],
["npm", "resolutions", "versions/updates", dep("https://github.com/silverwind/updates", "^1.0.6", "^1.0.0")],
]],
["include", "-j -i noty", pick(latestRows, "noty")],
["include regex", "-j -i /^noty/", pick(latestRows, "noty")],
["cooldown duration", "-j -i noty -C 12h", pick(latestRows, "noty")],
["packageManager", "-j -i npm", pick(latestRows, "npm")],
["overrides type", "-j -t overrides", latestRows.filter(row => row[1] === "overrides")],
["exclude and regex include select only matching packages", "-j -e gulp-sourcemaps -i /react/", pick(latestRows, "react")],
["glob include selects matching packages", "-j -i gulp*", pick(latestRows, "gulp-sourcemaps")],
["regex include and glob patch select matching packages", "-j -i /^gulp/ -P gulp*", [
["npm", "dependencies", "gulp-sourcemaps", dep("https://github.com/floridoo/gulp-sourcemaps", "2.0.1", "2.0.0")],
]],
["prerelease selection", "-j -i noty -p", pick(prereleaseRows, "noty")],
["a /regex/ greatest value applies to the packages it matches alone", "-j -i gulp-sourcemaps,noty -g /^gulp/", pick(latestRows, "gulp-sourcemaps", "noty")],
["a /regex/ prerelease value applies to the packages it matches alone", "-j -i gulp-sourcemaps,noty -p /^noty/", pick(prereleaseRows, "gulp-sourcemaps", "noty")],
["repeated multi-value flag survives swallowed flag recovery", "-j -i react -i -p", pick(prereleaseRows, "react")],
["repeated multi-value flag survives swallowed flag recovery when not last", "-j -i react -i -p -i gulp-sourcemaps", pick(prereleaseRows, "react", "gulp-sourcemaps")],
["jsr", `-j -f ${fixture("npm-jsr/package.json")}`, [
["npm", "dependencies", "@std/semver", dep("", "1.0.8", "1.0.5")],
["npm", "devDependencies", "@std/path", dep("", "1.0.8", "1.0.0")],
]],
["uv", `-j -f ${uvFile}`, [
["pypi", "dependency-groups.dev", "PyYAML", dep("https://github.com/yaml/pyyaml", "6.0", "1.0")],
["pypi", "dependency-groups.dev", "types-requests", dep("https://github.com/python/typeshed", "2.32.4.20250611", "2.32.0.20240622")],
["pypi", "project.dependencies", "djlint", dep("https://github.com/Riverside-Healthcare/djlint", "1.31.0", "1.30.0")],
["pypi", "project.dependencies", "ty", dep("https://github.com/astral-sh/ty", "0.0.1a19", "0.0.1a15")],
]],
["cargo", `-j -f ${fixture("cargo/Cargo.toml")}`, [
["cargo", "dependencies", "tokio", dep("https://crates.io/crates/tokio", "1.35", "1.0")],
["cargo", "dev-dependencies", "rand", dep("https://crates.io/crates/rand", "0.9", "0.8")],
["cargo", "target.cfg(unix).dependencies", "rand", dep("https://crates.io/crates/rand", "0.9", "0.8")],
]],
["go", `-j -f ${goFile}`, goRows],
["go indirect", `-j -f ${goFile} -I`, [
...goRows,
["go", "indirect", "github.com/example/testpkg", dep("https://github.com/example/testpkg", "2.0.0", "0.9.0")],
]],
["go prerelease is excluded by default", `-j -f ${goPreFile}`, undefined],
["go prerelease is enabled globally", `-j -f ${goPreFile} -p`, goPrereleaseRows],
["go prerelease is enabled per package", `-j -f ${goPreFile} -p github.com/example/prerelpkg`, goPrereleaseRows],
["go pseudo-version no downgrade", `-j -f ${fixture("go-pseudo/go.mod")}`, undefined],
])("%s", async (_name, args, expected) => {
expect(await makeTest(args)).toEqual(expected);
});
test("invalid config", async () => {
const {stdout, exitCode} = await captureCli(["-j", "-f", fixture("invalid-config/package.json"), "-c", ...apiArgs]);
expect(exitCode).toBe(1);
expect(stdout).toContain("updates.config.js");
expect(stdout).toContain("Unable to parse");
});
test("go @v/list fallback takes a date off the list line when .info is absent", async () => {
const {results} = await runCliExec(["-j", "-f", goFile, "-c", "--goproxy", goProxyUrl]);
expect(results.go.deps["github.com/example/listtime"].age).toBeTruthy();
});
test("a fractional timeout does not throw a non-integer AbortSignal delay, a negative one is rejected on the cli and through the api", async () => {
const {results} = await updates({files: [goFile], goproxy: goProxyUrl, timeout: 9999.4, color: false, noCache: true});
expect(results?.go?.deps).toBeTruthy();
expect((await rejection(runCliExec(["-T", "-5", ...apiArgs, "-f", testFile])))?.message).toMatch(/timeout/i);
expect((await rejection(updates({files: [goFile], goproxy: goProxyUrl, timeout: -1, color: false, noCache: true})))?.message).toMatch(/invalid timeout/i);
});
test.each([
[["-N", "a/**,{b,c}/**", "-X", "d/**"], {includePaths: ["a/**", "{b,c}/**"], excludePaths: ["d/**"]}],
[["-n"], {color: false, noColor: true}],
[["-c"], {color: true, noColor: false}],
[["-c", "-n"], {color: false, noColor: true}],
])("cli flags %s reach the config", async (argv, expected) => {
const {args, positionals} = parseCliArgs(argv);
expect(await resolveConfig(args, positionals)).toMatchObject(expected);
});
test("an = joined value is not taken for a flag", () => {
expect(parseCliArgs(["-i", "noty", "--exclude=-u"]).args).toEqual({include: ["noty"], exclude: ["-u"]});
});
test("go update", async () => {
const dir = copyFixture("go-update");
await runCliExec(["-u", "-f", join(dir, "go.mod"), "-c", "--goproxy", goProxyUrl]);
const goMod = read(dir, "go.mod");
expect(goMod.match(/github\.com\/google\/uuid\/v2 v2\.0\.0-20260217135312-8c5a7de9ffa1/g)).toHaveLength(4);
expect(goMod).not.toContain("uuid v1.5.0");
expect(goMod).not.toContain("go-github/v70");
expect(goMod).toMatch(/github\.com\/google\/go-github\/v\d+ v\d+\.\d+\.\d+/);
const main = read(dir, "main.go");
expect(main).not.toContain("go-github/v70");
expect(main).toMatch(/go-github\/v\d+\/github/);
});
test("go update v1 to v2", async () => {
const dir = copyFixture("go-update-v2");
await runCliExec(["-u", "-f", join(dir, "go.mod"), "-c", "--goproxy", goProxyUrl]);
const goMod = read(dir, "go.mod");
expect(goMod).toContain("github.com/example/testpkg/v2 v2.0.0");
expect(goMod).not.toContain("testpkg v1.0.0");
const main = read(dir, "main.go");
expect(main).toContain(`"github.com/example/testpkg/v2"`);
expect(main).toContain(`"github.com/example/testpkg/v2/sub"`);
expect(main).not.toMatch(/"github\.com\/example\/testpkg"(?!\/v2)/);
});
test("go pseudo-version update rewrites the full version", async () => {
const modPath = join(copyFixture("go-pseudo-update"), "go.mod");
await updates({files: [modPath], goproxy: goProxyUrl, update: true, indirect: true, color: false, noCache: true});
const updated = read(modPath);
expect(updated).toContain("github.com/example/pseudoupd v1.5.0");
expect(updated).not.toContain("20221128193559");
expect(updated).not.toContain("754e69321358");
});
test("go mode bumps Makefile go install versions and rewrites paths on major bumps, printing full specs when only the path moves, keeping its annotated lines", async () => {
lazyRoute("/go/github.com/example/tool/@latest", () => ({Version: "v2.0.0+incompatible"}));
lazyRoute("/go/github.com/example/tool/v2/@latest", () => ({Version: "v2.1.0"}));
const dir = writeTree("make", {Makefile: lines(
"UUID_PACKAGE ?= github.com/google/uuid@v1.4.0",
"TESTPKG_PACKAGE := github.com/example/testpkg@v1.0.0 # renovate: datasource=go",
"TOOL := github.com/example/tool/cmd/tool@v2",
"# DISABLED := github.com/example/testpkg@v0.5.0",
"SOURCE := $(wildcard *.go)",
)});
const {results} = await updates({files: [join(dir, "Makefile")], goproxy: goProxyUrl, update: true, color: false, noCache: true});
expect(Object.values(results.go)[0]).toMatchObject({
"github.com/example/testpkg": {old: "v1.0.0", new: "v2.0.0"},
"github.com/example/tool/cmd/tool": {old: "github.com/example/tool/cmd/tool@v2", new: "github.com/example/tool/v2/cmd/tool@v2"},
});
expect(Object.keys(results)).toEqual(["go"]);
expect(read(dir, "Makefile")).toBe(lines(
"UUID_PACKAGE ?= github.com/google/uuid/v2@v2.0.0-20260217135312-8c5a7de9ffa1",
"TESTPKG_PACKAGE := github.com/example/testpkg/v2@v2.0.0 # renovate: datasource=go",
"TOOL := github.com/example/tool/v2/cmd/tool@v2",
"# DISABLED := github.com/example/testpkg@v0.5.0",
"SOURCE := $(wildcard *.go)",
));
});
test("auto-discovery finds a Makefile once on a case-insensitive filesystem", async () => {
const dir = writeTree("make-discovery", {Makefile: "UUID_PACKAGE ?= github.com/google/uuid@v1.4.0\n"});
const {results} = await runCliExec(["-j", "-x", "-M", "go", ...apiArgs, "-f", dir]);
expect(Object.keys(results.go).map(file => basename(file))).toEqual(["Makefile"]);
});
test("auto-discovery finds tracked and untracked files at any depth, skipping gitignored ones unless passed and excluded paths", async () => {
const makefile = "UUID_PACKAGE ?= github.com/google/uuid@v1.4.0\n";
const dir = realpathSync.native(writeTree("discovery", {
"Makefile": makefile, "tools/tools.mk": makefile, "deep/er/Makefile": makefile, "node_modules/pkg/Makefile": makefile,
"untracked/Makefile": makefile, "gitignored/Makefile": makefile, "svc/app.Dockerfile": "FROM node:18\n", ".gitignore": "gitignored/\n",
}));
await execFileAsync("git", ["init", "-q"], {cwd: dir});
await execFileAsync("git", ["add", ".", ":!untracked"], {cwd: dir});
const discovered = async (options: UpdatesOptions) => Object.values((await updates(apiOpts({files: [dir], modes: ["go", "docker"], ...options}))).results)
.flatMap(Object.keys).map(file => relative(dir, file).replaceAll("\\", "/")).sort();
expect(await discovered({})).toEqual(["Makefile", "deep/er/Makefile", "svc/app.Dockerfile", "tools/tools.mk", "untracked/Makefile"]);
expect(await discovered({excludePaths: ["deep/**"]})).toEqual([
"Makefile", "node_modules/pkg/Makefile", "svc/app.Dockerfile", "tools/tools.mk", "untracked/Makefile",
]);
expect(await discovered({includePaths: ["tools/**"]})).toEqual(["tools/tools.mk"]);
expect(await discovered({files: [join(dir, "gitignored")]})).toEqual(["gitignored/Makefile"]);
expect(await discovered({files: [join(dir, "gitignored/Makefile")]})).toEqual(["gitignored/Makefile"]);
});
test("docker mode bumps image tags and re-resolves digests in Makefiles", async () => {
const dir = writeTree("make-docker", {Makefile: lines(
`SHELLCHECK_IMAGE ?= docker.io/koalaman/shellcheck:v0.11.0@sha256:${"a".repeat(64)} # renovate: datasource=docker`,
"PLAIN := koalaman/shellcheck:v0.11.0",
"TEST_MYSQL_HOST ?= mysql:3306",
)});
await updates({files: [join(dir, "Makefile")], dockerapi: dockerUrl, update: true, color: false, noCache: true});
expect(read(dir, "Makefile")).toBe(lines(
"SHELLCHECK_IMAGE ?= docker.io/koalaman/shellcheck:v0.12.0@sha256:list-new # renovate: datasource=docker",
"PLAIN := koalaman/shellcheck:v0.12.0",
"TEST_MYSQL_HOST ?= mysql:3306",
));
});
test("docker mode bumps a shell script *_IMAGE image and its digest on another registry after its token challenge, under cooldown dated by image metadata, but not a plain variable", async () => {
const registry = mockUrl.replace("http://", "");
const [oldDigest, newDigest] = [`sha256:${"a".repeat(64)}`, `sha256:${"b".repeat(64)}`];
const challenge = {"www-authenticate": `Bearer realm="${mockUrl}/registry-token",service="test"`};
const authorized = (req: IncomingMessage) => req.headers.authorization === "Bearer pull-token";
const registryRoute = (path: string, respond: (req: IncomingMessage, res: any) => void) => routes.set(`/v2/o/tool/${path}`, (req, res) => {
if (authorized(req)) respond(req, res);
else res.writeHead(401, challenge).end();
});
const json = (body: unknown) => (_req: IncomingMessage, res: any) => { res.end(JSON.stringify(body)); };
routes.set("/registry-token", (_req, res) => { res.end(JSON.stringify({token: "pull-token"})); });
registryRoute("tags/list", json({tags: ["1.0.0", "1.1.0", "1.2.0", "latest"]}));
registryRoute("manifests/1.2.0", json({annotations: {"org.opencontainers.image.created": new Date().toISOString()}}));
registryRoute("manifests/1.1.0", (req, res) => {
if (req.method === "HEAD") res.writeHead(200, {"docker-content-digest": newDigest}).end();
else res.end(JSON.stringify({manifests: [{platform: {os: "unknown"}, digest: "sha256:attestation"}, {platform: {os: "linux"}, digest: "sha256:image"}]}));
});
registryRoute("manifests/sha256:image", json({config: {digest: "sha256:config"}}));
registryRoute("blobs/sha256:config", json({created: "2024-01-01T00:00:00Z"}));
const dir = writeTree("registry-image", {"build.sh": lines(`TOOL_IMAGE="${registry}/o/tool:1.0.0@${oldDigest}"`, `MIRROR=${registry}/o/tool:1.0.0`)});
await updates({files: [join(dir, "build.sh")], modes: ["docker"], update: true, color: false, noCache: true, cooldown: "3d"});
expect(read(dir, "build.sh")).toBe(lines(`TOOL_IMAGE="${registry}/o/tool:1.1.0@${newDigest}"`, `MIRROR=${registry}/o/tool:1.0.0`));
});
test("go and docker modes bump discovered Makefiles and shell scripts alike, leaving current, unresolvable, excluded and failed values untouched", async () => {
const digest = `sha256:${"a".repeat(64)}`;
const tools = [
"github.com/example/testpkg/v2@v2.0.0", "github.com/example/pseudoupd@v1", "github.com/example/missing@v1.0.0",
"github.com/example/excluded@v1.0.0",
].join(" ");
const images = `example/makeallowed:1.0@${digest} example/broken:1.0`;
const dir = writeTree("shell", {
"Makefile": lines("TOOL ?= github.com/example/testpkg@v1.0.0", "IMAGE := example/image:1.0"),
"build.sh": lines(
`TOOL="\${TOOL:-github.com/example/testpkg@v1.0.0}"`,
"export IMAGE=example/image:1.0",
`TOOLS=(github.com/example/testpkg@v1.0.0 ${tools})`,
`IMAGES=(example/image:1.0 ${images})`,
),
"noop.sh": "echo done\n",
});
const {results, errors} = await updates({
files: [dir], modes: ["go", "docker"], exclude: ["github.com/example/excluded"], goproxy: goProxyUrl, dockerapi: dockerUrl,
update: true, color: false, noCache: true,
});
expect(Object.fromEntries(Object.entries(results).map(([mode, files]) => [mode, Object.keys(files).map(file => basename(file)).sort()])))
.toEqual({go: ["Makefile", "build.sh"], docker: ["Makefile", "build.sh"]});
expect(Object.values(results.go).flatMap(Object.keys)).not.toContain("github.com/example/pseudoupd");
expect(errors!.map(({mode, name}) => [mode, name])).toEqual([["docker", "example/broken"]]);
expect(read(dir, "Makefile")).toBe(lines("TOOL ?= github.com/example/testpkg/v2@v2.0.0", "IMAGE := example/image:1.1"));
expect(read(dir, "build.sh")).toBe(lines(
`TOOL="\${TOOL:-github.com/example/testpkg/v2@v2.0.0}"`,
"export IMAGE=example/image:1.1",
`TOOLS=(github.com/example/testpkg/v2@v2.0.0 ${tools})`,
`IMAGES=(example/image:1.1 ${images})`,
));
});
test("Makefile allowedVersions falls back to the highest allowed candidate", async () => {
const dir = writeTree("make-allowed", {
"Makefile": lines("TOOL := github.com/example/makeallowed/cmd/tool@v1.0.0", "IMAGE := example/makeallowed:1.0"),
"renovate.json": JSON.stringify({packageRules: [
{matchPackageNames: ["github.com/example/makeallowed/cmd/tool"], allowedVersions: "<2"},
{matchPackageNames: ["example/makeallowed"], allowedVersions: "<2"},
]}),
});
await updates({files: [join(dir, "Makefile")], goproxy: goProxyUrl, dockerapi: dockerUrl, update: true, color: false, noCache: true});
expect(read(dir, "Makefile")).toBe(lines("TOOL := github.com/example/makeallowed/cmd/tool@v1.1.0", "IMAGE := example/makeallowed:1.1"));
});
test("annotations respect native ownership, lookup identity, versioning, cooldowns and write validation across datasource modes", async () => {
const digest = `sha256:${"a".repeat(64)}`;
const release = (tag: string, prerelease = false) => ({tag_name: tag, prerelease});
lazyRoute("/github/repos/o/annotated/releases", () => [release("v3-init"), release("v2.0.0-rc.1", true), release("v1.8.0")]);
lazyRoute("/forgejo/api/v1/repos/o/annotated/releases", () => [release("v9.0.0$(id)"), release("v1.8.0")]);
lazyRoute("/npm/annotated-newline", () => ({name: "annotated-newline", "dist-tags": {latest: "2.0.0\n"}, versions: {"1.0.0": {}, "2.0.0\n": {}}}));
const input = {
".github/workflows/ci.yml": lines(
"env:",
" PRISM_VERSION: 1.15.0 # renovate: datasource=npm depName=prismjs",
` TEST_IMAGE: koalaman/shellcheck:v0.11.0@${digest} # renovate: datasource=docker`,
" GH_VERSION: 1.7.0 # renovate: datasource=github-releases depName=o/annotated extractVersion=^v(?<version>.+)$",
" RNA_VERSION: v1.7.3 # updates: datasource=forgejo-releases depName=o/annotated registryUrl=https://code.forgejo.org",
"jobs:",
" test:",
" container:",
" image: koalaman/shellcheck:v0.11.0 # renovate: datasource=docker",
),
"Makefile": lines(
"SHELLCHECK_IMAGE := koalaman/shellcheck:v0.11.0",
"# renovate: datasource=docker depName=koalaman/shellcheck",
"SHELLCHECK_VERSION := v0.11.0",
"# renovate: datasource=go packageName=github.com/example/testpkg/cmd/tool",
"TESTPKG_VERSION := v0.9.0",
),
"versions.env": lines(
"# renovate: datasource=crate lookupName=tokio",
"TOKIO_VERSION=1.30.0",
"PRISM_VERSION=1.15.0 # renovate: datasource=npm depName=prismjs allowedVersions=<1.16",
"HTTP_VERSION=1.7.0 # updates: datasource=github-releases depName=o/annotated registryUrl=http://github.com",
"SHORT_VERSION=v1.7 # renovate: datasource=github-releases depName=o/annotated",
"TYPES_VERSION=2.32 # renovate: datasource=pypi depName=types-requests",
"NEWLINE_VERSION=1.0.0 # renovate: datasource=npm depName=annotated-newline",
"MISSING_VERSION=1.0.0 # renovate: datasource=github-releases depName=o/missing",
"SUFFIXED_VERSION=1.0.0-alpine # updates: datasource=github-tags depName=o/annotated versioning=docker",
),
};
const dir = writeTree("annotations", input);
const run = (options: UpdatesOptions) => updates({...apiUrls, files: [dir, join(dir, "versions.env")], noCache: true, color: false, ...options});
expect(Object.keys((await run({modes: ["cargo"]})).results)).toEqual(["cargo"]);
const {results, errors} = await run({update: true});
expect(Object.fromEntries(errors!.map(({mode, name, error}) => [name, [mode, error]]))).toEqual({
"annotated-newline": ["npm", "Refusing to write \"2.0.0\\n\""], "o/missing": ["actions", "No releases found for o/missing"],
});
expect(Object.fromEntries(Object.entries(results).map(([mode, files]) =>
[mode, Object.values(files).flatMap(Object.keys).sort()]))).toEqual({
actions: ["o/annotated", "o/annotated@1.7.0", "o/annotated@v1.7.3"],
cargo: ["tokio"],
docker: ["koalaman/shellcheck:v0.11.0", "koalaman/shellcheck:v0.11.0", `koalaman/shellcheck:v0.11.0@${digest}`],
go: ["github.com/example/testpkg/cmd/tool"],
npm: ["prismjs"],
pypi: ["types-requests"],
});
expect(read(dir, ".github/workflows/ci.yml")).toBe(input[".github/workflows/ci.yml"].replace("1.15.0", "1.17.1")
.replace(`v0.11.0@${digest}`, "v0.12.0@sha256:list-new").replace("1.7.0", "1.8.0").replace("v1.7.3", "v1.8.0").replace("v0.11.0", "v0.12.0"));
expect(read(dir, "Makefile")).toBe(input.Makefile.replaceAll("v0.11.0", "v0.12.0").replace("v0.9.0", "v1.0.0"));
expect(read(dir, "versions.env")).toBe(input["versions.env"].replace("1.30.0", "1.35.0").replace("=v1.7 ", "=v1.8.0 ")
.replace("=2.32 ", "=2.32.4.20250611 "));
const dockerVersions = ["1.0", "1.1", "1.2"];
lazyRoute("/docker/v2/repositories/library/review-image/tags", () => ({count: 3,
results: dockerVersions.map(name => ({name, tag_last_pushed: "2024-01-01", digest: "sha256:new"}))}));
lazyRoute("/github/repos/o/ownership/tags", () => ["v3.0.0", "v1.0.0"].map(name => ({name, commit: {sha: ""}})));
lazyRoute("/github/repos/o/ownership/releases", () => [release("v2.0.0")]);
lazyRoute("/ipv6/v2/o/tool/tags/list", () => ({tags: ["1.0.0", "1.1.0"]}));
lazyRoute("/go/github.com/example/~tool/@latest", () => ({Version: "v1.1.0", Time: "2024-01-01"}));
const ownership = writeTree("annotation-ownership", {
".github/workflows/ci.yml": lines("jobs:", " test:", " runs-on: ubuntu-latest", " steps:",
" - uses: o/ownership@v1.0.0 # renovate: datasource=github-releases depName=o/ownership",
" container: review-image:1.0",
"env:", " VERSION: 1.0 # updates: datasource=docker depName=review-image"),
"Dockerfile": lines("ARG UNUSED=1.0 # renovate: datasource=docker depName=review-image",
"ARG USED=1.0 # updates: datasource=docker depName=alias", "ARG NESTED=1.0 # updates: datasource=docker depName=review-image",
"ARG NESTED_IMAGE=review-image:$NESTED", "FROM review-image:$USED",
"ENV TEST_IMAGE=review-image:1.0 # updates: datasource=docker", "FROM $NESTED_IMAGE"),
"compose.yml": lines("services:", " test:", " image: review-image:1.0 # updates: datasource=docker",
" environment:", " - TEST_IMAGE=review-image:1.0 # updates: datasource=docker"),
"Makefile": lines("BASE_IMAGE := review-image:1.0", "V := review-image:1.0 # updates: datasource=docker depName=alias",
"CHECK_IMAGE := \\", " review-image:1.0 # updates: datasource=docker depName=alias",
"IPV6_IMAGE := [2001:db8::1]:5000/o/tool:1.0.0",
"TOOL := github.com/example/~tool@v1.0.0"),
"build.sh": lines("BASE_IMAGE=review-image:1.0", "V=review-image:1.0 # updates: datasource=docker depName=alias",
"IPV6_IMAGE=[2001:db8::1]:5000/o/tool:1.0.0", "TOOL=github.com/example/~tool@v1.0.0"),
"go.mod": lines("module example.com/main", "", "go 1.23", "", "require github.com/example/testpkg v1.0.0"),
"main.go": lines("package main", 'import _ "github.com/example/testpkg"; const version = "1.15.0" // updates: datasource=npm depName=prismjs'),
"digest.env": lines(`IMAGE=review-image:1.2@${digest} # updates: datasource=docker`,
"MIRROR=example/mirror:1.0 # updates: datasource=docker packageName=review-image"),
});
const owned = await updates(apiOpts({files: [ownership, join(ownership, "main.go"), join(ownership, "digest.env")],
pin: {alias: "1.1"}, update: true}));
expect(owned.errors).toBeUndefined();
expect(Object.values(owned.results.actions).flatMap(Object.values).map(({new: value}) => value)).toEqual(["3.0.0"]);
expect(read(ownership, ".github/workflows/ci.yml")).toContain("o/ownership@v3.0.0");
expect(read(ownership, ".github/workflows/ci.yml")).toContain("container: review-image:1.2");
expect(read(ownership, ".github/workflows/ci.yml")).toContain("VERSION: 1.2 # updates:");
expect(read(ownership, "Dockerfile")).toBe(lines("ARG UNUSED=1.2 # renovate: datasource=docker depName=review-image",
"ARG USED=1.2 # updates: datasource=docker depName=alias", "ARG NESTED=1.2 # updates: datasource=docker depName=review-image",
"ARG NESTED_IMAGE=review-image:$NESTED", "FROM review-image:$USED",
"ENV TEST_IMAGE=review-image:1.2 # updates: datasource=docker", "FROM $NESTED_IMAGE"));
expect(read(ownership, "compose.yml")).not.toContain("review-image:1.0");
for (const file of ["Makefile", "build.sh"]) {
expect(read(ownership, file)).toContain("review-image:1.1 # updates: datasource=docker depName=alias");
expect(read(ownership, file)).toContain(`BASE_IMAGE${file === "Makefile" ? " := " : "="}review-image:1.2`);
expect(read(ownership, file)).toContain("[2001:db8::1]:5000/o/tool:1.1.0");
expect(read(ownership, file)).toContain("github.com/example/~tool@v1.1.0");
}
expect(read(ownership, "Makefile")).toContain(" review-image:1.2 # updates: datasource=docker depName=alias");
expect(read(ownership, "main.go")).toContain('import _ "github.com/example/testpkg/v2"; const version = "1.17.1"');
expect(read(ownership, "digest.env")).toContain("MIRROR=example/mirror:1.2 # updates:");
expect(Object.values(owned.results.docker).flatMap(Object.values).find(({old}) => old.includes("@")))
.toMatchObject({old: `review-image:1.2@${digest}`, new: "review-image:1.2@sha256:new"});
for (const [name, latest] of [["review-a", "2.0.0"], ["review-b", "3.0.0"]]) {
lazyRoute(`/npm/${name}`, () => ({name, "dist-tags": {latest}, versions: {"1.0.0": {}, [latest]: {}}, time: {[latest]: "2024-01-01"}}));
lazyRoute(`/npm/${name}/${latest}`, () => ({}));
}
for (const name of ["review-foo", "review-bar", "review-epoch"]) {
const latest = name === "review-epoch" ? "1!2.0" : name === "review-foo" ? "2.0.0" : "3.0.0";
lazyRoute(`/pypi/pypi/${name}/json`, () => ({info: {name, version: latest}, releases: {[latest]: [{}]}}));
}
lazyRoute("/npm/review-pre", () => ({name: "review-pre", "dist-tags": {latest: "1.0.0"}, versions: {"1.0.0": {}, "2.0.0-rc.1": {}}}));
lazyRoute("/npm/review-pre/2.0.0-rc.1", () => ({}));
lazyRoute("/forgejo/api/v1/repos/o/identity/releases", () => [release("v2.0.0")]);
lazyRoute("/forgejo/other/api/v1/repos/o/identity/releases", () => [release("v3.0.0")]);
const identities = writeTree("annotation-identities", {
"versions.env": lines("A=1.0.0 # updates: datasource=npm depName=tool packageName=review-a",
"B=1.0.0 # updates: datasource=npm depName=tool packageName=review-b", "PRE=1.0 # updates: datasource=npm depName=review-pre",
"F=1.0.0 # updates: datasource=forgejo-releases depName=o/identity registryUrl=https://code.forgejo.org",
"G=1.0.0 # updates: datasource=forgejo-releases depName=o/identity registryUrl=https://code.forgejo.org/other",
...["review-foo", "review-bar"].flatMap(depName => ["1.0.0", "1.5.0"].map(value =>
`V=${value} # updates: datasource=pypi depName=${depName}`)),
"EPOCH=1!1.0 # updates: datasource=pypi depName=review-epoch"),
});
const distinct = await updates(apiOpts({files: [join(identities, "versions.env")],
overrides: [{include: ["review-pre"], prerelease: true}], update: true}));
expect(distinct.errors).toBeUndefined();
expect(read(identities, "versions.env")).toContain("A=2.0.0 # updates:");
expect(read(identities, "versions.env")).toContain("B=3.0.0 # updates:");
expect(read(identities, "versions.env")).toContain("PRE=2.0.0-rc.1 # updates:");
expect(read(identities, "versions.env")).toContain("F=2.0.0 # updates:");
expect(read(identities, "versions.env")).toContain("G=3.0.0 # updates:");
expect(Object.values(distinct.results.npm).flatMap(Object.values).map(({new: value}) => value).sort((left, right) => left.localeCompare(right)))
.toEqual(["2.0.0", "2.0.0-rc.1", "3.0.0"]);
expect(Object.values(distinct.results.actions).flatMap(Object.values).map(({new: value}) => value).sort((left, right) => left.localeCompare(right))).toEqual(["2.0.0", "3.0.0"]);
expect(Object.keys(Object.values(distinct.results.pypi)[0]).sort())
.toEqual(["review-bar==1.0.0", "review-bar==1.5.0", "review-epoch", "review-foo==1.0.0", "review-foo==1.5.0"]);
expect(read(identities, "versions.env")).toContain("EPOCH=1!2.0 # updates:");
const oldDate = "2024-01-01T00:00:00Z";
const recentDate = new Date().toISOString();
const commitRequests: Array<string> = [];
lazyRoute("/github/repos/o/annotation-cooldown/tags", () => ["v2.0.0", "v1.1.0", "v1.0.0"].map(name =>
({name, commit: {sha: name === "v2.0.0" ? "recent" : "old"}})));
lazyRoute("/github/repos/o/annotation-cooldown/releases", () => ["v2.0.0", "v1.1.0"].map(tag_name =>
({tag_name, prerelease: false, published_at: oldDate})));
for (const sha of ["recent", "old"]) {
routes.set(`/github/repos/o/annotation-cooldown/git/commits/${sha}`, (req, res) => {
commitRequests.push(req.url);
res.end(JSON.stringify({committer: {date: sha === "recent" ? recentDate : oldDate}}));
});
}
lazyRoute("/npm/review-cooled", () => ({name: "review-cooled", "dist-tags": {latest: "2.0.0"}, versions: {"1.0.0": {}, "2.0.0": {}},
time: {"2.0.0": oldDate}}));
lazyRoute("/npm/review-cooled/2.0.0", () => ({_npmOperationalInternal: {tmp: String(Date.now())}}));
const cooldown = writeTree("annotation-cooldown", {
".github/workflows/ci.yml": lines("jobs:", " test:", " steps:", " - uses: o/annotation-cooldown@v1.0.0"),
"one.env": "V=v1.0.0 # updates: datasource=github-tags depName=o/annotation-cooldown\n",
"two.env": "V=v1.0.0 # updates: datasource=github-tags depName=o/annotation-cooldown\nN=1.0.0 # updates: datasource=npm depName=review-cooled\n",
});
const cooled = await updates(apiOpts({files: [cooldown, join(cooldown, "one.env"), join(cooldown, "two.env")],
forgeapi: "https://api.github.com", cooldown: 7, update: true}));
expect(cooled.errors).toBeUndefined();
expect(cooled.results.npm).toBeUndefined();
expect(Object.values(cooled.results.actions).flatMap(Object.values).map(({new: value}) => value)).toEqual(["1.1.0", "1.1.0", "1.1.0"]);
expect(commitRequests.sort()).toEqual(["/github/repos/o/annotation-cooldown/git/commits/old", "/github/repos/o/annotation-cooldown/git/commits/recent"]);
routes.set("/github/repos/o/short-tags/tags", (_req, res) => {
res.setHeader("x-total-count", "1000");
res.end(JSON.stringify(Array.from({length: 100}, (_value, index) => ({name: `v1.${100 - index}.0`, commit: {sha: ""}}))));
});
const lookups = [
{name: "short-tags", datasource: "github-tags", current: "v1.1.0", expected: "v1.100.0", fields: "", options: {}},
{name: "pre-tags", datasource: "github-tags", current: "v2.0.0-rc.1", expected: "v2.0.0-rc.2", fields: "", options: {}},
{name: "pre-releases", datasource: "github-releases", current: "v2.0.0-rc.1", expected: "v2.0.0-rc.2", fields: "", options: {}},
{name: "draft", datasource: "github-releases", current: "v1.0.0", expected: "v2.0.0-rc.2", fields: "", options: {prerelease: true}},
{name: "pep-beta", datasource: "github-releases", current: "1.0b1", expected: "1.0b2", fields: "versioning=pep440", options: {}},
{name: "pep-post", datasource: "github-tags", current: "1.0", expected: "1.1.post1", fields: "versioning=pep440", options: {}},
{name: "many-releases", datasource: "github-releases", current: "v1.0.0", expected: "v1.1.0", fields: "", options: {cooldown: 7}},
{name: "mixed-tags", datasource: "github-tags", current: "v1.0.0", expected: "2.0.0", fields: "", options: {}},
];
lazyRoute("/github/repos/o/pre-tags/tags", () => ["v2.0.0-rc.2", "v2.0.0-rc.1"].map(name => ({name, commit: {sha: ""}})));
lazyRoute("/github/repos/o/mixed-tags/tags", () => ["2.0.0", "v1.0.0"].map(name => ({name, commit: {sha: ""}})));
for (const name of ["pre-tags", "pre-releases", "draft"]) {
lazyRoute(`/github/repos/o/${name}/releases`, () => [{...release("v9.0.0"), draft: true}, release("v2.0.0-rc.2", true)]);
}
lazyRoute("/github/repos/o/pep-beta/releases", () => [release("1.0b2", true)]);
lazyRoute("/github/repos/o/pep-post/tags", () => [{name: "1.1.post1", commit: {sha: ""}}]);
lazyRoute("/github/repos/o/many-releases/releases", () => [
...Array.from({length: 100}, (_value, index) => ({...release(`v2.0.${index}`), published_at: recentDate})),
{...release("v1.1.0"), published_at: oldDate},
]);
const tagRequestsBefore = requestedUrls.filter(url => url.startsWith("/github/repos/o/short-tags/tags")).length;
const target = writeTree("annotation-lookups", Object.fromEntries(lookups.map(({name, datasource, current, fields}) =>
[`${name}.env`, `V=${current} # updates: datasource=${datasource} depName=o/${name} ${fields}\n`])));
expect((await updates(apiOpts({files: lookups.map(({name}) => join(target, `${name}.env`)),
overrides: lookups.map(({name, options}) => ({include: [`o/${name}`], ...options})), update: true}))).errors).toBeUndefined();
for (const {name, expected} of lookups) expect(read(target, `${name}.env`)).toContain(`V=${expected} # updates:`);
expect(requestedUrls.filter(url => url.startsWith("/github/repos/o/short-tags/tags"))).toHaveLength(tagRequestsBefore + 1);
});
test("docker image names match with and without the docker.io prefix", async () => {
const makefile = lines("PREFIXED := docker.io/koalaman/shellcheck:v0.11.0", "PLAIN := koalaman/shellcheck:v0.11.0");
const dir = writeTree("docker-io-prefix", {Makefile: makefile});
for (const options of [{pin: {"koalaman/shellcheck": "0.11.x"}}, {exclude: ["docker.io/koalaman/shellcheck"]}]) {
await updates({files: [join(dir, "Makefile")], dockerapi: dockerUrl, update: true, color: false, noCache: true, ...options});
expect(read(dir, "Makefile")).toBe(makefile);
}
const clashDir = writeTree("docker-npm-name-clash", {"package.json": JSON.stringify({dependencies: {noty: "3.1.0"}}), "Dockerfile": "FROM noty:18\n"});
const clash = await updates({
files: [clashDir], registry: npmUrl, forgeapi: githubUrl, dockerapi: dockerUrl, color: false, noCache: true, patch: ["docker.io/library/noty"],
});
expect(clash.results.npm.dependencies.noty.new).toBe("3.1.4");
expect(clash.results.docker).toBeUndefined();
});
test("go replace reports and writes the update", async () => {
const modPath = join(copyFixture("go-replace"), "go.mod");
const {results} = await runCliExec(["-j", "-u", "-f", modPath, "-c", "--goproxy", goProxyUrl]);
expect(dependencyRows(results)).toEqual([["go", "replace", "gitea.com/gitea/act", dep("https://gitea.com/gitea/act", "0.261.7", "0.261.4")]]);
const updated = read(modPath);
expect(updated).toContain("gitea.com/gitea/act v0.261.7");
expect(updated).not.toContain("gitea.com/gitea/act v0.261.4");
expect(updated).toContain("replace");
});
test("go workspace reports and writes member updates, skipping excluded members", async () => {
const dir = copyFixture("go-workspace");
appendFileSync(join(dir, "app", "go.mod"), "require example.com/workspace/lib v1.0.0\n");
const filtered = await updates({files: [dir], excludePaths: ["lib/**"], goproxy: goProxyUrl, color: false, noCache: true});
expect(filtered.errors).toBeUndefined();
expect(filtered.results.go["deps|./lib"]).toBeUndefined();
expect(filtered.results.go["deps|./app"]["example.com/workspace/lib"]).toBeUndefined();
expect(filtered.results.go["deps|./app"]["github.com/google/uuid"].old).toBe("1.5.0");
const {results: {go}, errors} = await updates({files: [dir], goproxy: goProxyUrl, update: true, color: false, noCache: true});
expect(errors).toBeUndefined();
expect(go["deps|./app"]["github.com/google/uuid"].old).toBe("1.5.0");
expect(go["deps|./lib"]["github.com/google/uuid"].old).toBe("1.5.0");
for (const member of ["app", "lib"]) {
expect(read(dir, member, "go.mod")).toContain("github.com/google/uuid/v2 v2.0.0-20260217135312-8c5a7de9ffa1");
expect(read(dir, member, "go.mod")).not.toContain("uuid v1.5.0");
}
expect(read(dir, "app", "main.go")).toContain('"github.com/google/uuid/v2"');
});
test("cargo workspace reports and writes root and member updates", async () => {
const dir = copyFixture("cargo-workspace");
expect(Object.keys((await updates({
files: [join(dir, "crate-a", "Cargo.toml"), dir], excludePaths: ["crate-a/**", "crate-b/**"], cargoapi: cargoUrl, color: false, noCache: true,
})).results.cargo).sort()).toEqual(["dependencies|./crate-a", "workspace.dependencies"]);
const {cargo} = (await updates({files: [join(dir, "Cargo.toml")], cargoapi: cargoUrl, update: true, color: false, noCache: true})).results;
expect(cargo).toMatchObject({
"workspace.dependencies": {serde_json: {old: "1.0.100", new: "1.0.120"}},
"dependencies|./crate-a": {serde: {old: "1.0.100", new: "1.0.200"}},
"dependencies|./crate-b": {tokio: {old: "1.34.0", new: "1.35.0"}},
"dev-dependencies|./crate-b": {rand: {old: "0.8.5", new: "0.9.0"}},
});
expect(read(dir, "Cargo.toml")).toContain('serde_json = "1.0.120"');
expect(read(dir, "crate-a", "Cargo.toml")).toContain('serde = "1.0.200"');
expect(read(dir, "crate-b", "Cargo.toml")).toContain('version = "1.35.0"');
expect(read(dir, "crate-b", "Cargo.toml")).toContain('rand = "0.9.0"');
});
test("multiple Cargo workspace roots keep member config identity", async () => {
const dir = writeTree("cargo-workspaces", Object.fromEntries([["one", "<=1.0.100"], ["two", "<=1.0.200"]].flatMap(([root, allowedVersions]) => [
[`${root}/Cargo.toml`, '[workspace]\nmembers = ["crates/*"]\n'],
[`${root}/crates/app/Cargo.toml`, '[package]\nname = "app"\nversion = "0.1.0"\n\n[dependencies]\nserde = "1.0.0"\n'],
[`${root}/renovate.json`, JSON.stringify({packageRules: [{matchPackageNames: ["serde"], allowedVersions}]})],
])));
await updates({
files: [join(dir, "one", "Cargo.toml"), join(dir, "two", "Cargo.toml")], cargoapi: cargoUrl, modes: ["cargo"], update: true, color: false, noCache: true,
});
expect(read(dir, "one", "crates", "app", "Cargo.toml")).toContain('serde = "1.0.100"');
expect(read(dir, "two", "crates", "app", "Cargo.toml")).toContain('serde = "1.0.200"');
});
test.each([
["CLI exclude", {exclude: ["serde"]}, {}],
["packageName rule", {}, {enabled: false}],
])("renamed Cargo crates respect a %s", async (_name, options, rule) => {
const dir = writeTree("cargo-alias", {
"Cargo.toml": '[dependencies]\nserde1 = { package = "serde", version = "1.0.0" }\n',
"renovate.json": JSON.stringify({packageRules: [{matchPackageNames: ["serde"], ...rule}]}),
});
const output = await updates(apiOpts({files: [join(dir, "Cargo.toml")], ...options}));
expect(output.errors).toBeUndefined();
expect(output.results).toEqual({});
});
test("Cargo workspace excludes use their own lockfile", async () => {
const dir = writeTree("cargo-exclude", {
"Cargo.toml": '[workspace]\nmembers = ["crates/*"]\nexclude = ["crates/standalone"]\n',
"Cargo.lock": '[[package]]\nname = "serde"\nversion = "1.0.100"\n',
"crates/standalone/Cargo.toml": '[dependencies]\nserde = "1.0.0"\n',
"crates/standalone/Cargo.lock": '[[package]]\nname = "serde"\nversion = "1.0.200"\n',
});
const output = await updates(apiOpts({files: [join(dir, "Cargo.toml"), join(dir, "crates/standalone/Cargo.toml")]}));
expect(output.errors).toBeUndefined();
expect(output.results).toEqual({});
});
test("pnpm workspace", async () => {
const options = {registry: npmUrl, forgeapi: githubUrl, color: false, noCache: true};
const {npm} = (await updates({...options, files: [pnpmWorkspaceFile]})).results;
expect(npm.devDependencies.typescript.new).toBeTruthy();
expect(npm["dependencies|./packages/app-a"].prismjs.new).toBeTruthy();
expect(npm["dependencies|./packages/lib-b"].react.new).toBeTruthy();
expect(npm["catalog|pnpm-workspace.yaml"].svgstore.new).toBeTruthy();
expect(npm["catalogs.build|pnpm-workspace.yaml"].typescript.new).toBeTruthy();
expect(npm["dependencies|./packages/lib-b"].svgstore).toBeUndefined();
const fromMember = await updates({...options, files: [fixture("pnpm-workspace/packages/app-a/package.json"), pnpmWorkspaceFile]});
expect(Object.keys(fromMember.results.npm).sort()).toEqual(Object.keys(npm).sort());
for (const files of [[fixture("pnpm-workspace/package.json")], [fixture("pnpm-workspace/package.json"), pnpmWorkspaceFile]]) {
expect((await updates({...options, files, excludePaths: ["package.json"]})).results.npm.devDependencies).toEqual(npm.devDependencies);
}
const excluded = await updates({...options, files: [dirname(pnpmWorkspaceFile)], excludePaths: ["packages/app-a/**"]});
expect(excluded.results.npm["dependencies|./packages/app-a"]).toBeUndefined();
expect(excluded.results.npm["dependencies|./packages/lib-b"].react.new).toBeTruthy();
});
test("pnpm workspace update, and a second run is a no-op", async () => {
const dir = copyFixture("pnpm-workspace");
const run = () => runCliExec(["-u", "-f", join(dir, "pnpm-workspace.yaml"), "-c", ...apiArgs]);
await run();
expect(read(dir, "package.json")).not.toContain('"^4"');
expect(read(dir, "packages", "app-a", "package.json")).not.toContain('"1.0.0"');
expect(read(dir, "packages", "lib-b", "package.json")).not.toContain('"18.0"');
expect(read(dir, "packages", "lib-b", "package.json")).toContain('"svgstore": "catalog:"');
const workspace = read(dir, "pnpm-workspace.yaml");
expect(workspace).toContain(' svgstore: "^2.0.3" # pinned');
expect(workspace).toContain(" typescript: ^5\n");
await run();
expect(read(dir, "pnpm-workspace.yaml")).toBe(workspace);
});
test("pnpm workspace alongside unrelated package.json", async () => {
for (const files of [[pnpmWorkspaceFile, testFile], [testFile, pnpmWorkspaceFile]]) {
const {npm} = (await updates({files, registry: npmUrl, forgeapi: githubUrl, color: false, noCache: true})).results;
expect(npm.devDependencies.typescript.new).toBeTruthy();
expect(npm["dependencies|./packages/app-a"].prismjs.new).toBeTruthy();
expect(npm["dependencies|./packages/lib-b"].react.new).toBeTruthy();
expect(Object.values(npm).flatMap(group => Object.keys(group))).toContain("gulp-sourcemaps");
}
});