diff --git a/index.js b/index.js index 4c9b569..1d45918 100644 --- a/index.js +++ b/index.js @@ -1,57 +1,31 @@ -const os = require('os'); -const fs = require('fs'); -const path = require('path'); +const child_process = require('child_process'); const crypto = require('crypto'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const cache = require('@actions/cache'); const core = require('@actions/core'); const exec = require('@actions/exec'); const github = require('@actions/github'); const tr = require('@actions/exec/lib/toolrunner'); -const cache = require('@actions/cache'); - -const paths = [path.join(os.homedir(), '.cache', 'pre-commit')]; - -async function getPythonVersion() { - let myOutput = ''; - const options = { - silent: true, - listeners: { - stdout: (data) => { - myOutput += data.toString(); - } - } - }; - - await exec.exec('python', ['-VV'], options); - await exec.exec('which', ['python'], options); - return myOutput; -} - -function hashFile(filePath) { - return hashString(fs.readFileSync(filePath).toString()); - -} function hashString(content) { const sha256 = crypto.createHash('sha256'); return sha256.update(content).digest('hex'); } -async function setupCache(cacheKey) { - try { - await cache.saveCache(paths, cacheKey); - } catch (e) { - if (e.toString().includes('reserveCache failed')) { - // race condition - core.info(e.message); - return; - } - throw e; +function getPythonVersion() { + const args = ['-c', 'import sys;print(sys.executable+"\\n"+sys.version)']; + const res = child_process.spawnSync('python', args); + if (res.status !== 0) { + throw 'python version check failed'; } + return res.stdout.toString(); } -async function restoreCache(cacheKey) { - return !!(await cache.restoreCache(paths, cacheKey)); +function hashFile(filePath) { + return hashString(fs.readFileSync(filePath).toString()); } function addToken(url, token) { @@ -74,11 +48,12 @@ async function main() { const pr = github.context.payload.pull_request; const push = !!token && !!pr; - const pyVer = await getPythonVersion(); - const cacheKey = `pre-commit-1-${hashString(pyVer)}-${hashFile('.pre-commit-config.yaml')}`; - await restoreCache(cacheKey); + const cachePaths = [path.join(os.homedir(), '.cache', 'pre-commit')]; + const py = getPythonVersion(); + const cacheKey = `pre-commit-2-${hashString(py)}-${hashFile('.pre-commit-config.yaml')}`; + await cache.restoreCache(cachePaths, cacheKey); const ret = await exec.exec('pre-commit', args, {ignoreReturnCode: push}); - await setupCache(cacheKey); + await cache.saveCache(cachePaths, cacheKey); if (ret && push) { // actions do not run on pushes made by actions.