-
Notifications
You must be signed in to change notification settings - Fork 69
/
index.js
250 lines (214 loc) · 6.67 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
// @ts-check
const core = require('@actions/core')
const exec = require('@actions/exec')
const io = require('@actions/io')
const hasha = require('hasha')
const cache = require('@actions/cache')
const fs = require('fs')
const os = require('os')
const path = require('path')
const quote = require('quote')
/**
* 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
}
const restoreCachedNpm = npmCache => {
console.log('trying to restore cached NPM modules')
return cache.restoreCache(
npmCache.inputPaths,
npmCache.primaryKey,
npmCache.restoreKeys
)
}
const saveCachedNpm = npmCache => {
console.log('saving NPM modules')
return cache
.saveCache(npmCache.inputPaths, npmCache.primaryKey)
.catch(err => {
// don't throw an error if cache already exists, which may happen due to
// race conditions
if (err.message.includes('Cache already exists')) {
console.warn(err.message)
return -1
}
// otherwise re-throw
throw err
})
}
const hasOption = (name, o) => name in o
const install = (opts = {}) => {
// Note: need to quote found tool to avoid Windows choking on
// npm paths with spaces like "C:\Program Files\nodejs\npm.cmd ci"
if (!hasOption('useYarn', opts)) {
console.error('passed options %o', opts)
throw new Error('Missing useYarn option')
}
if (!hasOption('usePackageLock', opts)) {
console.error('passed options %o', opts)
throw new Error('Missing usePackageLock option')
}
if (!hasOption('workingDirectory', opts)) {
console.error('passed options %o', opts)
throw new Error('Missing workingDirectory option')
}
const shouldUseYarn = opts.useYarn
const shouldUsePackageLock = opts.usePackageLock
const npmCacheFolder = opts.npmCacheFolder
if (!npmCacheFolder) {
console.error('passed opts %o', opts)
throw new Error('Missing npm cache folder to use')
}
const options = {
cwd: opts.workingDirectory
}
if (shouldUseYarn) {
console.log('installing NPM dependencies using Yarn')
return io.which('yarn', true).then(yarnPath => {
console.log('yarn at "%s"', yarnPath)
const args = shouldUsePackageLock ? ['--frozen-lockfile'] : []
core.debug(
`yarn command: "${yarnPath}" ${args} ${JSON.stringify(options)}`
)
return exec.exec(quote(yarnPath), args, options)
})
} else {
console.log('installing NPM dependencies')
core.exportVariable('npm_config_cache', npmCacheFolder)
return io.which('npm', true).then(npmPath => {
console.log('npm at "%s"', npmPath)
const args = shouldUsePackageLock ? ['ci'] : ['install']
core.debug(`npm command: "${npmPath}" ${args} ${JSON.stringify(options)}`)
return exec.exec(quote(npmPath), args, options)
})
}
}
const getPlatformAndArch = () => `${process.platform}-${process.arch}`
const getLockFilename = usePackageLock => workingDirectory => {
const packageFilename = path.join(workingDirectory, 'package.json')
if (!usePackageLock) {
return {
useYarn: false,
lockFilename: packageFilename
}
}
const yarnFilename = path.join(workingDirectory, 'yarn.lock')
const useYarn = fs.existsSync(yarnFilename)
core.debug(`yarn lock file "${yarnFilename}" exists? ${useYarn}`)
const packageLockFilename = path.join(workingDirectory, 'package-lock.json')
const result = {
useYarn,
lockFilename: useYarn ? yarnFilename : packageLockFilename
}
return result
}
const getCacheParams = ({
useYarn,
homeDirectory,
npmCacheFolder,
lockHash
}) => {
const platformAndArch = api.utils.getPlatformAndArch()
core.debug(`platform and arch ${platformAndArch}`)
const o = {}
if (useYarn) {
o.inputPaths = [path.join(homeDirectory, '.cache', 'yarn')]
o.primaryKey = `yarn-${platformAndArch}-${lockHash}`
o.restoreKeys = [o.primaryKey]
} else {
o.inputPaths = [npmCacheFolder]
o.primaryKey = `npm-${platformAndArch}-${lockHash}`
o.restoreKeys = [o.primaryKey]
}
return o
}
const installInOneFolder = ({ usePackageLock, workingDirectory }) => {
core.debug(`usePackageLock? ${usePackageLock}`)
core.debug(`working directory ${workingDirectory}`)
const lockInfo = getLockFilename(usePackageLock)(workingDirectory)
const lockHash = hasha.fromFileSync(lockInfo.lockFilename)
if (!lockHash) {
throw new Error(
`could not compute hash from file "${lockInfo.lockFilename}"`
)
}
core.debug(`lock filename ${lockInfo.lockFilename}`)
core.debug(`file hash ${lockHash}`)
// enforce the same NPM cache folder across different operating systems
const homeDirectory = os.homedir()
const NPM_CACHE_FOLDER = path.join(homeDirectory, '.npm')
const NPM_CACHE = getCacheParams({
useYarn: lockInfo.useYarn,
homeDirectory,
npmCacheFolder: NPM_CACHE_FOLDER,
lockHash
})
const opts = {
useYarn: lockInfo.useYarn,
usePackageLock,
workingDirectory,
npmCacheFolder: NPM_CACHE_FOLDER
}
return api.utils.restoreCachedNpm(NPM_CACHE).then(npmCacheHit => {
console.log('npm cache hit', npmCacheHit)
return api.utils.install(opts).then(() => {
if (npmCacheHit) {
return
}
return api.utils.saveCachedNpm(NPM_CACHE)
})
})
}
const npmInstallAction = async () => {
const usePackageLock = getInputBool('useLockFile', true)
core.debug(`usePackageLock? ${usePackageLock}`)
const wds = core.getInput('working-directory') || process.cwd()
const workingDirectories = wds
.split('\n')
.map(s => s.trim())
.filter(Boolean)
core.debug(
`iterating over working ${workingDirectories.length} directorie(s)`
)
for (const workingDirectory of workingDirectories) {
await api.utils.installInOneFolder({ usePackageLock, workingDirectory })
}
}
/**
* Object of exports, useful to easy testing when mocking individual methods
*/
const api = {
npmInstallAction,
// export functions mostly for testing
utils: {
restoreCachedNpm,
install,
saveCachedNpm,
getPlatformAndArch,
installInOneFolder
}
}
module.exports = api
// @ts-ignore
if (!module.parent) {
console.log('running npm-install GitHub Action')
npmInstallAction()
.then(() => {
console.log('all done, exiting')
})
.catch(error => {
console.log(error)
core.setFailed(error.message)
})
}