/
artifacts.ts
234 lines (219 loc) · 7.51 KB
/
artifacts.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import is from '@sindresorhus/is';
import { quote } from 'shlex';
import { TEMPORARY_ERROR } from '../../../constants/error-messages';
import { logger } from '../../../logger';
import type { HostRule } from '../../../types';
import { exec } from '../../../util/exec';
import type { ExecOptions } from '../../../util/exec/types';
import {
deleteLocalFile,
ensureCacheDir,
getSiblingFileName,
readLocalFile,
writeLocalFile,
} from '../../../util/fs';
import { getGitEnvironmentVariables } from '../../../util/git/auth';
import { find } from '../../../util/host-rules';
import { regEx } from '../../../util/regex';
import { Result } from '../../../util/result';
import { parse as parseToml } from '../../../util/toml';
import { PypiDatasource } from '../../datasource/pypi';
import type { UpdateArtifact, UpdateArtifactsResult } from '../types';
import { Lockfile, PoetrySchemaToml } from './schema';
import type { PoetryFile, PoetrySource } from './types';
export function getPythonConstraint(
pyProjectContent: string,
existingLockFileContent: string,
): string | null {
// Read Python version from `pyproject.toml` first as it could have been updated
const pyprojectPythonConstraint = Result.parse(
pyProjectContent,
PoetrySchemaToml.transform(
({ packageFileContent }) =>
packageFileContent.deps.find((dep) => dep.depName === 'python')
?.currentValue,
),
).unwrapOrNull();
if (pyprojectPythonConstraint) {
logger.debug('Using python version from pyproject.toml');
return pyprojectPythonConstraint;
}
const lockfilePythonConstraint = Result.parse(
existingLockFileContent,
Lockfile.transform(({ pythonVersions }) => pythonVersions),
).unwrapOrNull();
if (lockfilePythonConstraint) {
logger.debug('Using python version from poetry.lock');
return lockfilePythonConstraint;
}
return null;
}
export function getPoetryRequirement(
pyProjectContent: string,
existingLockFileContent: string,
): undefined | string | null {
// Read Poetry version from first line of poetry.lock
const firstLine = existingLockFileContent.split('\n')[0];
const poetryVersionMatch = firstLine.match(/by Poetry ([\d\\.]+)/);
if (poetryVersionMatch?.[1]) {
logger.debug('Using poetry version from poetry.lock header');
return poetryVersionMatch[1];
}
const { val: lockfilePoetryConstraint } = Result.parse(
existingLockFileContent,
Lockfile.transform(({ poetryConstraint }) => poetryConstraint),
).unwrap();
if (lockfilePoetryConstraint) {
logger.debug('Using poetry version from poetry.lock metadata');
return lockfilePoetryConstraint;
}
const { val: pyprojectPoetryConstraint } = Result.parse(
pyProjectContent,
PoetrySchemaToml.transform(({ poetryRequirement }) => poetryRequirement),
).unwrap();
if (pyprojectPoetryConstraint) {
logger.debug('Using poetry version from pyproject.toml');
return pyprojectPoetryConstraint;
}
return null;
}
function getPoetrySources(content: string, fileName: string): PoetrySource[] {
let pyprojectFile: PoetryFile;
try {
pyprojectFile = parseToml(content) as PoetryFile;
} catch (err) {
logger.debug({ err }, 'Error parsing pyproject.toml file');
return [];
}
if (!pyprojectFile.tool?.poetry) {
logger.debug(`{$fileName} contains no poetry section`);
return [];
}
const sources = pyprojectFile.tool?.poetry?.source ?? [];
const sourceArray: PoetrySource[] = [];
for (const source of sources) {
if (source.name && source.url) {
sourceArray.push({ name: source.name, url: source.url });
}
}
return sourceArray;
}
function getMatchingHostRule(url: string | undefined): HostRule {
const scopedMatch = find({ hostType: PypiDatasource.id, url });
return is.nonEmptyObject(scopedMatch) ? scopedMatch : find({ url });
}
function getSourceCredentialVars(
pyprojectContent: string,
packageFileName: string,
): NodeJS.ProcessEnv {
const poetrySources = getPoetrySources(pyprojectContent, packageFileName);
const envVars: NodeJS.ProcessEnv = {};
for (const source of poetrySources) {
const matchingHostRule = getMatchingHostRule(source.url);
const formattedSourceName = source.name
.replace(regEx(/(\.|-)+/g), '_')
.toUpperCase();
if (matchingHostRule.username) {
envVars[`POETRY_HTTP_BASIC_${formattedSourceName}_USERNAME`] =
matchingHostRule.username;
}
if (matchingHostRule.password) {
envVars[`POETRY_HTTP_BASIC_${formattedSourceName}_PASSWORD`] =
matchingHostRule.password;
}
}
return envVars;
}
export async function updateArtifacts({
packageFileName,
updatedDeps,
newPackageFileContent,
config,
}: UpdateArtifact): Promise<UpdateArtifactsResult[] | null> {
logger.debug(`poetry.updateArtifacts(${packageFileName})`);
const isLockFileMaintenance = config.updateType === 'lockFileMaintenance';
if (!is.nonEmptyArray(updatedDeps) && !isLockFileMaintenance) {
logger.debug('No updated poetry deps - returning null');
return null;
}
// Try poetry.lock first
let lockFileName = getSiblingFileName(packageFileName, 'poetry.lock');
let existingLockFileContent = await readLocalFile(lockFileName, 'utf8');
if (!existingLockFileContent) {
// Try pyproject.lock next
lockFileName = getSiblingFileName(packageFileName, 'pyproject.lock');
existingLockFileContent = await readLocalFile(lockFileName, 'utf8');
if (!existingLockFileContent) {
logger.debug(`No lock file found`);
return null;
}
}
logger.debug(`Updating ${lockFileName}`);
try {
await writeLocalFile(packageFileName, newPackageFileContent);
const cmd: string[] = [];
if (isLockFileMaintenance) {
await deleteLocalFile(lockFileName);
cmd.push('poetry update --lock --no-interaction');
} else {
cmd.push(
`poetry update --lock --no-interaction ${updatedDeps
.map((dep) => dep.depName)
.filter(is.string)
.map((dep) => quote(dep))
.join(' ')}`,
);
}
const pythonConstraint =
config?.constraints?.python ??
getPythonConstraint(newPackageFileContent, existingLockFileContent);
const poetryConstraint =
config.constraints?.poetry ??
getPoetryRequirement(newPackageFileContent, existingLockFileContent);
const extraEnv = {
...getSourceCredentialVars(newPackageFileContent, packageFileName),
...getGitEnvironmentVariables(['poetry']),
PIP_CACHE_DIR: await ensureCacheDir('pip'),
};
const execOptions: ExecOptions = {
cwdFile: packageFileName,
extraEnv,
docker: {},
userConfiguredEnv: config.env,
toolConstraints: [
{ toolName: 'python', constraint: pythonConstraint },
{ toolName: 'poetry', constraint: poetryConstraint },
],
};
await exec(cmd, execOptions);
const newPoetryLockContent = await readLocalFile(lockFileName, 'utf8');
if (existingLockFileContent === newPoetryLockContent) {
logger.debug(`${lockFileName} is unchanged`);
return null;
}
logger.debug(`Returning updated ${lockFileName}`);
return [
{
file: {
type: 'addition',
path: lockFileName,
contents: newPoetryLockContent,
},
},
];
} catch (err) {
// istanbul ignore if
if (err.message === TEMPORARY_ERROR) {
throw err;
}
logger.debug({ err }, `Failed to update ${lockFileName} file`);
return [
{
artifactError: {
lockFile: lockFileName,
stderr: `${String(err.stdout)}\n${String(err.stderr)}`,
},
},
];
}
}