setup-bazel/index.js
2024-01-18 11:56:04 -08:00

104 lines
2.8 KiB
JavaScript

const fs = require('fs')
const { setTimeout } = require('timers/promises')
const core = require('@actions/core')
const cache = require('@actions/cache')
const glob = require('@actions/glob')
const config = require('./config')
async function run() {
try {
await setupBazel()
} catch (error) {
core.setFailed(error.stack)
}
}
async function setupBazel() {
core.startGroup('Configure Bazel')
console.log('Configuration:')
console.log(JSON.stringify(config, null, 2))
await setupBazelrc()
core.endGroup()
await restoreCache(config.bazeliskCache)
await restoreCache(config.diskCache)
await restoreCache(config.repositoryCache)
await restoreExternalCaches(config.externalCache)
}
async function setupBazelrc() {
for (const bazelrcPath of config.paths.bazelrc) {
fs.writeFileSync(
bazelrcPath,
`startup --output_base=${config.paths.bazelOutputBase}\n`
)
fs.appendFileSync(bazelrcPath, config.bazelrc.join("\n"))
}
}
async function restoreExternalCaches(cacheConfig) {
if (!cacheConfig.enabled) {
return
}
// First fetch the manifest of external caches used.
const path = cacheConfig.manifest.path
await restoreCache({
enabled: true,
files: cacheConfig.manifest.files,
name: cacheConfig.manifest.name,
paths: [path]
})
// Now restore all external caches defined in manifest
if (fs.existsSync(path)) {
const manifest = fs.readFileSync(path, { encoding: 'utf8' })
for (const name of manifest.split('\n').filter(s => s)) {
await restoreCache({
enabled: cacheConfig[name]?.enabled ?? cacheConfig.default.enabled,
files: cacheConfig[name]?.files || cacheConfig.default.files,
name: cacheConfig.default.name(name),
paths: cacheConfig.default.paths(name)
})
}
}
}
async function restoreCache(cacheConfig) {
if (!cacheConfig.enabled) {
return
}
const delay = Math.random() * 1000 // timeout <= 1 sec to reduce 429 errors
await setTimeout(delay, async function () {
core.startGroup(`Restore cache for ${cacheConfig.name}`)
const hash = await glob.hashFiles(cacheConfig.files.join('\n'))
const name = cacheConfig.name
const paths = cacheConfig.paths
const restoreKey = `${config.baseCacheKey}-${name}-`
const key = `${restoreKey}${hash}`
console.log(`Attempting to restore ${name} cache from ${key}`)
const restoredKey = await cache.restoreCache(
paths, key, [restoreKey],
{ segmentTimeoutInMs: 300000 } // 5 minutes
)
if (restoredKey) {
console.log(`Successfully restored cache from ${restoredKey}`)
if (restoredKey === key) {
core.saveState(`${name}-cache-hit`, 'true')
}
} else {
console.log(`Failed to restore ${name} cache`)
}
core.endGroup()
}())
}
run()