forked from ruby/setup-ruby
-
Notifications
You must be signed in to change notification settings - Fork 3
/
common.js
395 lines (345 loc) · 11.4 KB
/
common.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
const os = require('os')
const path = require('path')
const fs = require('fs')
const util = require('util')
const stream = require('stream')
const crypto = require('crypto')
const core = require('@actions/core')
const tc = require('@actions/tool-cache')
const { performance } = require('perf_hooks')
const linuxOSInfo = require('linux-os-info')
export const windows = (os.platform() === 'win32')
// Extract to SSD on Windows, see https://github.com/ruby/setup-ruby/pull/14
export const drive = (windows ? (process.env['GITHUB_WORKSPACE'] || 'C')[0] : undefined)
export const inputs = {
selfHosted: undefined
}
export function partition(string, separator) {
const i = string.indexOf(separator)
if (i === -1) {
throw new Error(`No separator ${separator} in string ${string}`)
}
return [string.slice(0, i), string.slice(i + separator.length, string.length)]
}
let inGroup = false
export async function measure(name, block) {
const body = async () => {
const start = performance.now()
try {
return await block()
} finally {
const end = performance.now()
const duration = (end - start) / 1000.0
console.log(`Took ${duration.toFixed(2).padStart(6)} seconds`)
}
}
if (inGroup) {
// Nested groups are not yet supported on GitHub Actions
console.log(`> ${name}`)
return await body()
} else {
inGroup = true
try {
return await core.group(name, body)
} finally {
inGroup = false
}
}
}
// Same as mesaure() but without the group, and no time shown on error
export async function time(name, block) {
console.log(`> ${name}`)
const start = performance.now()
const value = await block()
const end = performance.now()
const duration = (end - start) / 1000.0
console.log(`Took ${duration.toFixed(2).padStart(6)} seconds`)
return value
}
export function isHeadVersion(rubyVersion) {
return ['head', 'debug', 'mingw', 'mswin', 'ucrt', 'asan'].includes(rubyVersion)
}
export function isStableVersion(engine, rubyVersion) {
if (engine.startsWith('truffleruby')) {
return /^\d+(\.\d+)*(-preview\d+)?$/.test(rubyVersion)
} else {
return /^\d+(\.\d+)*$/.test(rubyVersion)
}
}
export function hasBundlerDefaultGem(engine, rubyVersion) {
return isBundler1Default(engine, rubyVersion) || isBundler2Default(engine, rubyVersion)
}
export function isBundler1Default(engine, rubyVersion) {
if (engine === 'ruby') {
return floatVersion(rubyVersion) >= 2.6 && floatVersion(rubyVersion) < 2.7
} else if (engine.startsWith('truffleruby')) {
return floatVersion(rubyVersion) < 21.0
} else if (engine === 'jruby') {
return false
} else {
return false
}
}
export function isBundler2Default(engine, rubyVersion) {
if (engine === 'ruby') {
return floatVersion(rubyVersion) >= 2.7
} else if (engine.startsWith('truffleruby')) {
return floatVersion(rubyVersion) >= 21.0
} else if (engine === 'jruby') {
return floatVersion(rubyVersion) >= 9.3
} else {
return false
}
}
export function isBundler2dot2Default(engine, rubyVersion) {
if (engine === 'ruby') {
return floatVersion(rubyVersion) >= 3.0
} else if (engine.startsWith('truffleruby')) {
return floatVersion(rubyVersion) >= 22.0
} else if (engine === 'jruby') {
return floatVersion(rubyVersion) >= 9.3
} else {
return false
}
}
export function targetRubyVersion(engine, rubyVersion) {
const version = floatVersion(rubyVersion)
if (engine === 'ruby') {
return version
} else if (engine === 'jruby') {
if (version === 9.1) {
return 2.3
} else if (version === 9.2) {
return 2.5
} else if (version === 9.3) {
return 2.6
}
} else if (engine.startsWith('truffleruby')) {
if (version < 21.0) {
return 2.6
} else if (version < 22.0) {
return 2.7
} else if (version < 23.0) {
return 3.0
}
}
return 9.9 // unknown, assume recent
}
export function floatVersion(rubyVersion) {
const match = rubyVersion.match(/^\d+\.\d+/)
if (match) {
return parseFloat(match[0])
} else if (isHeadVersion(rubyVersion)) {
return 999.999
} else {
throw new Error(`Could not convert version ${rubyVersion} to a float`)
}
}
export async function hashFile(file) {
// See https://github.com/actions/runner/blob/master/src/Misc/expressionFunc/hashFiles/src/hashFiles.ts
const hash = crypto.createHash('sha256')
const pipeline = util.promisify(stream.pipeline)
await pipeline(fs.createReadStream(file), hash)
return hash.digest('hex')
}
// macos is not listed explicitly, see below
const GitHubHostedPlatforms = [
'ubuntu-20.04-x64',
'ubuntu-22.04-x64',
'ubuntu-24.04-x64',
'windows-2019-x64',
'windows-2022-x64',
]
// Precisely: whether we have builds for that platform and there are GitHub-hosted runners to test it
function isSupportedPlatform() {
const platform = getOSName()
switch (platform) {
case 'ubuntu':
return GitHubHostedPlatforms.includes(getOSNameVersionArch())
case 'macos':
// See https://github.com/ruby/ruby-builder/blob/master/README.md#naming
// 13 on arm64 because of old macos-arm-oss runners
return (os.arch() === 'x64' && parseInt(getOSVersion()) >= 13) ||
(os.arch() === 'arm64' && parseInt(getOSVersion()) >= 13)
case 'windows':
return GitHubHostedPlatforms.includes(getOSNameVersionArch())
}
}
// Actually a self-hosted runner for which the OS and OS version does not correspond to a GitHub-hosted runner image,
export function isSelfHostedRunner() {
if (inputs.selfHosted === undefined) {
throw new Error('inputs.selfHosted should have been already set')
}
return inputs.selfHosted === 'true' || !isSupportedPlatform()
}
export function selfHostedRunnerReason() {
if (inputs.selfHosted === 'true') {
return 'the self-hosted input was set'
} else if (!isSupportedPlatform()) {
return 'the platform does not match a GitHub-hosted runner image (or that image is deprecated and no longer supported)'
} else {
return 'unknown reason'
}
}
let osName = undefined
let osVersion = undefined
export function getOSName() {
if (osName !== undefined) {
return osName
}
const platform = os.platform()
if (platform === 'linux') {
const info = linuxOSInfo({mode: 'sync'})
osName = info.id
} else if (platform === 'darwin') {
osName = 'macos'
} else if (platform === 'win32') {
osName = 'windows'
} else {
throw new Error(`Unknown platform ${platform}`)
}
return osName
}
export function getOSVersion() {
if (osVersion !== undefined) {
return osVersion
}
const platform = os.platform()
if (platform === 'linux') {
const info = linuxOSInfo({mode: 'sync'})
osVersion = info.version_id
} else if (platform === 'darwin') {
// See https://github.com/sindresorhus/macos-release/blob/main/index.js
const darwinVersion = parseInt(os.release().match(/^\d+/)[0])
osVersion = `${darwinVersion - 9}`
} else if (platform === 'win32') {
osVersion = findWindowsVersion()
} else {
throw new Error(`Unknown platform ${platform}`)
}
return osVersion
}
export function getOSNameVersion() {
return `${getOSName()}-${getOSVersion()}`
}
export function getOSNameVersionArch() {
return `${getOSName()}-${getOSVersion()}-${os.arch()}`
}
function findWindowsVersion() {
const version = os.version()
const match = version.match(/^Windows Server (\d+) Datacenter/)
if (match) {
return match[1]
} else {
throw new Error('Could not find Windows version')
}
}
export function shouldUseToolCache(engine, version) {
return (engine === 'ruby' && !isHeadVersion(version)) || isSelfHostedRunner()
}
export function getToolCachePath() {
if (isSelfHostedRunner()) {
return getRunnerToolCache()
} else {
// Rubies prebuilt by this action embed this path rather than using $RUNNER_TOOL_CACHE
// so use that path if not isSelfHostedRunner()
return getDefaultToolCachePath()
}
}
export function getRunnerToolCache() {
const runnerToolCache = process.env['RUNNER_TOOL_CACHE']
if (!runnerToolCache) {
throw new Error('$RUNNER_TOOL_CACHE must be set')
}
return runnerToolCache
}
// Rubies prebuilt by this action embed this path rather than using $RUNNER_TOOL_CACHE
function getDefaultToolCachePath() {
const platform = getOSName()
switch (platform) {
case 'ubuntu':
return '/opt/hostedtoolcache'
case 'macos':
return '/Users/runner/hostedtoolcache'
case 'windows':
return 'C:\\hostedtoolcache\\windows'
}
}
// tc.find() but using RUNNER_TOOL_CACHE=getToolCachePath()
export function toolCacheFind(engine, version) {
const originalToolCache = getToolCachePath()
process.env['RUNNER_TOOL_CACHE'] = getToolCachePath()
try {
return tc.find(engineToToolCacheName(engine), version)
} finally {
process.env['RUNNER_TOOL_CACHE'] = originalToolCache
}
}
function engineToToolCacheName(engine) {
return {
ruby: 'Ruby',
jruby: 'JRuby',
truffleruby: 'TruffleRuby',
"truffleruby+graalvm": 'TruffleRubyGraalVM'
}[engine]
}
export function getToolCacheRubyPrefix(platform, engine, version) {
const toolCache = getToolCachePath()
return path.join(toolCache, engineToToolCacheName(engine), version, os.arch())
}
export function toolCacheCompleteFile(toolCacheRubyPrefix) {
return `${toolCacheRubyPrefix}.complete`
}
export function createToolCacheCompleteFile(toolCacheRubyPrefix) {
fs.writeFileSync(toolCacheCompleteFile(toolCacheRubyPrefix), '')
}
// convert windows path like C:\Users\runneradmin to /c/Users/runneradmin
export function win2nix(path) {
if (/^[A-Z]:/i.test(path)) {
// path starts with drive
path = `/${path[0].toLowerCase()}${partition(path, ':')[1]}`
}
return path.replace(/\\/g, '/').replace(/ /g, '\\ ')
}
// JRuby is installed after setupPath is called, so folder doesn't exist
function rubyIsUCRT(path) {
return !!(fs.existsSync(path) &&
fs.readdirSync(path, { withFileTypes: true }).find(dirent =>
dirent.isFile() && dirent.name.match(/^x64-(ucrt|vcruntime\d{3})-ruby\d{3}\.dll$/)))
}
export function setupPath(newPathEntries) {
let msys2Type = null
const envPath = windows ? 'Path' : 'PATH'
const originalPath = process.env[envPath].split(path.delimiter)
let cleanPath = originalPath.filter(entry => !/\bruby\b/i.test(entry))
core.startGroup(`Modifying ${envPath}`)
// First remove the conflicting path entries
if (cleanPath.length !== originalPath.length) {
console.log(`Entries removed from ${envPath} to avoid conflicts with default Ruby:`)
for (const entry of originalPath) {
if (!cleanPath.includes(entry)) {
console.log(` ${entry}`)
}
}
core.exportVariable(envPath, cleanPath.join(path.delimiter))
}
// Then add new path entries using core.addPath()
let newPath
const windowsToolchain = core.getInput('windows-toolchain')
if (windows && windowsToolchain !== 'none') {
// main Ruby dll determines whether mingw or ucrt build
msys2Type = rubyIsUCRT(newPathEntries[0]) ? 'ucrt64' : 'mingw64'
// add MSYS2 in path for all Rubies on Windows, as it provides a better bash shell and a native toolchain
const msys2 = [`C:\\msys64\\${msys2Type}\\bin`, 'C:\\msys64\\usr\\bin']
newPath = [...newPathEntries, ...msys2]
} else {
newPath = newPathEntries
}
console.log(`Entries added to ${envPath} to use selected Ruby:`)
for (const entry of newPath) {
console.log(` ${entry}`)
}
core.endGroup()
core.addPath(newPath.join(path.delimiter))
return msys2Type
}