Repository navigation
1023 lines (938 loc) · 47 KB
/
Copy pathcontinuous-integration.yml
File metadata and controls
1023 lines (938 loc) · 47 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
# Workflow to performs continuous integration steps against a Node.js project:
#
# - CodeQL analysis
# - Linting
# - Build
# - Test
name: Node.js Continuous Integration
on:
workflow_call:
inputs:
ignore-scripts:
description: |
Disable project and dependency lifecycle scripts during installation in build, lint and test jobs.
Set false to allow installation hooks, subject to the package manager's script approval settings.
Explicit commands are unaffected. Does not apply in container mode, which skips installation.
type: boolean
default: true
runs-on:
description: |
JSON array of runner(s) to use.
See https://docs.github.com/en/actions/using-jobs/choosing-the-runner-for-a-job.
type: string
default: '["ubuntu-latest"]'
required: false
build:
description: |
Build parameters. Accepts newline-separated commands, a JSON array, or a JSON object.
An empty or whitespace-only string skips the build job; tests and optional packaging can run without it.
For string, provide a list of commands to run during the build step, one per line.
For JSON object, provide the following properties:
- `commands`: Array of commands to run during the build step.
- `env`: Object of environment variables to set during the build step.
- `artifact`: String or array of strings specifying paths to artifacts to upload after the build
Example:
```json
{
"commands": [
"build",
"generate-artifacts"
],
"env": {
"CUSTOM_ENV_VAR": "value"
},
"artifact": [
"dist/",
"packages/package-a/build/"
]
}
```
type: string
required: false
default: "build"
package:
description: |
Create and validate public npm packages from the checked-out source and build output.
Pass "false" (the default) to disable, "true" for automatic package discovery and default checks,
or a JSON object to enable packaging with specific options. Quote booleans because this input has type string.
- `directories`: Optional array of public package directories relative to working-directory. Omit to discover workspaces or the standalone root package. Private packages are excluded.
- `tests`: Optional shell commands after default manifest and entry-point checks. Runs in an isolated npm consumer with lifecycle scripts disabled and installed binaries on PATH.
- `test-project`: Optional consumer fixture directory relative to working-directory. Its dependencies and scripts are copied without node_modules or Git metadata. Requires `tests`.
PACKAGE_INSTALL_PATH, PACKAGE_TARBALL_PATH, PACKAGE_NAME and PACKAGE_VERSION identify the tested package.
All workspace tarballs are created before consumer tests. Declared workspace dependencies are installed
from these local tarballs, so unpublished versions can be validated together.
The consumer is cleaned up on success or failure. Commands must not modify tarballs.
Requires non-container CI with the default Ubuntu artifact layout.
Unknown options and invalid field types are rejected before build or packaging.
Example: `{"tests":"my-cli --help"}`
type: string
default: "false"
checks:
description: "Optional flag to enable check steps."
type: boolean
required: false
default: true
lint:
description: |
Whether to enable linting.
Set to `null` or empty to disable.
Accepts a JSON object for lint options. See [lint action](../../actions/lint/README.md).
It should generate lint reports in standard formats.
Example:
```json:package.json
{
"lint:ci": "eslint . --output-file eslint-report.json --format json"
}
```
type: string
required: false
default: "true"
code-ql:
description: |
CodeQL analysis language, or a JSON object with `languages` and optional `config-file`.
Set to an empty string to disable CodeQL.
In JSON form, `languages` must be a nonempty string and `config-file` must be a string.
Omitting or leaving `config-file` empty keeps CodeQL's default configuration behavior.
Unknown JSON properties and invalid field types fail before CodeQL initialization.
Local configuration paths are relative to the caller repository root, not `working-directory`.
See https://github.com/github/codeql-action.
Example:
```json
{
"languages": "javascript-typescript",
"config-file": ".github/codeql/config.yml"
}
```
type: string
required: false
default: "typescript"
dependency-review:
description: |
Enable dependency review scan.
Works with public repositories and private repositories with a GitHub Advanced Security license.
See https://github.com/actions/dependency-review-action.
type: boolean
required: false
default: true
test:
description: |
Whether to enable testing.
Set to `null` or empty to disable.
Accepts a JSON object for test options. See [test action](../../actions/test/README.md).
If coverage is enabled, it should generate test and coverage reports in standard formats.
Optional `arguments` is a JSON array passed to the package script without shell expansion.
Set `shards` to an integer from 2 to 256 to enable Vitest blob sharding (default: 1).
Only tests are replicated; shards run with fail-fast disabled and concurrency limited to their count.
A single merge job validates every payload and publishes final reports, even after test failures.
`merge-command` defaults to `command`; use a separate package script when reporter settings differ.
Sharding owns --shard, --merge-reports and --outputFile.blob; do not put these in package scripts or arguments.
Use reporter-specific output paths such as --outputFile.junit=junit.xml; the scalar --outputFile form conflicts with blob output.
Keep the same project source, dependencies, Vitest config and absolute project path across jobs.
Rerun the entire workflow after failure; previous-attempt shard artifacts are never reused.
CI_TEST_SHARD is index/total during shards and empty during merging. If coverage thresholds are configured,
defer them to merging with `thresholds: process.env.CI_TEST_SHARD ? undefined : yourThresholds`.
Keep coverage enabled in both commands, and set coverage.reportOnFailure to retain failed-test coverage.
Final reporters and report-file must describe the merged JUnit/LCOV outputs.
Blob payloads include coverage; file-based attachments are not transferred by this workflow.
Example: `{"command":"test:ci","shards":2,"report-file":"junit.xml,coverage/lcov.info"}`.
For consolidated reports, set `comment` to false and `report-group` to the calling job ID
used in the common `ci-reports` workflow's `job-results`.
Example:
```json:package.json
{
"test:ci": "vitest run --reporter=default --reporter=junit --outputFile.junit=junit.xml --coverage.enabled --coverage.reporter=lcov --coverage.reporter=text"
}
```
type: string
required: false
default: "true"
working-directory:
description: |
Working directory where dependencies and application commands run.
Relative paths resolve against the workspace of each application job.
Directory existence and non-container workspace boundaries are validated in those jobs.
type: string
required: false
default: "."
container:
description: |
Container configuration to run CI steps in.
Accepts either a string (container image name) or a JSON object with container options.
String format (simple):
```yml
container: "node:18"
```
JSON object format (advanced):
```json
{
"image": "node:18",
"env": {
"NODE_ENV": "production"
},
"options": "--cpus 2",
"ports": [8080, 3000],
"volumes": ["/tmp:/tmp", "/cache:/cache"],
"credentials": {
"username": "myusername"
},
"pathMapping": {
"/app": "./relative/path/to/app"
}
}
```
Supported properties:
- `image` (required)
- `env` (object)
- `options` (string)
- `ports` (array)
- `volumes` (array)
- `credentials` (object with `username`).
- `pathMapping` (object) path mapping from container paths to repository paths. Defaults is working directory is mapped with repository root.
See https://docs.github.com/en/actions/how-tos/write-workflows/choose-where-workflows-run/run-jobs-in-a-container.
When specified, steps will execute inside this container instead of checking out code.
The container should have the project code and dependencies pre-installed.
type: string
required: false
default: ""
secrets:
build-secrets:
description: |
Secrets to be used during the build step.
Must be a multi-line env formatted string.
Example:
```txt
SECRET_EXAMPLE=$\{{ secrets.SECRET_EXAMPLE }}
```
required: false
container-password:
description: |
Password for container registry authentication, if required.
Used when the container image is hosted in a private registry.
See https://docs.github.com/en/actions/how-tos/write-workflows/choose-where-workflows-run/run-jobs-in-a-container#defining-credentials-for-a-container-registry.
required: false
github-token:
description: |
GitHub token to use for authentication.
Defaults to `GITHUB_TOKEN` if not provided.
required: false
outputs:
package-tarball-artifact-id:
description: Artifact ID of the package validated by the packaging job. Available when package is enabled and validation succeeds.
value: ${{ jobs.package-results.outputs.artifact-id }}
package-tarball-artifacts:
description: JSON object mapping package directories to validated tarball artifact IDs when packaging is enabled. Require successful CI before publication.
value: ${{ jobs.package-results.outputs.artifacts }}
build-artifact-id:
description: "ID of the build artifact) uploaded during the build step."
value: ${{ jobs.build.outputs.artifact-id }}
permissions: {}
jobs:
prepare:
name: 📦 Prepare configuration
runs-on: &ci-runner ${{ inputs.runs-on && fromJson(inputs.runs-on) || 'ubuntu-latest' }}
permissions: {}
outputs:
container-image: ${{ steps.parse.outputs.container-image }}
container-env: ${{ steps.parse.outputs.container-env }}
container-options: ${{ steps.parse.outputs.container-options }}
container-ports: ${{ steps.parse.outputs.container-ports }}
container-volumes: ${{ steps.parse.outputs.container-volumes }}
container-username: ${{ steps.parse.outputs.container-username }}
path-mapping: ${{ steps.parse.outputs.path-mapping }}
package-enabled: ${{ steps.package-config.outputs.enabled }}
package-manifest-prefix: ${{ steps.package-config.outputs.manifest-prefix }}
package-directories: ${{ steps.package-config.outputs.directories }}
package-tests: ${{ steps.package-config.outputs.tests }}
package-test-project: ${{ steps.package-config.outputs.test-project }}
working-directory: ${{ steps.build-variables.outputs.working-directory }}
build-env: ${{ steps.build-variables.outputs.env }}
build-commands: ${{ steps.build-variables.outputs.commands }}
build-artifact: ${{ steps.build-variables.outputs.artifact }}
test-enabled: ${{ steps.test-options.outputs.enabled }}
test-command: ${{ steps.test-options.outputs.command }}
test-coverage: ${{ steps.test-options.outputs.coverage }}
test-comment: ${{ steps.test-options.outputs.comment }}
test-report-group: ${{ steps.test-options.outputs.report-group }}
test-report-file: ${{ steps.test-options.outputs.report-file }}
test-arguments: ${{ steps.test-options.outputs.arguments }}
test-shards: ${{ steps.test-options.outputs.shards }}
test-matrix: ${{ steps.test-options.outputs.matrix }}
test-group: ${{ steps.test-options.outputs.group }}
test-merge-command: ${{ steps.test-options.outputs.merge-command }}
steps:
- id: test-options
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
TEST_INPUT: ${{ inputs.test }}
with:
script: |
const testInput = process.env.TEST_INPUT.trim();
const enabled = !['', 'null', 'false'].includes(testInput);
let testOptions = {};
if (enabled && testInput !== 'true') {
try {
const parsed = JSON.parse(testInput);
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new Error('test must be true, disabled, or a JSON object.');
}
testOptions = parsed;
} catch (error) {
core.setFailed(`Failed to parse test input as JSON: ${error.message}`);
return;
}
}
if (testOptions.coverage === undefined) {
testOptions.coverage = 'github';
}
if (testOptions.comment !== undefined && typeof testOptions.comment !== 'boolean') {
throw new Error('test.comment must be a boolean.');
}
if (testOptions['report-group'] !== undefined &&
(typeof testOptions['report-group'] !== 'string' || !/^[\w-]+$/.test(testOptions['report-group']))) {
throw new Error('test.report-group must be a job ID containing letters, numbers, underscores or hyphens.');
}
const shards = testOptions.shards === undefined ? 1 : testOptions.shards;
if (!Number.isInteger(shards) || shards < 1 || shards > 256) {
throw new Error('test.shards must be an integer from 1 to 256.');
}
const args = testOptions.arguments === undefined ? [] : testOptions.arguments;
if (!Array.isArray(args) || args.some(arg => typeof arg !== 'string' || arg.includes('\0'))) {
throw new Error('test.arguments must be an array of strings without null bytes.');
}
for (const key of ['command', 'merge-command']) {
if (testOptions[key] !== undefined && !(key === 'command' && testOptions[key] === '') && (typeof testOptions[key] !== 'string' || !testOptions[key].trim())) {
throw new Error(`test.${key} must be a nonempty package-script name.`);
}
}
core.setOutput('enabled', enabled);
core.setOutput('shards', shards);
core.setOutput('matrix', { shard: Array.from({ length: shards }, (_, i) => i + 1) });
core.setOutput('group', shards > 1 ? require('node:crypto').randomUUID() : '');
core.setOutput('arguments', args);
core.setOutput('merge-command', testOptions['merge-command'] || testOptions.command || 'test:ci');
core.setOutput('coverage', testOptions.coverage );
core.setOutput('comment', testOptions.comment ?? true);
core.setOutput('report-group', testOptions['report-group'] || '');
core.setOutput('report-file', testOptions['report-file'] || '');
core.setOutput('command', testOptions.command || 'test:ci');
- id: package-config
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
PACKAGE_INPUT: ${{ inputs.package }}
CONTAINER_INPUT: ${{ inputs.container }}
with:
script: |
let config;
try {
config = JSON.parse(process.env.PACKAGE_INPUT.trim() || 'false');
} catch {
throw new Error('package must be true, false, or a JSON object.');
}
if (typeof config !== 'boolean' && (!config || typeof config !== 'object' || Array.isArray(config))) {
throw new Error('package must be true, false, or a JSON object.');
}
const enabled = config !== false;
if (typeof config === 'boolean') config = {};
const allowed = ['directories', 'tests', 'test-project'];
const unknown = Object.keys(config).filter(key => !allowed.includes(key));
if (unknown.length) throw new Error(`Unknown package options: ${unknown.join(', ')}.`);
const { directories, tests = '', 'test-project': testProject = '' } = config;
if (typeof tests !== 'string' || typeof testProject !== 'string') {
throw new Error('package.tests and package.test-project must be strings.');
}
const path = require('node:path');
const relativeDirectory = value => typeof value === 'string' && value.trim() !== '' &&
!path.posix.isAbsolute(value) && !path.win32.isAbsolute(value) &&
!value.split(/[\\/]/).includes('..') && !/[\r\n\0]/.test(value);
if (directories !== undefined && (!Array.isArray(directories) || !directories.length || directories.length > 256 ||
directories.some(directory => !relativeDirectory(directory)) || new Set(directories).size !== directories.length)) {
throw new Error('package.directories must contain 1 to 256 unique relative directories inside the project.');
}
if (testProject && !relativeDirectory(testProject)) throw new Error('package.test-project must be a directory inside the project.');
if (testProject && !tests.trim()) throw new Error('package.test-project requires package.tests.');
if (enabled && process.env.CONTAINER_INPUT.trim()) {
throw new Error('Package validation requires non-container CI with the default Ubuntu artifact layout.');
}
core.setOutput('enabled', enabled);
core.setOutput('manifest-prefix', `ci-package-manifest-${require('node:crypto').randomUUID()}`);
core.setOutput('directories', directories === undefined ? '' : directories);
core.setOutput('tests', tests);
core.setOutput('test-project', testProject);
- id: parse
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
CONTAINER_INPUT: ${{ inputs.container }}
CONTAINER_PASSWORD: ${{ secrets.container-password }}
WORKING_DIRECTORY: ${{ inputs.working-directory }}
with:
script: |
const containerInput = process.env.CONTAINER_INPUT.trim();
if (!containerInput) {
return;
}
core.debug(`Container input: ${containerInput}`);
// Check if input is a JSON object or a simple string
const isJson = containerInput.startsWith('{');
let container = {
options: '--user root:root'
};
let pathMapping = {
[process.env.WORKING_DIRECTORY || '.']: process.env.GITHUB_WORKSPACE,
};
if (isJson) {
try {
const {pathMapping: parsedPathMapping, ...parsedContainer} = JSON.parse(containerInput);
core.debug(`Parsed container input as JSON: ${JSON.stringify(parsedContainer)}`);
container = {
...container,
...parsedContainer,
options: `${container.options} ${parsedContainer.options || ''}`.trim()
};
core.debug(`Parsed path mapping: ${JSON.stringify(parsedPathMapping)}`);
if (parsedPathMapping){
pathMapping = parsedPathMapping;
}
} catch (error) {
return core.setFailed(`Failed to parse container input as JSON: ${error.message}`,{ cause: error });
}
} else {
// Simple string format - just the image name
container.image = containerInput;
}
core.debug(`Parsed container configuration: ${JSON.stringify(container)}`);
if (!container.image) {
return core.setFailed('Container image must be specified in the container input.');
}
core.setOutput('container-image', container.image);
if (container.env) {
core.setOutput('container-env', JSON.stringify(container.env));
}
if (container.options) {
core.setOutput('container-options', container.options);
}
if (container.ports) {
core.setOutput('container-ports', JSON.stringify(container.ports));
}
if (container.volumes) {
core.setOutput('container-volumes', JSON.stringify(container.volumes));
}
if (container.credentials?.username) {
core.setOutput('container-username', container.credentials.username);
if (!process.env.CONTAINER_PASSWORD) {
return core.setFailed('Container password must be provided when container credentials username is specified.');
}
} else if (process.env.CONTAINER_PASSWORD) {
return core.setFailed('Container credentials username must be provided when container password is specified.');
}
core.debug(`Parsed path mapping: ${JSON.stringify(pathMapping)}`);
if (!pathMapping || typeof pathMapping !== 'object' || Object.keys(pathMapping).length === 0){
return core.setFailed('At least one path mapping must be specified in the container configuration.');
}
core.setOutput('path-mapping', Object.entries(pathMapping).reduce((acc, [containerPath, repoPath]) => {
acc += `${acc?',' : ''}${containerPath}:${repoPath}`;
return acc;
}, ""));
- id: build-variables
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
WORKING_DIRECTORY: ${{ inputs.working-directory }}
BUILD_INPUT: ${{ inputs.build }}
with:
script: |
const path = require('node:path');
const workingDirectory = path.normalize(process.env.WORKING_DIRECTORY || '.');
core.setOutput('working-directory', workingDirectory);
const buildInput = process.env.BUILD_INPUT.trim();
if (!buildInput) {
core.setOutput('commands', '');
core.setOutput('env', '{}');
return;
}
let commands = [];
let env = {};
// Build commands is a list of command(s), one per line.
const buildCommandsIsList = !buildInput.trim().startsWith('{') && !buildInput.trim().startsWith('[');
if (buildCommandsIsList) {
commands = buildInput.split('\n').map(command => command.trim()).filter(Boolean);
} else {
let build;
try {
build = JSON.parse(buildInput);
} catch (error) {
core.setFailed(`Failed to parse build input as JSON: ${error.message}`);
return;
}
// Build commands is a JSON array of commands
if (Array.isArray(build)) {
commands = build;
}
// Build commands is a JSON object
else {
commands = build.commands ?? ["build"];
env = build.env ?? {};
if (build.artifact) {
let buildArtifact = build.artifact;
if (typeof buildArtifact === 'string' || Array.isArray(buildArtifact)) {
buildArtifact = {
paths: buildArtifact
};
}
if (!buildArtifact || typeof buildArtifact !== 'object') {
return core.setFailed('Build artifact must be a path, path array or options object');
}
if (typeof buildArtifact.paths === 'string') {
buildArtifact.paths = buildArtifact.paths.split('\n');
}
if (!Array.isArray(buildArtifact.paths) || buildArtifact.paths.some(artifact => typeof artifact !== 'string')) {
return core.setFailed('Build artifact paths must be a string or an array of strings');
}
buildArtifact.paths = buildArtifact.paths
.map(artifact => artifact.trim())
.filter(Boolean)
.join('\n');
if (!buildArtifact.paths) {
return core.setFailed('No valid build artifact paths found');
}
// Generate a unique name for the artifact
buildArtifact.name = `${process.env.GITHUB_JOB}-build-${process.env.GITHUB_RUN_ID}-${Math.random().toString(36).substring(2, 8)}`;
core.setOutput('artifact', JSON.stringify(buildArtifact));
}
}
}
if (!Array.isArray(commands) || commands.some(command => typeof command !== 'string')) {
core.setFailed('Build commands array must only contain strings');
return;
}
if (!env || typeof env !== 'object' || Array.isArray(env)) {
return core.setFailed('Build env must be an object');
}
const sanitizedCommands = commands.map(command => command.trim()).filter(Boolean);
if (!sanitizedCommands.length) {
return core.setFailed('No build commands found');
}
core.setOutput('commands', sanitizedCommands.join('\n'));
core.setOutput('env', JSON.stringify(env));
code-ql:
name: 🛡️ CodeQL Analysis
if: inputs.checks == true && inputs.code-ql != ''
permissions:
security-events: write
runs-on: *ci-runner
steps:
- uses: hoverkraft-tech/ci-github-common/actions/checkout@af0bdd6313bd49aaf4a8a7f0de005fb0db856b03 # 4.3.3
- id: code-ql-options
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
CODE_QL: ${{ inputs.code-ql }}
with:
script: |
const input = process.env.CODE_QL.trim();
let options = { languages: input };
if (input.startsWith('{')) {
try {
options = JSON.parse(input);
} catch {
return core.setFailed('code-ql must be a language string or a valid JSON object.');
}
}
if (Object.keys(options).some(key => !['languages', 'config-file'].includes(key))) {
return core.setFailed('code-ql supports only languages and config-file.');
}
if (typeof options.languages !== 'string' || !options.languages.trim()) {
return core.setFailed('code-ql.languages must be a nonempty string.');
}
if (options['config-file'] !== undefined && typeof options['config-file'] !== 'string') {
return core.setFailed('code-ql.config-file must be a string.');
}
core.setOutput('languages', options.languages);
core.setOutput('config-file', options['config-file'] ?? '');
- uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
with:
languages: ${{ steps.code-ql-options.outputs.languages }}
config-file: ${{ steps.code-ql-options.outputs.config-file }}
- uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
dependency-review:
name: 🛡️ Dependency Review
if: github.event_name == 'pull_request' && inputs.checks == true && inputs.dependency-review
permissions:
contents: read
runs-on: *ci-runner
steps:
- uses: hoverkraft-tech/ci-github-common/actions/checkout@af0bdd6313bd49aaf4a8a7f0de005fb0db856b03 # 4.3.3
- uses: actions/dependency-review-action@bbc44d14a204704ccc493733616cd1e93a0321ec # v5.0.1
lint:
if: inputs.checks == true && inputs.lint
name: 👕 Lint
runs-on: *ci-runner
container: &ci-container
image: ${{ needs.prepare.outputs.container-image || '' }}
env: ${{ fromJSON(needs.prepare.outputs.container-env || '{}') }}
options: ${{ needs.prepare.outputs.container-options || ' ' }}
ports: ${{ fromJSON(needs.prepare.outputs.container-ports || '[]') }}
volumes: ${{ fromJSON(needs.prepare.outputs.container-volumes || '[]') }}
credentials: ${{ fromJSON(needs.prepare.outputs.container-username && format('{{"username":{0},"password":{1}}}',toJSON(needs.prepare.outputs.container-username),toJSON(secrets.container-password)) || '{}') }}
needs:
- prepare
permissions:
contents: read
packages: read
steps:
- uses: hoverkraft-tech/ci-github-common/actions/checkout@af0bdd6313bd49aaf4a8a7f0de005fb0db856b03 # 4.3.3
if: inputs.container == ''
- id: preparel-lint-options
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
LINT_INPUT: ${{ inputs.lint }}
with:
script: |
const lintInput = process.env.LINT_INPUT.trim();
let lintOptions = {};
if (lintInput && lintInput !== 'true') {
try {
const parsed = JSON.parse(lintInput);
lintOptions = { ...lintOptions, ...parsed };
} catch (error) {
core.setFailed(`Failed to parse lint input as JSON: ${error.message}`);
return;
}
}
core.setOutput('command', lintOptions.command || 'lint:ci');
core.setOutput('report-file', lintOptions['report-file'] || '');
- name: Run lint
uses: $/actions/lint
with:
ignore-scripts: ${{ inputs.ignore-scripts }}
working-directory: ${{ needs.prepare.outputs.working-directory }}
container: ${{ inputs.container != '' && 'true' || 'false' }}
command: ${{ steps.preparel-lint-options.outputs.command }}
report-file: ${{ steps.preparel-lint-options.outputs.report-file }}
path-mapping: ${{ needs.prepare.outputs.path-mapping || '' }}
build:
if: inputs.checks == true && needs.prepare.outputs.build-commands != ''
name: 🏗️ Build
runs-on: *ci-runner
container: *ci-container
needs:
- prepare
permissions:
contents: read
packages: read
outputs:
artifact-id: ${{ steps.build.outputs.artifact-id }}
steps:
- uses: hoverkraft-tech/ci-github-common/actions/checkout@af0bdd6313bd49aaf4a8a7f0de005fb0db856b03 # 4.3.3
if: inputs.container == ''
- id: build-artifact
if: needs.prepare.outputs.build-artifact
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
WORKING_DIRECTORY: ${{ needs.prepare.outputs.working-directory }}
BUILD_ARTIFACT: ${{ needs.prepare.outputs.build-artifact }}
with:
script: |
const path = require('node:path');
const workingDirectory = path.resolve(process.env.GITHUB_WORKSPACE, process.env.WORKING_DIRECTORY);
const artifact = JSON.parse(process.env.BUILD_ARTIFACT);
artifact.paths = artifact.paths.split('\n').map(artifactPath => {
const fullPath = path.resolve(workingDirectory, artifactPath);
// Preserve the full directory layout used by artifact consumers.
return fullPath.replace(/\/([^/]+)/, '/*$1');
}).join('\n');
core.setOutput('artifact', JSON.stringify(artifact));
- id: build
uses: $/actions/build
with:
ignore-scripts: ${{ inputs.ignore-scripts }}
container: ${{ inputs.container != '' && 'true' || 'false' }}
working-directory: ${{ needs.prepare.outputs.working-directory }}
build-secrets: ${{ secrets.build-secrets }}
build-commands: ${{ needs.prepare.outputs.build-commands }}
build-env: ${{ needs.prepare.outputs.build-env }}
build-artifact: ${{ steps.build-artifact.outputs.artifact }}
test:
if: >-
${{ !cancelled() && inputs.checks == true && inputs.test && needs.prepare.outputs.test-enabled == 'true' &&
needs.prepare.result == 'success' &&
(needs.build.result == 'success' ||
(needs.build.result == 'skipped' && needs.prepare.outputs.build-commands == '')) }}
name: ${{ needs.prepare.outputs.test-shards == '1' && '🧪 Test' || format('🧪 Test shard {0}/{1}', matrix.shard, needs.prepare.outputs.test-shards) }}
runs-on: *ci-runner
container: *ci-container
needs:
- prepare
- build
permissions:
contents: read
id-token: write # Required for Codecov uploads with OIDC authentication
packages: read
pull-requests: write
strategy:
fail-fast: false
max-parallel: ${{ fromJSON(needs.prepare.outputs.test-shards) }}
matrix: ${{ fromJSON(needs.prepare.outputs.test-matrix) }}
steps:
- uses: hoverkraft-tech/ci-github-common/actions/checkout@af0bdd6313bd49aaf4a8a7f0de005fb0db856b03 # 4.3.3
if: inputs.container == ''
- if: needs.build.outputs.artifact-id && inputs.container == ''
uses: hoverkraft-tech/ci-github-common/actions/download-artifact@af0bdd6313bd49aaf4a8a7f0de005fb0db856b03 # 4.3.3
with:
artifact-ids: ${{ needs.build.outputs.artifact-id }}
path: "/"
- name: Run tests
uses: $/actions/test
with:
ignore-scripts: ${{ inputs.ignore-scripts }}
working-directory: ${{ needs.prepare.outputs.working-directory }}
container: ${{ inputs.container != '' && 'true' || 'false' }}
command: ${{ needs.prepare.outputs.test-command }}
arguments: ${{ needs.prepare.outputs.test-arguments }}
shard: ${{ needs.prepare.outputs.test-shards != '1' && format('{0}/{1}', matrix.shard, needs.prepare.outputs.test-shards) || '' }}
shard-group: ${{ format('ci-test-{0}-{1}-{2}', github.run_id, github.run_attempt, needs.prepare.outputs.test-group) }}
coverage: ${{ needs.prepare.outputs.test-coverage }}
comment: ${{ needs.prepare.outputs.test-comment }}
report-group: ${{ needs.prepare.outputs.test-report-group }}
report-file: ${{ needs.prepare.outputs.test-report-file }}
path-mapping: ${{ needs.prepare.outputs.path-mapping || '' }}
github-token: ${{ secrets.github-token || github.token }}
test-merge:
name: Merge test results
if: >-
${{ !cancelled() && inputs.checks == true && inputs.test &&
needs.prepare.result == 'success' && needs.prepare.outputs.test-shards != '1' &&
(needs.test.result == 'success' || needs.test.result == 'failure') }}
needs: [prepare, build, test]
runs-on: *ci-runner
container: *ci-container
permissions:
contents: read
id-token: write
packages: read
pull-requests: write
steps:
- uses: hoverkraft-tech/ci-github-common/actions/checkout@af0bdd6313bd49aaf4a8a7f0de005fb0db856b03 # 4.3.3
if: inputs.container == ''
- if: needs.build.outputs.artifact-id && inputs.container == ''
uses: hoverkraft-tech/ci-github-common/actions/download-artifact@af0bdd6313bd49aaf4a8a7f0de005fb0db856b03 # 4.3.3
with:
artifact-ids: ${{ needs.build.outputs.artifact-id }}
path: "/"
- name: Merge tests and publish reports
uses: $/actions/test
with:
ignore-scripts: ${{ inputs.ignore-scripts }}
working-directory: ${{ needs.prepare.outputs.working-directory }}
container: ${{ inputs.container != '' && 'true' || 'false' }}
command: ${{ needs.prepare.outputs.test-merge-command }}
arguments: ${{ needs.prepare.outputs.test-arguments }}
merge-shards: ${{ needs.prepare.outputs.test-shards }}
shard-group: ${{ format('ci-test-{0}-{1}-{2}', github.run_id, github.run_attempt, needs.prepare.outputs.test-group) }}
coverage: ${{ needs.prepare.outputs.test-coverage }}
comment: ${{ needs.prepare.outputs.test-comment }}
report-group: ${{ needs.prepare.outputs.test-report-group }}
report-file: ${{ needs.prepare.outputs.test-report-file }}
path-mapping: ${{ needs.prepare.outputs.path-mapping || '' }}
github-token: ${{ secrets.github-token || github.token }}
- name: Require successful shards
if: always()
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
SHARD_RESULT: ${{ needs.test.result }}
with:
script: |
if (process.env.SHARD_RESULT !== 'success') {
core.setFailed('Every test shard must succeed, including setup and artifact upload.');
}
discover-packages:
name: Discover public packages
if: inputs.checks == true && needs.prepare.outputs.package-enabled == 'true'
needs: prepare
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
directories: ${{ steps.packages.outputs.directories }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- id: working-directory
uses: hoverkraft-tech/ci-github-common/actions/working-directory@af0bdd6313bd49aaf4a8a7f0de005fb0db856b03 # 4.3.3
with:
working-directory: ${{ needs.prepare.outputs.working-directory }}
- id: packages
uses: $/actions/package/discover
with:
working-directory: ${{ steps.working-directory.outputs.absolute-path }}
directories: ${{ needs.prepare.outputs.package-directories }}
package:
name: Create package ${{ matrix.directory }}
if: >-
${{ !cancelled() && inputs.checks == true && needs.prepare.outputs.package-enabled == 'true' &&
needs.prepare.result == 'success' && needs.discover-packages.result == 'success' &&
(needs.build.result == 'success' ||
(needs.build.result == 'skipped' && needs.prepare.outputs.build-commands == '')) }}
needs: [prepare, discover-packages, build]
runs-on: ubuntu-latest
permissions:
contents: read
strategy:
fail-fast: false
matrix:
directory: ${{ fromJSON(needs.discover-packages.outputs.directories) }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- id: setup-node
uses: $/actions/setup-node
with:
working-directory: ${{ inputs.working-directory }}
install-dependencies: "false"
- name: Link pnpm workspace dependencies
if: steps.setup-node.outputs.package-manager == 'pnpm'
working-directory: ${{ inputs.working-directory }}
run: pnpm install --frozen-lockfile --ignore-scripts
- name: Package prepared files
id: package
uses: $/actions/package/create
with:
working-directory: ${{ inputs.working-directory }}
package-directory: ${{ matrix.directory }}
build-artifact-id: ${{ needs.build.outputs.artifact-id }}
build-artifact-path: /
- name: Record package artifact
id: report
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
DIRECTORY: ${{ matrix.directory }}
PROJECT: ${{ inputs.working-directory }}
ARTIFACT_ID: ${{ steps.package.outputs.package-tarball-artifact-id }}
TARBALL: ${{ steps.package.outputs.package-tarball-path }}
with:
script: |
const fs = require('node:fs');
const path = require('node:path');
const report = path.join(process.env.RUNNER_TEMP, `${process.env.ARTIFACT_ID}.json`);
fs.writeFileSync(report, JSON.stringify({ directory: process.env.DIRECTORY, project: process.env.PROJECT, artifactId: process.env.ARTIFACT_ID, tarball: path.basename(process.env.TARBALL), attempt: Number(process.env.GITHUB_RUN_ATTEMPT) }));
core.setOutput('path', report);
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: ${{ needs.prepare.outputs.package-manifest-prefix }}-${{ steps.package.outputs.package-tarball-artifact-id }}
path: ${{ steps.report.outputs.path }}
if-no-files-found: error
package-manifests:
name: Collect package artifacts
if: >-
${{ !cancelled() && inputs.checks == true && needs.prepare.outputs.package-enabled == 'true' &&
needs.prepare.result == 'success' && needs.discover-packages.result == 'success' &&
needs.package.result == 'success' }}
needs: [prepare, discover-packages, package]
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
artifact-id: ${{ steps.collect.outputs.artifact-id }}
artifacts: ${{ steps.collect.outputs.artifacts }}
artifact-ids: ${{ steps.collect.outputs.artifact-ids }}
matrix: ${{ steps.collect.outputs.matrix }}
steps:
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
pattern: ${{ needs.prepare.outputs.package-manifest-prefix }}-*
merge-multiple: true
path: ${{ runner.temp }}/package-validation
- id: collect
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
DIRECTORIES: ${{ needs.discover-packages.outputs.directories }}
PROJECT: ${{ inputs.working-directory }}
REPORT_DIRECTORY: ${{ runner.temp }}/package-validation
with:
script: |
const fs = require('node:fs');
const path = require('node:path');
const directories = JSON.parse(process.env.DIRECTORIES);
const files = await (await glob.create(path.join(process.env.REPORT_DIRECTORY, '*.json'), { followSymbolicLinks: false, matchDirectories: false })).glob();
const reports = files.map(file => JSON.parse(fs.readFileSync(file, 'utf8'))).filter(report => report.project === process.env.PROJECT);
const matrix = directories.map(directory => {
const matches = reports.filter(report => report.directory === directory).sort((a, b) => b.attempt - a.attempt);
const latest = matches[0];
if (!latest || !/^[1-9][0-9]*$/.test(latest.artifactId) || !Number.isSafeInteger(Number(latest.artifactId)) || !/^[a-zA-Z0-9._-]+\.tgz$/.test(latest.tarball || '') ||
!Number.isSafeInteger(latest.attempt) || latest.attempt < 1 ||
(matches[1] && latest.attempt === matches[1].attempt)) {
throw new Error(`Expected one package artifact for ${directory}.`);
}
return { directory, artifactId: latest.artifactId, tarball: latest.tarball };
});
const artifacts = Object.fromEntries(matrix.map(item => [item.directory, item.artifactId]));
core.setOutput('matrix', matrix);
core.setOutput('artifact-ids', matrix.map(item => item.artifactId).join(','));
core.setOutput('artifacts', artifacts);
if (directories.length === 1) core.setOutput('artifact-id', artifacts[directories[0]]);
package-validation:
name: Validate package ${{ matrix.directory }}
if: ${{ !cancelled() && needs.package-manifests.result == 'success' }}
needs: [prepare, package-manifests]
runs-on: ubuntu-latest
permissions:
contents: read
strategy:
fail-fast: false
matrix:
include: ${{ fromJSON(needs.package-manifests.outputs.matrix) }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: $/actions/setup-node
with:
working-directory: ${{ inputs.working-directory }}
install-dependencies: "false"
- name: Download workspace tarballs
uses: hoverkraft-tech/ci-github-common/actions/download-artifact@af0bdd6313bd49aaf4a8a7f0de005fb0db856b03 # 4.3.3
with:
artifact-ids: ${{ needs.package-manifests.outputs.artifact-ids }}
path: ${{ runner.temp }}/workspace-tarballs
skip-decompress: true
merge-multiple: true
- id: tarballs
name: Locate package and dependency tarballs
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
TARBALL_NAME: ${{ matrix.tarball }}
with:
script: |
const path = require('node:path');
const files = await (await glob.create(path.join(process.env.RUNNER_TEMP, 'workspace-tarballs', '**/*.tgz'), {
followSymbolicLinks: false, matchDirectories: false,
})).glob();
const matches = files.filter(file => path.basename(file) === process.env.TARBALL_NAME);
if (matches.length !== 1) throw new Error('Expected exactly one target package tarball.');
core.setOutput('target', matches[0]);
core.setOutput('dependencies', files.filter(file => file !== matches[0]));
- name: Test the package as a consumer
uses: $/actions/package/test
with:
working-directory: ${{ inputs.working-directory }}