-
Notifications
You must be signed in to change notification settings - Fork 347
/
index.js
970 lines (835 loc) · 25.8 KB
/
index.js
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
// @ts-check
const { restoreCache, saveCache } = require('@actions/cache')
const core = require('@actions/core')
const exec = require('@actions/exec')
const io = require('@actions/io')
const { Octokit } = require('@octokit/core')
const hasha = require('hasha')
const fs = require('fs')
const os = require('os')
const path = require('path')
const quote = require('quote')
const cliParser = require('argument-vector')()
const findYarnWorkspaceRoot = require('find-yarn-workspace-root')
const debug = require('debug')('@cypress/github-action')
const { ping } = require('./src/ping')
const { SUMMARY_ENV_VAR } = require('@actions/core/lib/summary')
/**
* Parses input command, finds the tool and
* the runs the command.
*/
const execCommand = (
fullCommand,
waitToFinish = true,
label = 'executing'
) => {
const cwd = cypressCommandOptions.cwd
console.log('%s command "%s"', label, fullCommand)
console.log('current working directory "%s"', cwd)
const args = cliParser.parse(fullCommand)
debug(`parsed command: ${args.join(' ')}`)
return io.which(args[0], true).then((toolPath) => {
debug(`found command "${toolPath}"`)
debug(`with arguments ${args.slice(1).join(' ')}`)
const toolArguments = args.slice(1)
const argsString = toolArguments.join(' ')
debug(`running ${quote(toolPath)} ${argsString} in ${cwd}`)
debug(`waiting for the command to finish? ${waitToFinish}`)
const promise = exec.exec(
quote(toolPath),
toolArguments,
cypressCommandOptions
)
if (waitToFinish) {
return promise
}
})
}
const isWindows = () => os.platform() === 'win32'
const isUrl = (s) => /^https?:\/\//.test(s)
/**
* Quote strings that contain Windows delimiters.
* https://github.com/cypress-io/github-action/issues/459
*/
const quoteWindowsArgument = (value) => {
if (!/[,;=\s]/.test(value)) {
return value
}
return quote(value)
}
/**
* Returns true if the Cypress binary installation was skipped
* via an environment variable https://on.cypress.io/installing
*/
const isCypressBinarySkipped = () =>
process.env.CYPRESS_INSTALL_BINARY === '0'
const homeDirectory = os.homedir()
const platformAndArch = `${process.platform}-${process.arch}`
const startWorkingDirectory = process.cwd()
// seems the working directory should be absolute to work correctly
// https://github.com/cypress-io/github-action/issues/211
const workingDirectory = core.getInput('working-directory')
? path.resolve(core.getInput('working-directory'))
: startWorkingDirectory
debug(`working directory ${workingDirectory}`)
/**
* When running "npm install" or any other Cypress-related commands,
* use the install directory as current working directory
*/
const cypressCommandOptions = {
cwd: workingDirectory
}
const yarnFilename = path.join(
findYarnWorkspaceRoot(workingDirectory) || workingDirectory,
'yarn.lock'
)
const pnpmLockFilename = path.join(workingDirectory, 'pnpm-lock.yaml')
const packageLockFilename = path.join(
workingDirectory,
'package-lock.json'
)
const useYarn = () => fs.existsSync(yarnFilename)
const usePnpm = () => fs.existsSync(pnpmLockFilename)
const useNpm = () => fs.existsSync(packageLockFilename)
const lockHash = () => {
const lockFilename = useYarn()
? yarnFilename
: usePnpm()
? pnpmLockFilename
: useNpm()
? packageLockFilename
: noLockFile()
const fileHash = hasha.fromFileSync(lockFilename)
debug(`Hash from file ${lockFilename} is ${fileHash}`)
return fileHash
}
const noLockFile = () => {
core.error(
`Action failed. Missing package manager lockfile. ` +
`Expecting one of package-lock.json (npm), pnpm-lock.yaml (pnpm) or yarn.lock (yarn) in working-directory ` +
workingDirectory
)
process.exit(1)
}
// enforce the same npm cache folder across different operating systems
const NPM_CACHE_FOLDER = path.join(homeDirectory, '.npm')
const getNpmCache = () => {
const o = {}
let key = core.getInput('cache-key')
const hash = lockHash()
if (!key) {
if (useYarn()) {
key = `yarn-${platformAndArch}-${hash}`
} else if (usePnpm()) {
key = `pnpm-${platformAndArch}-${hash}`
} else {
key = `npm-${platformAndArch}-${hash}`
}
} else {
console.log('using custom cache key "%s"', key)
}
if (useYarn()) {
o.inputPath = path.join(homeDirectory, '.cache', 'yarn')
} else if (usePnpm()) {
o.inputPath = NPM_CACHE_FOLDER
} else {
o.inputPath = NPM_CACHE_FOLDER
}
// use exact restore key to prevent npm cache from growing
// https://glebbahmutov.com/blog/do-not-let-npm-cache-snowball/
o.restoreKeys = o.primaryKey = key
return o
}
// custom Cypress binary cache folder
// see https://on.cypress.io/caching
const CYPRESS_CACHE_FOLDER =
process.env.CYPRESS_CACHE_FOLDER ||
path.join(homeDirectory, '.cache', 'Cypress')
debug(`using custom Cypress cache folder "${CYPRESS_CACHE_FOLDER}"`)
const getCypressBinaryCache = () => {
const o = {
inputPath: CYPRESS_CACHE_FOLDER
}
const hash = lockHash()
const key = `cypress-${platformAndArch}-${hash}`
// use only exact restore key to prevent cached folder growing in size
// https://glebbahmutov.com/blog/do-not-let-cypress-cache-snowball/
o.restoreKeys = o.primaryKey = key
return o
}
const restoreCachedNpm = () => {
debug('trying to restore cached npm modules')
const NPM_CACHE = getNpmCache()
return restoreCache([NPM_CACHE.inputPath], NPM_CACHE.primaryKey, [
NPM_CACHE.restoreKeys
]).catch((e) => {
console.warn('Restoring npm cache error: %s', e.message)
})
}
const saveCachedNpm = () => {
debug('saving npm modules')
const NPM_CACHE = getNpmCache()
return saveCache([NPM_CACHE.inputPath], NPM_CACHE.primaryKey).catch(
(e) => {
console.warn('Saving npm cache error: %s', e.message)
}
)
}
const restoreCachedCypressBinary = () => {
debug('trying to restore cached Cypress binary')
const CYPRESS_BINARY_CACHE = getCypressBinaryCache()
return restoreCache(
[CYPRESS_BINARY_CACHE.inputPath],
CYPRESS_BINARY_CACHE.primaryKey,
[CYPRESS_BINARY_CACHE.restoreKeys]
).catch((e) => {
console.warn('Restoring Cypress cache error: %s', e.message)
})
}
const saveCachedCypressBinary = () => {
debug('saving Cypress binary')
if (isCypressBinarySkipped()) {
debug('Skipping Cypress cache save, binary is not installed')
return Promise.resolve()
}
const CYPRESS_BINARY_CACHE = getCypressBinaryCache()
return saveCache(
[CYPRESS_BINARY_CACHE.inputPath],
CYPRESS_BINARY_CACHE.primaryKey
).catch((e) => {
console.warn('Saving Cypress cache error: %s', e.message)
})
}
const install = () => {
// prevent lots of progress messages during install
core.exportVariable('CI', '1')
core.exportVariable('CYPRESS_CACHE_FOLDER', CYPRESS_CACHE_FOLDER)
// set npm cache path in case the user has custom install command
core.exportVariable('npm_config_cache', NPM_CACHE_FOLDER)
// Note: need to quote found tool to avoid Windows choking on
// npm paths with spaces like "C:\Program Files\nodejs\npm.cmd ci"
const installCommand = core.getInput('install-command')
if (installCommand) {
debug(`using custom install command "${installCommand}"`)
return execCommand(installCommand, true, 'install command')
}
if (useYarn()) {
debug('installing npm dependencies using Yarn')
return io.which('yarn', true).then((yarnPath) => {
debug(`yarn at "${yarnPath}"`)
return exec.exec(
quote(yarnPath),
['--frozen-lockfile'],
cypressCommandOptions
)
})
} else if (usePnpm()) {
debug('installing npm dependencies using pnpm')
return io.which('pnpm', true).then((pnpmPath) => {
debug(`pnpm at "${pnpmPath}"`)
return exec.exec(
quote(pnpmPath),
['install', '--frozen-lockfile'],
cypressCommandOptions
)
})
} else {
debug('installing npm dependencies')
return io.which('npm', true).then((npmPath) => {
debug(`npm at "${npmPath}"`)
return exec.exec(quote(npmPath), ['ci'], cypressCommandOptions)
})
}
}
const listCypressBinaries = () => {
debug(
`Cypress versions in the cache folder ${CYPRESS_CACHE_FOLDER}`
)
if (isCypressBinarySkipped()) {
debug('Skipping Cypress cache list, binary is not installed')
return Promise.resolve()
}
core.exportVariable('CYPRESS_CACHE_FOLDER', CYPRESS_CACHE_FOLDER)
return io.which('npx', true).then((npxPath) => {
return exec.exec(
quote(npxPath),
['cypress', 'cache', 'list'],
cypressCommandOptions
)
})
}
const verifyCypressBinary = () => {
debug(
`Verifying Cypress using cache folder ${CYPRESS_CACHE_FOLDER}`
)
if (isCypressBinarySkipped()) {
debug('Skipping Cypress verify, binary is not installed')
return Promise.resolve()
}
core.exportVariable('CYPRESS_CACHE_FOLDER', CYPRESS_CACHE_FOLDER)
return io.which('npx', true).then((npxPath) => {
return exec.exec(
quote(npxPath),
['cypress', 'verify'],
cypressCommandOptions
)
})
}
/**
* Grabs a boolean GitHub Action parameter input and casts it.
* @param {string} name - parameter name
* @param {boolean} defaultValue - default value to use if the parameter was not specified
* @returns {boolean} converted input argument or default value
*/
const getInputBool = (name, defaultValue = false) => {
const param = core.getInput(name)
if (param === 'true' || param === '1') {
return true
}
if (param === 'false' || param === '0') {
return false
}
return defaultValue
}
/**
* Grabs the spec input from the workflow and normalizes
* it, since sometimes it can be multiline
* @returns {string|undefined}
*/
const getSpecsList = () => {
const spec = core.getInput('spec')
if (!spec) {
return
}
const specLines = spec.split('\n').join(',')
debug(`extracted spec lines into: "${specLines}"`)
return specLines
}
const buildAppMaybe = () => {
const buildApp = core.getInput('build')
if (!buildApp) {
return
}
debug(`building application using "${buildApp}"`)
return execCommand(buildApp, true, 'build app')
}
const startServersMaybe = () => {
let startCommand
if (isWindows()) {
// allow custom Windows start command
startCommand =
core.getInput('start-windows') || core.getInput('start')
} else {
startCommand = core.getInput('start')
}
if (!startCommand) {
debug('No start command found')
return Promise.resolve()
}
// allow commands to be separated using commas or newlines
const separateStartCommands = startCommand
.split(/,|\n/)
.map((s) => s.trim())
.filter(Boolean)
debug(
`Separated ${
separateStartCommands.length
} start commands ${separateStartCommands.join(', ')}`
)
return separateStartCommands.map((startCommand) => {
return execCommand(startCommand, false, `start server`)
})
}
/**
* Pings give URL(s) until the timeout expires.
* @param {string} waitOn A single URL or comma-separated URLs
* @param {Number?} waitOnTimeout in seconds
*/
const waitOnUrl = (waitOn, waitOnTimeout = 60) => {
console.log(
'waiting on "%s" with timeout of %s seconds',
waitOn,
waitOnTimeout
)
const waitTimeoutMs = waitOnTimeout * 1000
const waitUrls = waitOn
.split(',')
.map((s) => s.trim())
.filter(Boolean)
debug(`Waiting for urls ${waitUrls.join(', ')}`)
// run every wait promise after the previous has finished
// to avoid "noise" of debug messages
return waitUrls.reduce((prevPromise, url) => {
return prevPromise.then(() => {
debug(`Waiting for url ${url}`)
return ping(url, waitTimeoutMs)
})
}, Promise.resolve())
}
const waitOnMaybe = () => {
const waitOn = core.getInput('wait-on')
if (!waitOn) {
return
}
const waitOnTimeout = core.getInput('wait-on-timeout') || '60'
const timeoutSeconds = parseFloat(waitOnTimeout)
if (isUrl(waitOn)) {
return waitOnUrl(waitOn, timeoutSeconds)
}
console.log('Waiting using command "%s"', waitOn)
return execCommand(waitOn, true)
}
const I = (x) => x
const detectPrNumber = async () => {
const {
GITHUB_SHA,
GITHUB_TOKEN,
GITHUB_RUN_ID,
GITHUB_REPOSITORY,
GITHUB_HEAD_REF,
GITHUB_REF,
GITHUB_SERVER_URL,
CYPRESS_PULL_REQUEST_ID,
CYPRESS_PULL_REQUEST_URL
} = process.env
if (CYPRESS_PULL_REQUEST_ID && CYPRESS_PULL_REQUEST_URL) {
// Both pull request envs are already defined - no need to do anything else
return
}
const [owner, repo] = GITHUB_REPOSITORY.split('/')
let prNumber
if (GITHUB_TOKEN) {
debug(
`Detecting PR number by asking GitHub about run ${GITHUB_RUN_ID}`
)
const client = new Octokit({
auth: GITHUB_TOKEN
})
if (GITHUB_HEAD_REF) {
// GITHUB_HEAD_REF is only defined when the event that triggered it was 'pull_request' or 'pull_request_target' (meaning a PR number should be readily-available)
// should have format refs/pull/<pr_number>/merge when triggered by pull_request workflow
prNumber = parseInt(GITHUB_REF.split('/')[2])
} else {
try {
const resp = await client.request(
'GET /repos/:owner/:repo/commits/:commit_sha/pulls',
{
owner,
repo,
commit_sha: GITHUB_SHA
}
)
if (
resp &&
resp.data &&
resp.data[0] &&
resp.data[0].number
) {
prNumber = resp.data[0].number
}
} catch (e) {
console.error(
`Unable to fetch related PR data for commit: '${GITHUB_SHA}': `,
e
)
}
}
if (prNumber) {
if (!CYPRESS_PULL_REQUEST_ID) {
core.exportVariable('CYPRESS_PULL_REQUEST_ID', prNumber)
}
const url = `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/pull/${prNumber}`
if (!CYPRESS_PULL_REQUEST_URL) {
core.exportVariable('CYPRESS_PULL_REQUEST_URL', url)
}
}
}
}
/**
* Asks Cypress API if there were already builds for this commit.
* In that case increments the count to get unique parallel id.
*/
const getCiBuildId = async () => {
const {
GITHUB_WORKFLOW,
GITHUB_SHA,
GITHUB_TOKEN,
GITHUB_RUN_ID,
GITHUB_REPOSITORY
} = process.env
const [owner, repo] = GITHUB_REPOSITORY.split('/')
let branch
let buildId = `${GITHUB_WORKFLOW} - ${GITHUB_SHA}`
if (GITHUB_TOKEN) {
debug(
`Determining build id by asking GitHub about run ${GITHUB_RUN_ID}`
)
const client = new Octokit({
auth: GITHUB_TOKEN
})
const resp = await client.request(
'GET /repos/:owner/:repo/actions/runs/:run_id',
{
owner,
repo,
run_id: parseInt(GITHUB_RUN_ID)
}
)
if (resp && resp.data && resp.data.head_branch) {
branch = resp.data.head_branch
debug(`found the branch name ${branch}`)
}
// This will return the complete list of jobs for a run with their steps,
// this should always return data when there are jobs on the workflow.
// Every time the workflow is re-run the jobs length should stay the same
// (because the same amount of jobs were ran) but the id of them should change
// letting us, select the first id as unique id
// https://docs.github.com/en/rest/reference/actions#list-jobs-for-a-workflow-run
const runsList = await client.request(
'GET /repos/:owner/:repo/actions/runs/:run_id/jobs',
{
owner,
repo,
run_id: parseInt(GITHUB_RUN_ID)
}
)
if (
runsList &&
runsList.data &&
runsList.data.jobs &&
runsList.data.jobs.length
) {
const jobId = runsList.data.jobs[0].id
debug(`fetched run list with jobId ${jobId}`)
buildId = `${GITHUB_RUN_ID}-${jobId}`
} else {
debug('could not get run list data')
}
}
debug(`determined branch ${branch} and build id ${buildId}`)
return { branch, buildId }
}
/**
* Forms entire command line like "npx cypress run ..."
*/
const runTestsUsingCommandLine = async () => {
debug('Running Cypress tests using CLI command')
const quoteArgument = isWindows() ? quoteWindowsArgument : I
const commandPrefix = core.getInput('command-prefix')
if (!commandPrefix) {
throw new Error('Expected command prefix')
}
const record = getInputBool('record')
const parallel = getInputBool('parallel')
const component = getInputBool('component')
const headed = getInputBool('headed')
// TODO using yarn to run cypress when yarn is used for install
// split potentially long command?
let cmd = []
// we need to split the command prefix into individual arguments
// otherwise they are passed all as a single string
const parts = commandPrefix.split(' ')
cmd = cmd.concat(parts)
debug(`with concatenated command prefix: ${cmd.join(' ')}`)
// push each CLI argument separately
cmd.push('cypress')
cmd.push('run')
if (component) {
cmd.push('--component')
}
if (headed) {
cmd.push('--headed')
}
if (record) {
cmd.push('--record')
}
if (parallel) {
cmd.push('--parallel')
}
const group = core.getInput('group')
if (group) {
cmd.push('--group')
cmd.push(quoteArgument(group))
}
const tag = core.getInput('tag')
if (tag) {
cmd.push('--tag')
cmd.push(quoteArgument(tag))
}
const configInput = core.getInput('config')
if (configInput) {
cmd.push('--config')
cmd.push(quoteArgument(configInput))
}
const spec = getSpecsList()
if (spec) {
cmd.push('--spec')
cmd.push(quoteArgument(spec))
}
const project = core.getInput('project')
if (project) {
cmd.push('--project')
cmd.push(quoteArgument(project))
}
const configFileInput = core.getInput('config-file')
if (configFileInput) {
cmd.push('--config-file')
cmd.push(quoteArgument(configFileInput))
}
const autoCancelAfterFailures = core.getInput(
'auto-cancel-after-failures'
)
if (autoCancelAfterFailures) {
cmd.push('--auto-cancel-after-failures')
cmd.push(quoteArgument(autoCancelAfterFailures))
}
if (parallel || group) {
let buildIdVar = null
if (!core.getInput('ci-build-id')) {
const { branch, buildId } = await getCiBuildId()
if (branch) {
core.exportVariable('GH_BRANCH', branch)
}
buildIdVar = buildId
}
cmd.push('--ci-build-id')
const ciBuildId = core.getInput('ci-build-id') || buildIdVar
cmd.push(quoteArgument(ciBuildId))
}
const browser = core.getInput('browser')
if (browser) {
cmd.push('--browser')
// TODO should browser be quoted?
// If it is a path, it might have spaces
cmd.push(browser)
}
const envInput = core.getInput('env')
if (envInput) {
// TODO should env be quoted?
// If it is a JSON, it might have spaces
cmd.push('--env')
cmd.push(envInput)
}
const quiet = getInputBool('quiet')
if (quiet) {
cmd.push('--quiet')
}
console.log('Cypress test command: npx %s', cmd.join(' '))
// since we have quoted arguments ourselves, do not double quote them
const opts = {
...cypressCommandOptions,
windowsVerbatimArguments: false
}
debug(`in working directory "${cypressCommandOptions.cwd}"`)
const npxPath = await io.which('npx', true)
debug(`npx path: ${npxPath}`)
return exec.exec(quote(npxPath), cmd, opts)
}
/**
* Run Cypress tests by collecting input parameters
* and using Cypress module API to run tests.
* @see https://on.cypress.io/module-api
*/
const runTests = async () => {
const commandPrefix = core.getInput('command-prefix')
const customCommand = core.getInput('command')
const cypressOptions = {
headed: getInputBool('headed'),
record: getInputBool('record'),
parallel: getInputBool('parallel'),
quiet: getInputBool('quiet'),
component: getInputBool('component')
}
const runTests = getInputBool('runTests', true)
const spec = getSpecsList()
if (!runTests) {
console.log('Skipping running tests: runTests parameter is false')
return
}
// export common environment variables that help run Cypress
core.exportVariable('CYPRESS_CACHE_FOLDER', CYPRESS_CACHE_FOLDER)
core.exportVariable('TERM', 'xterm')
await detectPrNumber()
if (customCommand) {
console.log('Using custom test command: %s', customCommand)
return execCommand(customCommand, true, 'run tests')
}
if (commandPrefix) {
return runTestsUsingCommandLine()
}
const cypressModulePath =
require.resolve('cypress', { paths: [workingDirectory] }) ||
'cypress'
const cypress = require(cypressModulePath)
debug('Running Cypress tests using Module API')
debug(`requiring cypress dependency, cwd is ${process.cwd()}`)
debug(`working directory ${workingDirectory}`)
debug(`resolved cypress ${cypressModulePath}`)
if (core.getInput('group')) {
cypressOptions.group = core.getInput('group')
}
if (core.getInput('tag')) {
cypressOptions.tag = core.getInput('tag')
}
if (core.getInput('config')) {
cypressOptions.config = core.getInput('config')
debug(`Cypress config "${cypressOptions.config}"`)
}
if (spec) {
cypressOptions.spec = spec
}
if (core.getInput('config-file')) {
cypressOptions.configFile = core.getInput('config-file')
}
// if the user set the explicit folder, use that
if (core.getInput('project')) {
cypressOptions.project = core.getInput('project')
}
if (core.getInput('browser')) {
cypressOptions.browser = core.getInput('browser')
}
if (core.getInput('auto-cancel-after-failures')) {
cypressOptions.autoCancelAfterFailures = core.getInput(
'auto-cancel-after-failures'
)
}
if (core.getInput('env')) {
cypressOptions.env = core.getInput('env')
}
if (cypressOptions.parallel || cypressOptions.group) {
const { branch, buildId } = await getCiBuildId()
if (branch) {
core.exportVariable('GH_BRANCH', branch)
}
cypressOptions.ciBuildId = core.getInput('ci-build-id') || buildId
}
debug(`Cypress options ${JSON.stringify(cypressOptions)}`)
const onTestsFinished = (testResults) => {
const resultsUrl = testResults.runUrl
process.chdir(startWorkingDirectory)
if (testResults.failures) {
console.error('Test run failed, code %d', testResults.failures)
console.error('More information might be available above')
if (testResults.message) {
console.error(
'Cypress module has returned the following error message:'
)
console.error(testResults.message)
}
return Promise.reject(
new Error(testResults.message || 'Error running Cypress')
)
}
debug(`Cypress tests: ${testResults.totalFailed} failed`)
if (resultsUrl) {
debug(`resultsUrl ${resultsUrl}`)
} else {
debug('There is no resultsUrl')
}
// we still set the output explicitly
core.setOutput('dashboardUrl', resultsUrl) // deprecated and retained for backward compatibility
core.setOutput('resultsUrl', resultsUrl) // replacement for dashboardUrl
if (testResults.totalFailed) {
return Promise.reject(
new Error(`Cypress tests: ${testResults.totalFailed} failed`)
)
}
}
const onTestsError = (e) => {
process.chdir(startWorkingDirectory)
console.error(e)
return Promise.reject(e)
}
process.chdir(workingDirectory)
return cypress
.run(cypressOptions)
.then(generateSummary)
.then(onTestsFinished, onTestsError)
}
// Summary is not available for GitHub Enterprise at the moment
const isSummaryEnabled = () => {
const isSummaryInput = getInputBool('publish-summary')
return process.env[SUMMARY_ENV_VAR] !== undefined && isSummaryInput
}
const generateSummary = async (testResults) => {
if (!isSummaryEnabled()) {
return testResults
}
const headers = [
{ data: 'Result', header: true },
{ data: 'Passed :white_check_mark:', header: true },
{ data: 'Failed :x:', header: true },
{ data: 'Pending :hand:', header: true },
{ data: 'Skipped :leftwards_arrow_with_hook:', header: true },
{ data: 'Duration :clock8:', header: true }
]
const status =
testResults.totalFailed === 0
? 'Passing :white_check_mark:'
: 'Failing :red_circle:'
const summaryRows = [
status,
`${testResults.totalPassed}`,
`${testResults.totalFailed}`,
`${testResults.totalPending}`,
`${testResults.totalSkipped}`,
`${testResults.totalDuration / 1000}s` || ''
]
const summaryTitle = core.getInput('summary-title')
await core.summary
.addHeading(summaryTitle ? summaryTitle : 'Cypress Results', 2)
.addTable([headers, summaryRows])
.addLink(
testResults.runUrl ? 'View run in Cypress Cloud' : '',
testResults.runUrl || ''
)
.write()
return testResults
}
const installMaybe = () => {
const installParameter = getInputBool('install', true)
if (!installParameter) {
console.log('Skipping install because install parameter is false')
return Promise.resolve()
}
return Promise.all([
restoreCachedNpm(),
restoreCachedCypressBinary()
]).then(([npmCacheHit, cypressCacheHit]) => {
debug(`npm cache hit ${npmCacheHit}`)
debug(`cypress cache hit ${cypressCacheHit}`)
return install().then(() => {
debug('install has finished')
return listCypressBinaries().then(() => {
if (npmCacheHit && cypressCacheHit) {
debug('no need to verify Cypress binary or save caches')
return Promise.resolve(undefined)
}
debug('verifying Cypress binary')
return verifyCypressBinary()
.then(saveCachedNpm)
.then(saveCachedCypressBinary)
})
})
})
}
installMaybe()
.then(buildAppMaybe)
.then(startServersMaybe)
.then(waitOnMaybe)
.then(runTests)
.then(() => {
debug('all done, exiting')
// force exit to avoid waiting for child processes,
// like the server we have started
// see https://github.com/actions/toolkit/issues/216
process.exit(0)
})
.catch((error) => {
// final catch - when anything goes wrong, throw an error
// and exit the action with non-zero code
debug(error.message)
debug(error.stack)
core.setFailed(error.message)
process.exit(1)
})