setup-bazel/index.js

101 lines
2.5 KiB
JavaScript

const fs = require('fs')
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 () {
fs.writeFileSync(
config.paths.bazelrc,
`startup --output_base=${config.paths.bazelOutputBase}\n`
)
for (const line of config.bazelrc) {
fs.appendFileSync(config.paths.bazelrc, `${line}\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: true,
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
}
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()