-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
artifacts.ts
238 lines (225 loc) · 7.25 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
235
236
237
238
import is from '@sindresorhus/is';
import semver from 'semver';
import { TEMPORARY_ERROR } from '../../../constants/error-messages';
import { logger } from '../../../logger';
import type { HostRule } from '../../../types';
import { exec } from '../../../util/exec';
import type { ExecOptions, ExtraEnv, Opt } from '../../../util/exec/types';
import {
deleteLocalFile,
ensureCacheDir,
readLocalFile,
writeLocalFile,
} from '../../../util/fs';
import { getRepoStatus } from '../../../util/git';
import { find } from '../../../util/host-rules';
import { PypiDatasource } from '../../datasource/pypi';
import type {
UpdateArtifact,
UpdateArtifactsConfig,
UpdateArtifactsResult,
} from '../types';
import { extractPackageFile } from './extract';
import { PipfileLockSchema } from './schema';
export function getPythonConstraint(
existingLockFileContent: string,
config: UpdateArtifactsConfig,
): string | undefined {
const { constraints = {} } = config;
const { python } = constraints;
if (python) {
logger.debug('Using python constraint from config');
return python;
}
try {
const result = PipfileLockSchema.safeParse(existingLockFileContent);
// istanbul ignore if: not easily testable
if (!result.success) {
logger.warn({ error: result.error }, 'Invalid Pipfile.lock');
return undefined;
}
// Exact python version has been included since 2022.10.9. It is more specific than the major.minor version
if (result.data._meta?.requires?.python_full_version) {
const pythonFullVersion = result.data._meta.requires.python_full_version;
return `== ${pythonFullVersion}`;
}
// Before 2022.10.9, only the major.minor version was included
if (result.data._meta?.requires?.python_version) {
const pythonVersion = result.data._meta.requires.python_version;
return `== ${pythonVersion}.*`;
}
} catch (err) {
// Do nothing
}
return undefined;
}
export function getPipenvConstraint(
existingLockFileContent: string,
config: UpdateArtifactsConfig,
): string {
const { constraints = {} } = config;
const { pipenv } = constraints;
if (pipenv) {
logger.debug('Using pipenv constraint from config');
return pipenv;
}
try {
const result = PipfileLockSchema.safeParse(existingLockFileContent);
// istanbul ignore if: not easily testable
if (!result.success) {
logger.warn({ error: result.error }, 'Invalid Pipfile.lock');
return '';
}
if (result.data.default?.pipenv?.version) {
return result.data.default.pipenv.version;
}
if (result.data.develop?.pipenv?.version) {
return result.data.develop.pipenv.version;
}
// Exact python version has been included since 2022.10.9
const pythonFullVersion = result.data._meta?.requires?.python_full_version;
if (is.string(pythonFullVersion) && semver.valid(pythonFullVersion)) {
// python_full_version was added after 3.6 was already deprecated, so it should be impossible to have a 3.6 version
if (semver.satisfies(pythonFullVersion, '3.7.*')) {
return '< 2023.10.20';
}
// Future deprecations will go here
}
// Before 2022.10.9, only the major.minor version was included
const pythonVersion = result.data._meta?.requires?.python_version;
if (pythonVersion) {
if (pythonVersion === '3.6') {
// Python 3.6 was deprecated in 2022.4.20
return '< 2022.4.20';
}
if (pythonVersion === '3.7') {
// Python 3.7 was deprecated in 2023.10.20 but we shouldn't reach here unless we are < 2022.10.9
return '< 2022.10.9';
}
}
} catch (err) {
// Do nothing
}
return '';
}
function getMatchingHostRule(url: string): HostRule {
return find({ hostType: PypiDatasource.id, url });
}
async function findPipfileSourceUrlWithCredentials(
pipfileContent: string,
pipfileName: string,
): Promise<string | null> {
const pipfile = await extractPackageFile(pipfileContent, pipfileName);
if (!pipfile) {
logger.debug('Error parsing Pipfile');
return null;
}
const credentialTokens = [
'$USERNAME:',
// eslint-disable-next-line no-template-curly-in-string
'${USERNAME}',
'$PASSWORD@',
// eslint-disable-next-line no-template-curly-in-string
'${PASSWORD}',
];
const sourceWithCredentials = pipfile.registryUrls?.find((url) =>
credentialTokens.some((token) => url.includes(token)),
);
// Only one source is currently supported
return sourceWithCredentials ?? null;
}
export async function updateArtifacts({
packageFileName: pipfileName,
newPackageFileContent: newPipfileContent,
config,
}: UpdateArtifact): Promise<UpdateArtifactsResult[] | null> {
logger.debug(`pipenv.updateArtifacts(${pipfileName})`);
const lockFileName = pipfileName + '.lock';
const existingLockFileContent = await readLocalFile(lockFileName, 'utf8');
if (!existingLockFileContent) {
logger.debug('No Pipfile.lock found');
return null;
}
try {
await writeLocalFile(pipfileName, newPipfileContent);
if (config.isLockFileMaintenance) {
await deleteLocalFile(lockFileName);
}
const cmd = 'pipenv lock';
const tagConstraint = getPythonConstraint(existingLockFileContent, config);
const pipenvConstraint = getPipenvConstraint(
existingLockFileContent,
config,
);
const extraEnv: Opt<ExtraEnv> = {
PIPENV_CACHE_DIR: await ensureCacheDir('pipenv'),
PIP_CACHE_DIR: await ensureCacheDir('pip'),
WORKON_HOME: await ensureCacheDir('virtualenvs'),
};
const execOptions: ExecOptions = {
cwdFile: pipfileName,
docker: {},
userConfiguredEnv: config.env,
toolConstraints: [
{
toolName: 'python',
constraint: tagConstraint,
},
{
toolName: 'pipenv',
constraint: pipenvConstraint,
},
],
};
const sourceUrl = await findPipfileSourceUrlWithCredentials(
newPipfileContent,
pipfileName,
);
if (sourceUrl) {
logger.debug({ sourceUrl }, 'Pipfile contains credentials');
const hostRule = getMatchingHostRule(sourceUrl);
if (hostRule) {
logger.debug('Found matching hostRule for Pipfile credentials');
if (hostRule.username) {
logger.debug('Adding USERNAME environment variable for pipenv');
extraEnv.USERNAME = hostRule.username;
}
if (hostRule.password) {
logger.debug('Adding PASSWORD environment variable for pipenv');
extraEnv.PASSWORD = hostRule.password;
}
}
}
execOptions.extraEnv = extraEnv;
logger.trace({ cmd }, 'pipenv lock command');
await exec(cmd, execOptions);
const status = await getRepoStatus();
if (!status?.modified.includes(lockFileName)) {
return null;
}
logger.debug('Returning updated Pipfile.lock');
return [
{
file: {
type: 'addition',
path: lockFileName,
contents: await readLocalFile(lockFileName, 'utf8'),
},
},
];
} catch (err) {
// istanbul ignore if
if (err.message === TEMPORARY_ERROR) {
throw err;
}
logger.debug({ err }, 'Failed to update Pipfile.lock');
return [
{
artifactError: {
lockFile: lockFileName,
stderr: err.message,
},
},
];
}
}