-
Notifications
You must be signed in to change notification settings - Fork 0
627 lines (552 loc) · 23.9 KB
/
continuous-integration.yml
File metadata and controls
627 lines (552 loc) · 23.9 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
# Workflow to performs continuous integration steps agains a Node.js project:
#
# - CodeQL analysis
# - Linting
# - Build
# - Test
name: Node.js Continuous Integration
on:
workflow_call:
inputs:
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"
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: |
Code QL analysis language.
See https://github.com/github/codeql-action.
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:
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 }}
steps:
- id: parse
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.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@b17226e57c8ef31f860719766656ebb6df017218 # 0.31.6
- uses: github/codeql-action/init@5d4e8d1aca955e8d8589aabd499c5cae939e33c7 # v4.31.9
with:
languages: ${{ inputs.code-ql }}
- uses: github/codeql-action/analyze@5d4e8d1aca955e8d8589aabd499c5cae939e33c7 # v4.31.9
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@b17226e57c8ef31f860719766656ebb6df017218 # 0.31.6
- uses: actions/dependency-review-action@3c4e3dcb1aa7874d2c16be7d79418e9b7efd6261 # v4.8.2
setup:
name: ⚙️ Setup
runs-on: *ci-runner
needs:
- prepare
permissions:
contents: read
packages: read
# FIXME: This is a workaround for having workflow ref. See https://github.com/orgs/community/discussions/38659
id-token: write
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.working-directory }}
build-env: ${{ steps.build-variables.outputs.env }}
build-commands: ${{ steps.build-variables.outputs.commands }}
build-artifact: ${{ steps.build-variables.outputs.artifact }}
steps:
- name: Checkout repository
if: inputs.container == ''
uses: hoverkraft-tech/ci-github-common/actions/checkout@b17226e57c8ef31f860719766656ebb6df017218 # 0.31.6
- id: working-directory
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
WORKING_DIRECTORY_INPUT: ${{ inputs.working-directory }}
with:
script: |
const fs = require('node:fs');
const path = require('node:path');
let workingDirectory = process.env.WORKING_DIRECTORY_INPUT || '.';
if (!path.isAbsolute(workingDirectory)) {
workingDirectory = path.join(process.env.GITHUB_WORKSPACE, workingDirectory);
}
if (!fs.existsSync(workingDirectory)) {
core.setFailed(`The specified working directory does not exist: ${workingDirectory}`);
return;
}
workingDirectory = path.resolve(workingDirectory);
core.debug(`Running in working directory: ${workingDirectory}`);
core.setOutput('working-directory', workingDirectory);
- id: build-variables
if: inputs.build != ''
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
WORKING_DIRECTORY: ${{ steps.working-directory.outputs.working-directory }}
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
id-token: write # Needed for getting local workflow actions
steps:
- uses: hoverkraft-tech/ci-github-common/actions/checkout@b17226e57c8ef31f860719766656ebb6df017218 # 0.31.6
if: inputs.container == ''
- id: local-workflow-actions
uses: hoverkraft-tech/ci-github-common/actions/local-workflow-actions@b17226e57c8ef31f860719766656ebb6df017218 # 0.31.6
with:
actions-path: actions
- id: preparel-lint-options
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.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: ./self-workflow/actions/lint
with:
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 || '' }}
# jscpd:ignore-start
- uses: hoverkraft-tech/ci-github-common/actions/local-workflow-actions@b17226e57c8ef31f860719766656ebb6df017218 # 0.31.6
if: always() && steps.local-workflow-actions.outputs.repository
with:
actions-path: actions
repository: ${{ steps.local-workflow-actions.outputs.repository }}
ref: ${{ steps.local-workflow-actions.outputs.ref }}
# jscpd:ignore-end
build:
if: inputs.checks == true
name: 🏗️ Build
runs-on: *ci-runner
container: *ci-container
needs:
- prepare
- setup
permissions:
contents: read
packages: read
id-token: write # Needed for getting local workflow actions
outputs:
artifact-id: ${{ steps.build.outputs.artifact-id }}
steps:
- uses: hoverkraft-tech/ci-github-common/actions/checkout@b17226e57c8ef31f860719766656ebb6df017218 # 0.31.6
if: needs.setup.outputs.build-commands && inputs.container == ''
- id: local-workflow-actions
uses: hoverkraft-tech/ci-github-common/actions/local-workflow-actions@b17226e57c8ef31f860719766656ebb6df017218 # 0.31.6
with:
actions-path: actions
- id: build
if: needs.setup.outputs.build-commands
uses: ./self-workflow/actions/build
with:
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 }}
# jscpd:ignore-start
- uses: hoverkraft-tech/ci-github-common/actions/local-workflow-actions@b17226e57c8ef31f860719766656ebb6df017218 # 0.31.6
if: always() && steps.local-workflow-actions.outputs.repository
with:
actions-path: actions
repository: ${{ steps.local-workflow-actions.outputs.repository }}
ref: ${{ steps.local-workflow-actions.outputs.ref }}
# jscpd:ignore-end
test:
if: inputs.checks == true && inputs.test
name: 🧪 Test
runs-on: *ci-runner
container: *ci-container
needs:
- prepare
- setup
- build
permissions:
contents: read
pull-requests: write
packages: read
id-token: write # Needed for getting local workflow actions
steps:
- uses: hoverkraft-tech/ci-github-common/actions/checkout@b17226e57c8ef31f860719766656ebb6df017218 # 0.31.6
if: inputs.container == ''
- if: needs.build.outputs.artifact-id && inputs.container == ''
uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
with:
artifact-ids: ${{ needs.build.outputs.artifact-id }}
path: "/"
- id: local-workflow-actions
uses: hoverkraft-tech/ci-github-common/actions/local-workflow-actions@b17226e57c8ef31f860719766656ebb6df017218 # 0.31.6
with:
actions-path: actions
- id: prepare-test-options
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.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: ./self-workflow/actions/test
with:
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 }}
# jscpd:ignore-start
- uses: hoverkraft-tech/ci-github-common/actions/local-workflow-actions@b17226e57c8ef31f860719766656ebb6df017218 # 0.31.6
if: always() && steps.local-workflow-actions.outputs.repository
with:
actions-path: actions
repository: ${{ steps.local-workflow-actions.outputs.repository }}
ref: ${{ steps.local-workflow-actions.outputs.ref }}
# jscpd:ignore-end