forked from cypress-io/github-action
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
749 lines (650 loc) · 20 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
// @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 { ping } = require('./src/ping')
/**
* 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)
core.debug(`parsed command: ${args.join(' ')}`)
return io.which(args[0], true).then((toolPath) => {
core.debug(`found command "${toolPath}"`)
core.debug(`with arguments ${args.slice(1).join(' ')}`)
const toolArguments = args.slice(1)
const argsString = toolArguments.join(' ')
core.debug(`running ${quote(toolPath)} ${argsString} in ${cwd}`)
core.debug('without waiting for the promise to resolve')
const promise = exec.exec(
quote(toolPath),
toolArguments,
cypressCommandOptions
)
if (waitToFinish) {
return promise
}
})
}
const isWindows = () => os.platform() === 'win32'
const isUrl = (s) => /^https?:\/\//.test(s)
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
core.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 packageLockFilename = path.join(
workingDirectory,
'package-lock.json'
)
const useYarn = () => fs.existsSync(yarnFilename)
const lockHash = () => {
const lockFilename = useYarn() ? yarnFilename : packageLockFilename
const fileHash = hasha.fromFileSync(lockFilename)
core.debug(`Hash from file ${lockFilename} is ${fileHash}`)
return fileHash
}
// 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 {
key = `npm-${platformAndArch}-${hash}`
}
} else {
console.log('using custom cache key "%s"', key)
}
if (useYarn()) {
o.inputPath = path.join(homeDirectory, '.cache', 'yarn')
} 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')
core.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 = () => {
core.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 = () => {
core.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 = () => {
core.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 = () => {
core.debug('saving Cypress binary')
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) {
core.debug(`using custom install command "${installCommand}"`)
return execCommand(installCommand, true, 'install command')
}
if (useYarn()) {
core.debug('installing NPM dependencies using Yarn')
return io.which('yarn', true).then((yarnPath) => {
core.debug(`yarn at "${yarnPath}"`)
return exec.exec(
quote(yarnPath),
['--frozen-lockfile'],
cypressCommandOptions
)
})
} else {
core.debug('installing NPM dependencies')
return io.which('npm', true).then((npmPath) => {
core.debug(`npm at "${npmPath}"`)
return exec.exec(quote(npmPath), ['ci'], cypressCommandOptions)
})
}
}
const listCypressBinaries = () => {
core.debug(
`Cypress versions in the cache folder ${CYPRESS_CACHE_FOLDER}`
)
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 = () => {
core.debug(
`Verifying Cypress using cache folder ${CYPRESS_CACHE_FOLDER}`
)
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(',')
core.debug(`extracted spec lines into: "${specLines}"`)
return specLines
}
const buildAppMaybe = () => {
const buildApp = core.getInput('build')
if (!buildApp) {
return
}
core.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) {
core.debug('No start command found')
return
}
const separateStartCommands = startCommand
.split(',')
.map((s) => s.trim())
.filter(Boolean)
core.debug(
`Separated start commands ${separateStartCommands.join(', ')}`
)
return separateStartCommands.map((startCommand) => {
return execCommand(
startCommand,
false,
`start server "${startCommand}`
)
})
}
/**
* 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)
core.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(() => {
core.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
/**
* 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 parallelId = `${GITHUB_WORKFLOW} - ${GITHUB_SHA}`
if (GITHUB_TOKEN) {
core.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
core.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
core.debug(`fetched run list with jobId ${jobId}`)
parallelId = `${GITHUB_RUN_ID}-${jobId}`
} else {
core.debug('could not get run list data')
}
}
core.debug(
`determined branch ${branch} and parallel id ${parallelId}`
)
return { branch, parallelId }
}
/**
* Forms entire command line like "npx cypress run ..."
*/
const runTestsUsingCommandLine = async () => {
core.debug('Running Cypress tests using CLI command')
const quoteArgument = isWindows() ? quote : I
const commandPrefix = core.getInput('command-prefix')
if (!commandPrefix) {
throw new Error('Expected command prefix')
}
const record = getInputBool('record')
const parallel = getInputBool('parallel')
const headless = getInputBool('headless')
// 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)
core.debug(`with concatenated command prefix: ${cmd.join(' ')}`)
// push each CLI argument separately
cmd.push('cypress')
cmd.push('run')
if (headless) {
cmd.push('--headless')
}
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))
}
if (parallel || group) {
const { branch, parallelId } = await getCiBuildId()
if (branch) {
core.exportVariable('GH_BRANCH', branch)
}
const customCiBuildId = core.getInput('ci-build-id') || parallelId
cmd.push('--ci-build-id')
cmd.push(quoteArgument(customCiBuildId))
}
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
}
core.debug(`in working directory "${cypressCommandOptions.cwd}"`)
const npxPath = await io.which('npx', true)
core.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 runTests = getInputBool('runTests', true)
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')
const customCommand = core.getInput('command')
if (customCommand) {
console.log('Using custom test command: %s', customCommand)
return execCommand(customCommand, true, 'run tests')
}
const commandPrefix = core.getInput('command-prefix')
if (commandPrefix) {
return runTestsUsingCommandLine()
}
core.debug('Running Cypress tests using NPM module API')
core.debug(`requiring cypress dependency, cwd is ${process.cwd()}`)
core.debug(`working directory ${workingDirectory}`)
const cypressModulePath =
require.resolve('cypress', {
paths: [workingDirectory]
}) || 'cypress'
core.debug(`resolved cypress ${cypressModulePath}`)
const cypress = require(cypressModulePath)
const cypressOptions = {
headless: getInputBool('headless'),
record: getInputBool('record'),
parallel: getInputBool('parallel'),
quiet: getInputBool('quiet')
}
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')
core.debug(`Cypress config "${cypressOptions.config}"`)
}
const spec = getSpecsList()
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('env')) {
cypressOptions.env = core.getInput('env')
}
if (cypressOptions.parallel || cypressOptions.group) {
const { branch, parallelId } = await getCiBuildId()
if (branch) {
core.exportVariable('GH_BRANCH', branch)
}
const customCiBuildId = core.getInput('ci-build-id') || parallelId
if (customCiBuildId) {
cypressOptions.ciBuildId = customCiBuildId
}
}
core.debug(`Cypress options ${JSON.stringify(cypressOptions)}`)
const onTestsFinished = (testResults) => {
process.chdir(startWorkingDirectory)
if (testResults.failures) {
console.error('Test run failed, code %d', testResults.failures)
if (testResults.message) {
console.error(testResults.message)
}
return Promise.reject(
new Error(testResults.message || 'Error running Cypress')
)
}
core.debug(`Cypress tests: ${testResults.totalFailed} failed`)
const dashboardUrl = testResults.runUrl
if (dashboardUrl) {
core.debug(`Dashboard url ${dashboardUrl}`)
} else {
core.debug('There is no Dashboard url')
}
// we still set the output explicitly
core.setOutput('dashboardUrl', 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(onTestsFinished, onTestsError)
}
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]) => {
core.debug(`npm cache hit ${npmCacheHit}`)
core.debug(`cypress cache hit ${cypressCacheHit}`)
return install().then(() => {
return listCypressBinaries().then(() => {
if (npmCacheHit && cypressCacheHit) {
core.debug(
'no need to verify Cypress binary or save caches'
)
return Promise.resolve(undefined)
}
return verifyCypressBinary()
.then(saveCachedNpm)
.then(saveCachedCypressBinary)
})
})
})
}
installMaybe()
.then(buildAppMaybe)
.then(startServersMaybe)
.then(waitOnMaybe)
.then(runTests)
.then(() => {
core.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
core.debug(error.message)
core.debug(error.stack)
core.setFailed(error.message)
process.exit(1)
})