setup-python/src/cache-distributions/poetry-cache.ts

93 lines
2.3 KiB
TypeScript
Raw Normal View History

2021-11-24 15:10:58 +00:00
import * as glob from '@actions/glob';
2022-05-04 12:33:57 +02:00
import * as io from '@actions/io';
2021-11-24 15:10:58 +00:00
import * as path from 'path';
import * as exec from '@actions/exec';
2022-05-04 12:33:57 +02:00
import * as core from '@actions/core';
2021-11-24 15:10:58 +00:00
import CacheDistributor from './cache-distributor';
class PoetryCache extends CacheDistributor {
constructor(
private pythonVersion: string,
protected patterns: string = '**/poetry.lock'
) {
super('poetry', patterns);
}
protected async getCacheGlobalDirectories() {
const poetryConfig = await this.getPoetryConfiguration();
const cacheDir = poetryConfig['cache-dir'];
const virtualenvsPath = poetryConfig['virtualenvs.path'].replace(
'{cache-dir}',
cacheDir
);
const paths = [virtualenvsPath];
2021-11-27 17:17:01 +00:00
if (poetryConfig['virtualenvs.in-project'] === true) {
2021-11-24 15:10:58 +00:00
paths.push(path.join(process.cwd(), '.venv'));
}
2022-05-04 12:33:57 +02:00
const pythonLocation = await io.which('python');
if (pythonLocation) {
core.debug(`pythonLocation is ${pythonLocation}`);
const {exitCode, stderr} = await exec.getExecOutput(
`poetry env use ${pythonLocation}`
);
if (exitCode) {
throw new Error(stderr);
}
} else {
core.warning('python binaries were not found in PATH.');
}
2021-11-24 15:10:58 +00:00
return paths;
}
protected async computeKeys() {
const hash = await glob.hashFiles(this.patterns);
const primaryKey = `${this.CACHE_KEY_PREFIX}-${process.env['RUNNER_OS']}-python-${this.pythonVersion}-${this.packageManager}-${hash}`;
const restoreKey = undefined;
return {
primaryKey,
restoreKey
};
}
private async getPoetryConfiguration() {
2021-11-24 18:40:05 +00:00
const {stdout, stderr, exitCode} = await exec.getExecOutput('poetry', [
'config',
'--list'
]);
2021-11-24 15:10:58 +00:00
if (exitCode && stderr) {
throw new Error(
2022-02-18 11:31:04 -06:00
'Could not get cache folder path for poetry package manager'
2021-11-24 15:10:58 +00:00
);
}
const lines = stdout.trim().split('\n');
2021-11-24 15:10:58 +00:00
2021-11-27 17:17:01 +00:00
const config: any = {};
2021-11-24 15:10:58 +00:00
for (let line of lines) {
line = line.replace(/#.*$/, '');
const [key, value] = line.split('=').map(part => part.trim());
2021-11-27 17:17:01 +00:00
config[key] = JSON.parse(value);
2021-11-24 15:10:58 +00:00
}
2021-11-27 17:17:01 +00:00
return config as {
'cache-dir': string;
'virtualenvs.in-project': boolean;
'virtualenvs.path': string;
};
2021-11-24 15:10:58 +00:00
}
}
export default PoetryCache;