Repository navigation
805 lines (728 loc) · 34 KB
/
Copy pathcontinuous-integration.yml
File metadata and controls
805 lines (728 loc) · 34 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
# 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. Must be a string or a JSON object.
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.
The consumer is cleaned up on success or failure. Commands must not modify the tarball.
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.
Example:
```json:package.json
{
"test:ci": "vitest run --reporter=default --reporter=junit --outputFile=junit.xml --coverage.enabled --coverage.reporter=lcov --coverage.reporter=text"
}
```
type: string
required: false
default: "true"
working-directory:
description: "Working directory where the dependencies are installed."
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-directories: ${{ steps.package-config.outputs.directories }}
package-tests: ${{ steps.package-config.outputs.tests }}
package-test-project: ${{ steps.package-config.outputs.test-project }}
steps:
- 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('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;
}, ""));
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@5fbb531db839a26ebcc35c4946be279f945f7633 # 1.0.0
- 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@5fbb531db839a26ebcc35c4946be279f945f7633 # 1.0.0
- uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0
setup:
name: ⚙️ Setup
runs-on: *ci-runner
needs:
- prepare
permissions:
contents: read
packages: read
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)) || '{}') }}
outputs:
working-directory: ${{ steps.working-directory.outputs.absolute-path }}
build-env: ${{ steps.build-variables.outputs.env }}
build-commands: ${{ steps.build-variables.outputs.commands }}
build-artifact: ${{ steps.build-variables.outputs.artifact }}
package-directories: ${{ steps.packages.outputs.directories }}
steps:
- name: Checkout repository
if: inputs.container == ''
uses: hoverkraft-tech/ci-github-common/actions/checkout@5fbb531db839a26ebcc35c4946be279f945f7633 # 1.0.0
- id: working-directory
uses: hoverkraft-tech/ci-github-common/actions/working-directory@5fbb531db839a26ebcc35c4946be279f945f7633 # 1.0.0
with:
working-directory: ${{ inputs.working-directory }}
enforce-path-in-workspace: ${{ inputs.container && 'false' || 'true' }}
- name: Discover public packages
id: packages
if: inputs.checks == true && needs.prepare.outputs.package-enabled == 'true'
uses: $/actions/package/discover
with:
working-directory: ${{ steps.working-directory.outputs.absolute-path }}
directories: ${{ needs.prepare.outputs.package-directories }}
- id: build-variables
if: inputs.build != ''
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
WORKING_DIRECTORY: ${{ steps.working-directory.outputs.absolute-path }}
BUILD_INPUT: ${{ inputs.build }}
with:
script: |
const path = require('node:path');
const workingDirectory = process.env.WORKING_DIRECTORY;
const buildInput = process.env.BUILD_INPUT.trim();
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) {
buildArtifact = build.artifact;
if (typeof buildArtifact === 'string' || Array.isArray(buildArtifact)) {
buildArtifact = {
paths: buildArtifact
};
}
if (typeof buildArtifact.paths === 'string') {
buildArtifact.paths = buildArtifact.paths.split('\n');
} else if (!Array.isArray(buildArtifact.paths)) {
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)
.map(artifact => {
// FIXME: Workaround to preserve full path to artifact
const fullpath = artifact.startsWith('/') ? artifact : path.join(workingDirectory, artifact);
// Add a wildcard to the first folder of the path
return fullpath.replace(/\/([^/]+)/, '/*$1');
}).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 (commands.some(command => typeof command !== 'string')) {
core.setFailed('Build commands array must only contain strings');
return;
}
const sanitizedCommands = commands.map(command => command.trim()).filter(Boolean);
if (!sanitizedCommands.length) {
core.setFailed('No build commands found');
}
core.setOutput('commands', sanitizedCommands.join('\n'));
core.setOutput('env', JSON.stringify(env));
lint:
if: inputs.checks == true && inputs.lint
name: 👕 Lint
runs-on: *ci-runner
container: *ci-container
needs:
- prepare
- setup
permissions:
contents: read
packages: read
steps:
- uses: hoverkraft-tech/ci-github-common/actions/checkout@5fbb531db839a26ebcc35c4946be279f945f7633 # 1.0.0
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.setup.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
name: 🏗️ Build
runs-on: *ci-runner
container: *ci-container
needs:
- prepare
- setup
permissions:
contents: read
packages: read
outputs:
artifact-id: ${{ steps.build.outputs.artifact-id }}
steps:
- uses: hoverkraft-tech/ci-github-common/actions/checkout@5fbb531db839a26ebcc35c4946be279f945f7633 # 1.0.0
if: needs.setup.outputs.build-commands && inputs.container == ''
- id: build
if: needs.setup.outputs.build-commands
uses: $/actions/build
with:
ignore-scripts: ${{ inputs.ignore-scripts }}
container: ${{ inputs.container != '' && 'true' || 'false' }}
working-directory: ${{ needs.setup.outputs.working-directory }}
build-secrets: ${{ secrets.build-secrets }}
build-commands: ${{ needs.setup.outputs.build-commands }}
build-env: ${{ needs.setup.outputs.build-env }}
build-artifact: ${{ needs.setup.outputs.build-artifact }}
test:
if: inputs.checks == true && inputs.test
name: 🧪 Test
runs-on: *ci-runner
container: *ci-container
needs:
- prepare
- setup
- build
permissions:
contents: read
id-token: write # Required for Codecov uploads with OIDC authentication
packages: read
pull-requests: write
steps:
- uses: hoverkraft-tech/ci-github-common/actions/checkout@5fbb531db839a26ebcc35c4946be279f945f7633 # 1.0.0
if: inputs.container == ''
- if: needs.build.outputs.artifact-id && inputs.container == ''
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
artifact-ids: ${{ needs.build.outputs.artifact-id }}
path: "/"
- id: prepare-test-options
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
TEST_INPUT: ${{ inputs.test }}
with:
script: |
const testInput = process.env.TEST_INPUT.trim();
let testOptions = {};
if (testInput && testInput !== 'true') {
try {
const parsed = JSON.parse(testInput);
testOptions = { ...testOptions, ...parsed };
} catch (error) {
core.setFailed(`Failed to parse test input as JSON: ${error.message}`);
return;
}
}
if (testOptions.coverage === undefined) {
testOptions.coverage = 'github';
}
core.setOutput('coverage', testOptions.coverage );
core.setOutput('report-file', testOptions['report-file'] || '');
core.setOutput('command', testOptions.command || 'test:ci');
- name: Run tests
uses: $/actions/test
with:
ignore-scripts: ${{ inputs.ignore-scripts }}
working-directory: ${{ needs.setup.outputs.working-directory }}
container: ${{ inputs.container != '' && 'true' || 'false' }}
command: ${{ steps.prepare-test-options.outputs.command }}
coverage: ${{ steps.prepare-test-options.outputs.coverage }}
report-file: ${{ steps.prepare-test-options.outputs.report-file }}
path-mapping: ${{ needs.prepare.outputs.path-mapping || '' }}
github-token: ${{ secrets.github-token || github.token }}
package:
name: Validate package ${{ matrix.directory }}
if: inputs.checks == true && needs.prepare.outputs.package-enabled == 'true'
needs: [prepare, setup, build]
runs-on: ubuntu-latest
permissions:
contents: read
strategy:
fail-fast: false
matrix:
directory: ${{ fromJSON(needs.setup.outputs.package-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: Test the package as a consumer
uses: $/actions/package/test
with:
working-directory: ${{ inputs.working-directory }}
tarball-path: ${{ steps.package.outputs.package-tarball-path }}
commands: ${{ needs.prepare.outputs.package-tests }}
test-project: ${{ needs.prepare.outputs.package-test-project }}
- name: Validate npm publication without publishing
uses: $/actions/package/publish
with:
package-tarball-artifact-id: ${{ steps.package.outputs.package-tarball-artifact-id }}
dry-run: "true"
provenance: "false"
github-token: ""
- name: Record successful validation
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 }}
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, attempt: Number(process.env.GITHUB_RUN_ATTEMPT) }));
core.setOutput('path', report);
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: ci-package-validation-${{ steps.package.outputs.package-tarball-artifact-id }}
path: ${{ steps.report.outputs.path }}
if-no-files-found: error
package-results:
name: Collect validated packages
if: inputs.checks == true && needs.prepare.outputs.package-enabled == 'true'
needs: [prepare, setup, package]
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
artifact-id: ${{ steps.collect.outputs.artifact-id }}
artifacts: ${{ steps.collect.outputs.artifacts }}
steps:
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
pattern: ci-package-validation-*
merge-multiple: true
path: ${{ runner.temp }}/package-validation
- id: collect
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
env:
DIRECTORIES: ${{ needs.setup.outputs.package-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 artifacts = Object.fromEntries(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)) ||
!Number.isSafeInteger(latest.attempt) || latest.attempt < 1 ||
(matches[1] && latest.attempt === matches[1].attempt)) {
throw new Error(`Expected one validated package result for ${directory}.`);
}
return [directory, latest.artifactId];
}));
core.setOutput('artifacts', artifacts);
if (directories.length === 1) core.setOutput('artifact-id', artifacts[directories[0]]);