Skip to content
This repository has been archived by the owner. It is now read-only.
Permalink
Browse files
embedding cache steps by using @actions/cache
  • Loading branch information
Trim21 authored and asottile committed Jun 13, 2020
1 parent 7d1e41a commit 4a08748ace346be6b06cec8872f8f47006efc238
Showing 4 changed files with 95 additions and 12 deletions.
@@ -24,12 +24,6 @@ jobs:
steps:
- uses: actions/checkout@v1
- uses: actions/setup-python@v1
- name: set PY
run: echo "::set-env name=PY::$(python -c 'import hashlib, sys;print(hashlib.sha256(sys.version.encode()+sys.executable.encode()).hexdigest())')"
- uses: actions/cache@v1
with:
path: ~/.cache/pre-commit
key: pre-commit|${{ env.PY }}|${{ hashFiles('.pre-commit-config.yaml') }}
- uses: pre-commit/action@v1.1.1
```

@@ -1,7 +1,58 @@
const os = require('os');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

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;
}
}

async function restoreCache(cacheKey) {
return !!(await cache.restoreCache(paths, cacheKey));
}

function addToken(url, token) {
return url.replace(/^https:\/\//, `https://x-access-token:${token}@`);
@@ -22,7 +73,13 @@ async function main() {
const token = core.getInput('token');
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 ret = await exec.exec('pre-commit', args, {ignoreReturnCode: push});
await setupCache(cacheKey);

if (ret && push) {
// actions do not run on pushes made by actions.
// need to make absolute sure things are good before pushing

Some generated files are not rendered by default. Learn more.

@@ -1,6 +1,7 @@
{
"private": true,
"dependencies": {
"@actions/cache": "*",
"@actions/core": "*",
"@actions/exec": "*",
"@actions/github": "*"

0 comments on commit 4a08748

Please sign in to comment.