-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.mjs
More file actions
5730 lines (5555 loc) · 199 KB
/
Copy pathcore.mjs
File metadata and controls
5730 lines (5555 loc) · 199 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
// SPDX-FileCopyrightText: 2026 ReallyMe LLC
//
// SPDX-License-Identifier: MIT OR Apache-2.0
import { lstatSync, readdirSync, readFileSync, realpathSync, writeSync } from "node:fs";
import { createHash } from "node:crypto";
import { extname, isAbsolute, relative, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { spawnSync } from "node:child_process";
// This module is the release package's shared policy core. The public runner
// supplies this exact immutable module to consumers so release-critical checks
// cannot drift independently from the pinned package revision.
export const RELEASE_READINESS_VERSION = "0.6.7";
const DEFAULT_FAILURE_PREFIX = "release readiness check failed";
const MAX_PRODUCTION_SOURCE_LINES = 500;
const MAX_SEPARATE_TEST_SOURCE_LINES = 800;
const DEFAULT_REALLYME_LATEST_STABLE_DEPENDENCIES = [
"reallyme-crypto",
"reallyme-codec",
"reallyme-jose",
"reallyme-cose",
];
const escapeRegExpLiteral = (value) => value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
const scrubProtoCommentsAndStrings = (source) => {
let output = "";
let state = "normal";
for (let index = 0; index < source.length; index += 1) {
const character = source[index];
const next = source[index + 1];
if (state === "normal") {
if (character === "/" && next === "/") {
output += " ";
index += 1;
state = "line-comment";
} else if (character === "/" && next === "*") {
output += " ";
index += 1;
state = "block-comment";
} else if (character === '"' || character === "'") {
output += " ";
state = character === '"' ? "double-quoted-string" : "single-quoted-string";
} else {
output += character;
}
continue;
}
if (state === "line-comment") {
if (character === "\n") {
output += "\n";
state = "normal";
} else {
output += " ";
}
continue;
}
if (state === "block-comment") {
if (character === "*" && next === "/") {
output += " ";
index += 1;
state = "normal";
} else {
output += character === "\n" ? "\n" : " ";
}
continue;
}
if (character === "\\" && next !== undefined) {
output += next === "\n" ? " \n" : " ";
index += 1;
} else if (
(state === "double-quoted-string" && character === '"') ||
(state === "single-quoted-string" && character === "'")
) {
output += " ";
state = "normal";
} else {
output += character === "\n" ? "\n" : " ";
}
}
return output;
};
const javascriptSlashStartsRegex = (source, index) => {
let cursor = index - 1;
while (cursor >= 0 && /\s/u.test(source[cursor])) {
cursor -= 1;
}
if (cursor < 0) {
return true;
}
return "=(:,[!&|?;{}".includes(source[cursor]);
};
const scrubJavaScriptCommentsAndStrings = (source, options = {}) => {
const preserveStrings = options.preserveStrings ?? false;
const preserveComments = options.preserveComments ?? false;
let output = "";
let state = "normal";
let regexCharacterClass = false;
for (let index = 0; index < source.length; index += 1) {
const character = source[index];
const next = source[index + 1];
if (state === "normal") {
if (character === "/" && next === "/") {
output += preserveComments ? "//" : " ";
index += 1;
state = "line-comment";
} else if (character === "/" && next === "*") {
output += preserveComments ? "/*" : " ";
index += 1;
state = "block-comment";
} else if (character === "/" && javascriptSlashStartsRegex(source, index)) {
output += preserveStrings ? character : " ";
regexCharacterClass = false;
state = "regex";
} else if (character === '"' || character === "'" || character === "`") {
output += preserveStrings ? character : " ";
state =
character === '"'
? "double-quoted-string"
: character === "'"
? "single-quoted-string"
: "template-string";
} else {
output += character;
}
continue;
}
if (state === "line-comment") {
if (character === "\n") {
output += "\n";
state = "normal";
} else {
output += preserveComments ? character : " ";
}
continue;
}
if (state === "block-comment") {
if (character === "*" && next === "/") {
output += preserveComments ? "*/" : " ";
index += 1;
state = "normal";
} else {
output += preserveComments ? character : character === "\n" ? "\n" : " ";
}
continue;
}
if (state === "regex") {
if (character === "\\" && next !== undefined) {
output += preserveStrings ? `${character}${next}` : next === "\n" ? " \n" : " ";
index += 1;
} else if (character === "[") {
output += preserveStrings ? character : " ";
regexCharacterClass = true;
} else if (character === "]") {
output += preserveStrings ? character : " ";
regexCharacterClass = false;
} else if (character === "/" && !regexCharacterClass) {
output += preserveStrings ? character : " ";
state = "normal";
} else {
output += preserveStrings ? character : character === "\n" ? "\n" : " ";
}
continue;
}
if (character === "\\" && next !== undefined) {
output += preserveStrings ? `${character}${next}` : next === "\n" ? " \n" : " ";
index += 1;
} else if (
(state === "double-quoted-string" && character === '"') ||
(state === "single-quoted-string" && character === "'") ||
(state === "template-string" && character === "`")
) {
output += preserveStrings ? character : " ";
state = "normal";
} else {
output += preserveStrings ? character : character === "\n" ? "\n" : " ";
}
}
return output;
};
const rustRawStringStart = (source, index) => {
let cursor = index;
if (source[cursor] === "b" && source[cursor + 1] === "r") {
cursor += 2;
} else if (source[cursor] === "r") {
cursor += 1;
} else {
return null;
}
let hashCount = 0;
while (source[cursor] === "#") {
hashCount += 1;
cursor += 1;
}
if (source[cursor] !== '"') {
return null;
}
return {
length: cursor - index + 1,
terminator: `"${"#".repeat(hashCount)}`,
};
};
const scrubRustCommentsAndStrings = (source) => {
let output = "";
let state = "normal";
let blockDepth = 0;
let rawTerminator = "";
for (let index = 0; index < source.length; index += 1) {
const character = source[index];
const next = source[index + 1];
if (state === "normal") {
if (character === "/" && next === "/") {
output += " ";
index += 1;
state = "line-comment";
} else if (character === "/" && next === "*") {
output += " ";
index += 1;
blockDepth = 1;
state = "block-comment";
} else {
const rawStart = rustRawStringStart(source, index);
if (rawStart !== null) {
output += " ".repeat(rawStart.length);
index += rawStart.length - 1;
rawTerminator = rawStart.terminator;
state = "raw-string";
} else if (character === '"') {
output += " ";
state = "quoted-string";
} else {
output += character;
}
}
continue;
}
if (state === "line-comment") {
if (character === "\n") {
output += "\n";
state = "normal";
} else {
output += " ";
}
continue;
}
if (state === "block-comment") {
if (character === "/" && next === "*") {
output += " ";
index += 1;
blockDepth += 1;
} else if (character === "*" && next === "/") {
output += " ";
index += 1;
blockDepth -= 1;
if (blockDepth === 0) {
state = "normal";
}
} else {
output += character === "\n" ? "\n" : " ";
}
continue;
}
if (state === "quoted-string") {
if (character === "\\" && next !== undefined) {
output += next === "\n" ? " \n" : " ";
index += 1;
} else if (character === '"') {
output += " ";
state = "normal";
} else {
output += character === "\n" ? "\n" : " ";
}
continue;
}
if (source.startsWith(rawTerminator, index)) {
output += " ".repeat(rawTerminator.length);
index += rawTerminator.length - 1;
state = "normal";
} else {
output += character === "\n" ? "\n" : " ";
}
}
return output;
};
const scrubSlashCommentsAndStrings = (source, options = {}) => {
const preserveComments = options.preserveComments ?? false;
let output = "";
let state = "normal";
let blockDepth = 0;
for (let index = 0; index < source.length; index += 1) {
const character = source[index];
const next = source[index + 1];
if (state === "normal") {
if (character === "/" && next === "/") {
output += preserveComments ? "//" : " ";
index += 1;
state = "line-comment";
} else if (character === "/" && next === "*") {
output += preserveComments ? "/*" : " ";
index += 1;
blockDepth = 1;
state = "block-comment";
} else if (source.startsWith('"""', index)) {
output += " ";
index += 2;
state = "triple-quoted-string";
} else if (character === '"' || character === "'") {
output += " ";
state = character === '"' ? "double-quoted-string" : "single-quoted-string";
} else {
output += character;
}
continue;
}
if (state === "line-comment") {
if (character === "\n") {
output += "\n";
state = "normal";
} else {
output += preserveComments ? character : " ";
}
continue;
}
if (state === "block-comment") {
if (character === "/" && next === "*") {
output += preserveComments ? "/*" : " ";
index += 1;
blockDepth += 1;
} else if (character === "*" && next === "/") {
output += preserveComments ? "*/" : " ";
index += 1;
blockDepth -= 1;
if (blockDepth === 0) {
state = "normal";
}
} else {
output += preserveComments ? character : character === "\n" ? "\n" : " ";
}
continue;
}
if (state === "triple-quoted-string") {
if (source.startsWith('"""', index)) {
output += " ";
index += 2;
state = "normal";
} else {
output += character === "\n" ? "\n" : " ";
}
continue;
}
if (character === "\\" && next !== undefined) {
output += next === "\n" ? " \n" : " ";
index += 1;
} else if (
(state === "double-quoted-string" && character === '"') ||
(state === "single-quoted-string" && character === "'")
) {
output += " ";
state = "normal";
} else {
output += character === "\n" ? "\n" : " ";
}
}
return output;
};
const scrubSlashCommentsPreservingStrings = (source) => {
let output = "";
let state = "normal";
let blockDepth = 0;
for (let index = 0; index < source.length; index += 1) {
const character = source[index];
const next = source[index + 1];
if (state === "normal") {
if (character === "/" && next === "/") {
output += " ";
index += 1;
state = "line-comment";
} else if (character === "/" && next === "*") {
output += " ";
index += 1;
blockDepth = 1;
state = "block-comment";
} else {
output += character;
if (character === '"' || character === "'") {
state = character === '"' ? "double-quoted-string" : "single-quoted-string";
}
}
continue;
}
if (state === "line-comment") {
if (character === "\n") {
output += "\n";
state = "normal";
} else {
output += " ";
}
continue;
}
if (state === "block-comment") {
if (character === "/" && next === "*") {
output += " ";
index += 1;
blockDepth += 1;
} else if (character === "*" && next === "/") {
output += " ";
index += 1;
blockDepth -= 1;
if (blockDepth === 0) {
state = "normal";
}
} else {
output += character === "\n" ? "\n" : " ";
}
continue;
}
output += character;
if (character === "\\" && next !== undefined) {
output += next;
index += 1;
} else if (
(state === "double-quoted-string" && character === '"') ||
(state === "single-quoted-string" && character === "'")
) {
state = "normal";
}
}
return output;
};
const scrubHashCommentsPreservingStrings = (source) =>
source
.split("\n")
.map((line) => {
let quote = null;
for (let index = 0; index < line.length; index += 1) {
const character = line[index];
if (quote !== null) {
if (character === "\\") {
index += 1;
} else if (character === quote) {
quote = null;
}
continue;
}
if (character === '"' || character === "'") {
quote = character;
} else if (character === "#" && (index === 0 || /\s/u.test(line[index - 1]))) {
return line.slice(0, index);
}
}
return line;
})
.join("\n");
const scrubHtmlComments = (source) => source.replace(/<!--[\s\S]*?-->/gu, (comment) =>
comment.replace(/[^\n]/gu, " "));
export const scrubCommentsForAssertion = (path, source) => {
const extension = extname(path).toLowerCase();
if ([".js", ".jsx", ".mjs", ".mts", ".ts", ".tsx"].includes(extension)) {
return scrubJavaScriptCommentsAndStrings(source, { preserveStrings: true });
}
if (
[".c", ".cc", ".cpp", ".h", ".hpp", ".java", ".kt", ".kts", ".proto", ".rs", ".swift"]
.includes(extension)
) {
return scrubSlashCommentsPreservingStrings(source);
}
if ([".py", ".rb", ".sh", ".toml", ".yaml", ".yml"].includes(extension) || path.endsWith("/.gitignore")) {
return scrubHashCommentsPreservingStrings(source);
}
if (extension === ".md") {
return scrubHtmlComments(source);
}
return source;
};
export function createReleaseReadinessContext(options) {
const {
scriptUrl,
repoRoot = "..",
requireTrackedFiles = false,
failurePrefix = DEFAULT_FAILURE_PREFIX,
} = options ?? {};
if (typeof scriptUrl !== "string" || scriptUrl.length === 0) {
console.error(`${failurePrefix}: scriptUrl is required`);
process.exit(1);
}
let root;
try {
// Canonicalize the repository root so containment checks remain stable when
// the caller reached the worktree through an operating-system path alias
// such as /tmp versus /private/tmp.
root = realpathSync(resolve(fileURLToPath(new URL(repoRoot, scriptUrl))));
} catch {
console.error(`${failurePrefix}: repository root is missing or inaccessible`);
process.exit(1);
}
let trackedFiles = null;
const fail = (message) => {
console.error(`${failurePrefix}: ${message}`);
process.exit(1);
};
const reportSourcePolicy = (language) => {
if (
process.env.RELEASE_READINESS_ENFORCED_VERSION !== RELEASE_READINESS_VERSION ||
process.env.RELEASE_READINESS_SOURCE_POLICY_FD !== "3"
) {
return;
}
try {
writeSync(3, `${language}\n`);
} catch {
fail(`could not report the enforced ${language} source policy`);
}
};
const resolveRepositoryPath = (path, description = "path") => {
if (
typeof path !== "string" ||
path.length === 0 ||
path.includes("\0") ||
isAbsolute(path)
) {
fail(`${description} must be a non-empty repository-relative path`);
}
const absolute = resolve(root, path);
const repositoryRelative = relative(root, absolute);
if (
repositoryRelative === ".." ||
repositoryRelative.startsWith(`..${sep}`) ||
isAbsolute(repositoryRelative)
) {
fail(`${description} escapes the repository root`);
}
return absolute;
};
const assertCanonicalPathInsideRepository = (absolute, description) => {
let canonical;
try {
canonical = realpathSync(absolute);
} catch {
fail(`${description} is missing or inaccessible`);
}
const repositoryRelative = relative(root, canonical);
if (
repositoryRelative === ".." ||
repositoryRelative.startsWith(`..${sep}`) ||
isAbsolute(repositoryRelative)
) {
fail(`${description} resolves outside the repository root`);
}
return canonical;
};
const assertRegularFile = (path) => {
const absolute = resolveRepositoryPath(path);
let status;
try {
status = lstatSync(absolute);
} catch {
fail(`${path} is missing from the worktree`);
}
if (status.isSymbolicLink()) {
fail(`${path} must not be a symbolic link`);
}
if (!status.isFile()) {
fail(`${path} is not a regular file`);
}
return assertCanonicalPathInsideRepository(absolute, path);
};
const assertRepositoryDirectory = (path, description = path) => {
const absolute = resolveRepositoryPath(path, description);
let status;
try {
status = lstatSync(absolute);
} catch {
fail(`${description} is missing from the worktree`);
}
if (status.isSymbolicLink()) {
fail(`${description} must not be a symbolic link`);
}
if (!status.isDirectory()) {
fail(`${description} is not a directory`);
}
return assertCanonicalPathInsideRepository(absolute, description);
};
const run = (command, args, runOptions = {}) => {
if (typeof command !== "string" || command.length === 0) {
fail("release readiness command must be a non-empty string");
}
if (!Array.isArray(args) || args.some((arg) => typeof arg !== "string")) {
fail(`${command} arguments must be an array of strings`);
}
const cwd =
runOptions.cwd === undefined
? root
: assertRepositoryDirectory(
runOptions.cwd,
`${command} working directory`,
);
const result = spawnSync(command, args, {
cwd,
encoding: "utf8",
stdio: runOptions.capture ? "pipe" : "inherit",
env: runOptions.env ?? process.env,
});
if (result.error) {
fail(`${[command, ...args].join(" ")} failed to start: ${result.error.message}`);
}
if (result.status !== 0) {
if (runOptions.capture) {
process.stdout.write(result.stdout ?? "");
process.stderr.write(result.stderr ?? "");
}
process.exit(result.status ?? 1);
}
return result;
};
const loadTrackedFiles = () => {
if (trackedFiles !== null) {
return trackedFiles;
}
const result = spawnSync("git", ["ls-files", "-z"], {
cwd: root,
encoding: "utf8",
stdio: "pipe",
});
if (result.error) {
fail(`git ls-files -z failed to start: ${result.error.message}`);
}
if (result.status !== 0) {
process.stdout.write(result.stdout ?? "");
process.stderr.write(result.stderr ?? "");
process.exit(result.status ?? 1);
}
trackedFiles = new Set(result.stdout.split("\0").filter(Boolean));
return trackedFiles;
};
const requireTracked = (path) => {
resolveRepositoryPath(path);
if (!loadTrackedFiles().has(path)) {
fail(`${path} is not tracked by Git`);
}
};
const assertPathsAbsent = (paths) => {
if (
!Array.isArray(paths) ||
paths.some((path) => typeof path !== "string" || path.length === 0)
) {
fail("absent path policy must be an array of non-empty strings");
}
for (const path of paths) {
const absolute = resolveRepositoryPath(path);
try {
// lstat observes broken symlinks as well as live files and directories.
// existsSync would silently treat a broken compatibility symlink as
// absent, leaving a retired entry in release artifacts.
lstatSync(absolute);
fail(`${path} must not exist`);
} catch (error) {
if (
error === null ||
typeof error !== "object" ||
!("code" in error) ||
error.code !== "ENOENT"
) {
fail(`${path} absence could not be verified`);
}
}
if (
requireTrackedFiles &&
[...loadTrackedFiles()].some(
(trackedPath) => trackedPath === path || trackedPath.startsWith(`${path}/`),
)
) {
fail(`${path} must not remain tracked by Git`);
}
}
};
if (requireTrackedFiles) {
const coreAbsolutePath = realpathSync(fileURLToPath(import.meta.url));
const corePath = relative(root, coreAbsolutePath).replaceAll("\\", "/");
const enforcedCoreUrl = process.env.RELEASE_READINESS_CORE_URL;
if (typeof enforcedCoreUrl === "string" && enforcedCoreUrl.length > 0) {
let enforcedCorePath;
try {
enforcedCorePath = realpathSync(fileURLToPath(new URL(enforcedCoreUrl)));
} catch {
fail("external release-readiness core is not bound to the pinned runner");
}
if (
enforcedCorePath !== coreAbsolutePath ||
process.env.RELEASE_READINESS_ENFORCED_VERSION !== RELEASE_READINESS_VERSION
) {
fail("external release-readiness core is not bound to the pinned runner");
}
} else {
requireTracked(corePath);
}
}
const readText = (path) => {
if (requireTrackedFiles) {
requireTracked(path);
}
return readFileSync(assertRegularFile(path), "utf8");
};
const readJson = (path) => {
try {
return JSON.parse(readText(path));
} catch {
fail(`${path} is not valid JSON`);
}
};
const fingerprintFile = (path) =>
createHash("sha256").update(readFileSync(assertRegularFile(path))).digest("hex");
const listFiles = (path) => {
resolveRepositoryPath(path);
const directory = assertRepositoryDirectory(path);
const prefix = `${path}/`;
if (requireTrackedFiles) {
const files = [...loadTrackedFiles()].filter((file) => file.startsWith(prefix));
if (files.length === 0) {
fail(`${path} has no tracked files`);
}
return files;
}
const files = [];
const visit = (current) => {
for (const entry of readdirSync(current).sort()) {
const absolute = resolve(current, entry);
const status = lstatSync(absolute);
if (status.isSymbolicLink()) {
fail(`${relative(root, absolute)} must not be a symbolic link`);
}
if (status.isDirectory()) {
visit(absolute);
} else if (status.isFile()) {
files.push(relative(root, absolute));
} else {
fail(`${relative(root, absolute)} is not a regular file`);
}
}
};
visit(directory);
return files;
};
const loadUntrackedFiles = () => {
const result = spawnSync(
"git",
["ls-files", "--others", "--exclude-standard", "-z"],
{
cwd: root,
encoding: "utf8",
stdio: "pipe",
},
);
if (result.error) {
fail(`git ls-files --others --exclude-standard -z failed to start: ${result.error.message}`);
}
if (result.status !== 0) {
process.stdout.write(result.stdout ?? "");
process.stderr.write(result.stderr ?? "");
process.exit(result.status ?? 1);
}
return result.stdout.split("\0").filter(Boolean);
};
const assertContains = (path, needle) => {
if (!scrubCommentsForAssertion(path, readText(path)).includes(needle)) {
fail(`${path} does not contain ${needle}`);
}
};
const assertNotContains = (path, needle) => {
if (readText(path).includes(needle)) {
fail(`${path} must not contain ${needle}`);
}
};
const assertMinOccurrences = (path, needle, expectedMin) => {
const count = readText(path).split(needle).length - 1;
if (count < expectedMin) {
fail(`${path} contains ${needle} ${count} time(s), expected at least ${expectedMin}`);
}
};
const assertTextPolicy = (policy) => {
const files = policy?.files ?? [];
if (!Array.isArray(files) || files.length === 0) {
fail("text policy requires at least one file policy");
}
for (const filePolicy of files) {
const {
path,
required = [],
forbidden = [],
minimumOccurrences = [],
requiredMatches = [],
forbiddenMatches = [],
} = filePolicy ?? {};
if (typeof path !== "string" || path.length === 0) {
fail("text file policy requires a path");
}
for (const [policyName, needles] of [
["required", required],
["forbidden", forbidden],
]) {
if (
!Array.isArray(needles) ||
needles.some((needle) => typeof needle !== "string")
) {
fail(`${path} ${policyName} text policy must be an array of strings`);
}
}
if (!Array.isArray(minimumOccurrences)) {
fail(`${path} minimum-occurrence policy must be an array`);
}
if (!Array.isArray(requiredMatches) || !Array.isArray(forbiddenMatches)) {
fail(`${path} regular-expression policies must be arrays`);
}
for (const needle of required) {
assertContains(path, needle);
}
for (const needle of forbidden) {
assertNotContains(path, needle);
}
for (const occurrence of minimumOccurrences) {
const { needle, count } = occurrence ?? {};
if (typeof needle !== "string" || !Number.isSafeInteger(count) || count < 0) {
fail(`${path} has an invalid minimum-occurrence policy`);
}
assertMinOccurrences(path, needle, count);
}
for (const matchPolicy of requiredMatches) {
const { pattern, description } = matchPolicy ?? {};
requireMatch(path, pattern, description);
}
for (const matchPolicy of forbiddenMatches) {
const { pattern, description } = matchPolicy ?? {};
assertNotMatches(path, pattern, description);
}
}
};
const clonePattern = (pattern) => {
if (!(pattern instanceof RegExp)) {
fail("release readiness match assertions require a RegExp");
}
return new RegExp(pattern.source, pattern.flags);
};
const requireMatch = (path, pattern, description) => {
// Clone caller-provided expressions so global or sticky regex state cannot
// make a repeated release check depend on an earlier invocation.
const match = clonePattern(pattern).exec(readText(path));
if (match === null) {
fail(`${path} does not contain ${description}`);
}
return match;
};
const assertNotMatches = (path, pattern, description) => {
// Keep this assertion deterministic when a shared expression uses `g` or `y`.
if (clonePattern(pattern).test(readText(path))) {
fail(`${path} must not contain ${description}`);
}
};
const assertLockPackageVersion = (lock, name, version, source = null) => {
const blocks = lock.match(/\[\[package\]\]\n[\s\S]*?(?=\n\[\[package\]\]|\n*$)/g) ?? [];
const block = blocks.find(
(candidate) =>
candidate.includes(`name = "${name}"\n`) && candidate.includes(`version = "${version}"\n`),
);
if (block === undefined) {
fail(`Cargo.lock does not pin ${name} ${version}`);
}
if (source !== null && !block.includes(`source = "${source}"\n`)) {
fail(`Cargo.lock ${name} ${version} does not use ${source}`);
}
};
const runNodeCheck = (scriptPath, args = []) => {
const result = spawnSync(process.execPath, [scriptPath, ...args], {
cwd: root,
encoding: "utf8",
stdio: "pipe",
});
if (result.error) {
fail(`${[scriptPath, ...args].join(" ")} failed to start: ${result.error.message}`);
}
if (result.status !== 0) {
const output = `${result.stdout ?? ""}${result.stderr ?? ""}`.trim();
const command = [scriptPath, ...args].join(" ");
fail(`${command} failed${output.length === 0 ? "" : `:\n${output}`}`);
}
};
const packageList = (packageName) => {
const args = ["package", "--list", "-p", packageName];
if (process.env.GITHUB_ACTIONS !== "true") {
args.push("--allow-dirty");
}
return run("cargo", args, { capture: true }).stdout.split(/\r?\n/u).filter(Boolean);
};
const assertPackageFiles = (packageName, requiredFiles) => {
const files = new Set(packageList(packageName));
for (const file of requiredFiles) {
if (!files.has(file)) {
fail(`${packageName} package is missing ${file}`);
}
}
};
const runCommands = (commands) => {
if (!Array.isArray(commands) || commands.length === 0) {
fail("command policy requires at least one command");
}
for (const entry of commands) {
if (!Array.isArray(entry) || entry.length < 2 || entry.length > 3) {
fail("command policy entries must be [command, args, options?] tuples");
}
const [command, args, options] = entry;
if (
options !== undefined &&
(options === null || typeof options !== "object" || Array.isArray(options))
) {
fail("command policy options must be an object");
}
run(command, args, options ?? {});
}
};
const validateLatestStableVersions = (versions = {}) => {
if (versions === null || typeof versions !== "object" || Array.isArray(versions)) {
fail("latest stable version overrides must be an explicit mapping");
}
const parsed = new Map();
for (const [crateName, version] of Object.entries(versions)) {
if (!/^[a-z][a-z0-9_-]*$/u.test(crateName)) {
fail("latest stable version override names must be crate identifiers");
}
if (typeof version !== "string" || !/^\d+\.\d+\.\d+$/u.test(version)) {
fail(`${crateName} latest stable override must be an exact stable version`);
}
parsed.set(crateName, version);
}
return parsed;
};
const loadLatestCargoRegistryVersion = (crateName, latestStableVersions) => {
if (!/^[a-z][a-z0-9_-]*$/u.test(crateName)) {
fail("latest Cargo registry version lookup requires a crate identifier");
}
const overriddenVersion = latestStableVersions.get(crateName);
if (overriddenVersion !== undefined) {
return overriddenVersion;
}
const result = run("cargo", ["search", crateName, "--limit", "20"], {
capture: true,
});
const match = new RegExp(
`^${escapeRegExpLiteral(crateName)}\\s*=\\s*"([^"]+)"`,
"mu",
).exec(result.stdout);
if (match === null) {
fail(`cargo search did not return ${crateName}`);
}
if (!/^\d+\.\d+\.\d+$/u.test(match[1])) {
fail(`${crateName} latest Cargo registry version is not stable`);
}