-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathpipUtils.ts
More file actions
397 lines (354 loc) · 14.3 KB
/
pipUtils.ts
File metadata and controls
397 lines (354 loc) · 14.3 KB
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
import * as tomljs from '@iarna/toml';
import * as fse from 'fs-extra';
import * as path from 'path';
import { l10n, LogOutputChannel, ProgressLocation, QuickInputButtons, QuickPickItem, Uri, window } from 'vscode';
import { PackageManagementOptions, PythonEnvironment, PythonEnvironmentApi, PythonProject } from '../../api';
import { EXTENSION_ROOT_DIR } from '../../common/constants';
import { PackageManagement, Pickers, VenvManagerStrings } from '../../common/localize';
import { traceInfo } from '../../common/logging';
import { showQuickPickWithButtons, withProgress } from '../../common/window.apis';
import { findFiles } from '../../common/workspace.apis';
import { selectFromCommonPackagesToInstall, selectFromInstallableToInstall } from '../common/pickers';
import { Installable } from '../common/types';
import { mergePackages } from '../common/utils';
import { refreshPipPackages } from './utils';
export interface PyprojectToml {
project?: {
name?: string;
version?: string;
};
'build-system'?: {
requires?: unknown;
};
}
export function validatePyprojectToml(toml: PyprojectToml): string | undefined {
// 1. Validate required "requires" field in [build-system] section (PEP 518)
const buildSystem = toml['build-system'];
if (buildSystem && !buildSystem.requires) {
// See PEP 518: https://peps.python.org/pep-0518/
return l10n.t('Missing required field "requires" in [build-system] section of pyproject.toml.');
}
const project = toml.project;
if (!project) {
return undefined;
}
const name = project.name;
// 2. Validate required "name" field in [project] section (PEP 621)
// See PEP 621: https://peps.python.org/pep-0621/
if (!name) {
return l10n.t('Missing required field "name" in [project] section of pyproject.toml.');
}
// 3. Validate package name (PEP 508)
// PEP 508 regex: must start and end with a letter or digit, can contain -_., and alphanumeric characters. No spaces allowed.
// See https://peps.python.org/pep-0508/
const nameRegex = /^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$/;
if (!nameRegex.test(name)) {
return l10n.t('Invalid package name "{0}" in pyproject.toml.', name);
}
// 4. Validate version format (PEP 440)
const version = project.version;
if (version !== undefined) {
if (version.length === 0) {
return l10n.t('Version cannot be empty in pyproject.toml.');
}
// PEP 440 version regex. Versions must follow PEP 440 format (e.g., "1.0.0", "2.1a3").
// See https://peps.python.org/pep-0440/
// This regex is adapted from the official python 'packaging' library:
// https://github.com/pypa/packaging/blob/main/src/packaging/version.py
const versionRegex =
/^v?([0-9]+!)?([0-9]+(?:\.[0-9]+)*)(?:[-_.]?(a|b|c|rc|alpha|beta|pre|preview)[-_.]?([0-9]+)?)?(?:(?:-([0-9]+))|(?:[-_.]?(post|rev|r)[-_.]?([0-9]+)?))?(?:[-_.]?(dev)[-_.]?([0-9]+)?)?(?:\+([a-z0-9]+(?:[-_.][a-z0-9]+)*))?$/i;
if (!versionRegex.test(version)) {
return l10n.t('Invalid version "{0}" in pyproject.toml.', version);
}
}
return undefined;
}
async function tomlParse(fsPath: string, log?: LogOutputChannel): Promise<tomljs.JsonMap> {
try {
const content = await fse.readFile(fsPath, 'utf-8');
return tomljs.parse(content);
} catch (err) {
log?.error('Failed to parse `pyproject.toml`:', err);
}
return {};
}
function isPipInstallableToml(toml: tomljs.JsonMap): boolean {
return toml['build-system'] !== undefined && toml.project !== undefined;
}
function getTomlInstallable(toml: tomljs.JsonMap, tomlPath: Uri): Installable[] {
const extras: Installable[] = [];
const projectDir = path.dirname(tomlPath.fsPath);
if (isPipInstallableToml(toml)) {
const name = path.basename(tomlPath.fsPath);
extras.push({
name,
displayName: name,
description: VenvManagerStrings.installEditable,
group: 'TOML',
args: ['-e', projectDir],
uri: tomlPath,
});
}
if (toml.project && (toml.project as tomljs.JsonMap)['optional-dependencies']) {
const deps = (toml.project as tomljs.JsonMap)['optional-dependencies'];
for (const key of Object.keys(deps)) {
extras.push({
name: key,
displayName: key,
group: 'TOML',
// Use a single -e argument with the extras specified as part of the path
args: ['-e', `${projectDir}[${key}]`],
uri: tomlPath,
});
}
}
return extras;
}
async function getCommonPackages(): Promise<Installable[]> {
try {
const pipData = path.join(EXTENSION_ROOT_DIR, 'files', 'common_pip_packages.json');
const data = await fse.readFile(pipData, { encoding: 'utf-8' });
const packages = JSON.parse(data) as { name: string; uri: string }[];
return packages.map((p) => {
return {
name: p.name,
displayName: p.name,
uri: Uri.parse(p.uri),
};
});
} catch {
return [];
}
}
async function selectWorkspaceOrCommon(
installableResult: ProjectInstallableResult,
common: Installable[],
showSkipOption: boolean,
installed: string[],
): Promise<PipPackages | undefined> {
const installable = installableResult.installables;
if (installable.length === 0 && common.length === 0) {
return undefined;
}
const items: QuickPickItem[] = [];
if (installable.length > 0) {
items.push({
label: PackageManagement.workspaceDependencies,
description: PackageManagement.workspaceDependenciesDescription,
});
}
if (common.length > 0) {
items.push({
label: PackageManagement.searchCommonPackages,
description: PackageManagement.searchCommonPackagesDescription,
});
}
if (showSkipOption && items.length > 0) {
items.push({ label: PackageManagement.skipPackageInstallation });
}
let showBackButton = true;
let selected: QuickPickItem[] | QuickPickItem | undefined = undefined;
if (items.length === 1) {
selected = items[0];
showBackButton = false;
} else {
selected = await showQuickPickWithButtons(items, {
placeHolder: Pickers.Packages.selectOption,
ignoreFocusOut: true,
showBackButton: true,
matchOnDescription: false,
matchOnDetail: false,
});
}
if (selected && !Array.isArray(selected)) {
try {
if (selected.label === PackageManagement.workspaceDependencies) {
const selectedInstallables = await selectFromInstallableToInstall(installable, undefined, {
showBackButton,
});
const validationError = installableResult.validationError;
const shouldProceed = await shouldProceedAfterPyprojectValidation(
validationError,
selectedInstallables?.install ?? [],
);
if (!shouldProceed) {
return undefined;
}
return selectedInstallables;
} else if (selected.label === PackageManagement.searchCommonPackages) {
return await selectFromCommonPackagesToInstall(common, installed, undefined, { showBackButton });
} else if (selected.label === PackageManagement.skipPackageInstallation) {
traceInfo('Package Installer: user selected skip package installation');
return { install: [], uninstall: [] } satisfies PipPackages;
} else {
return undefined;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (ex: any) {
if (ex === QuickInputButtons.Back) {
return selectWorkspaceOrCommon(installableResult, common, showSkipOption, installed);
}
}
}
return undefined;
}
export interface PipPackages {
install: string[];
uninstall: string[];
}
export interface ProjectInstallableResult {
/**
* List of installable packages from pyproject.toml file
*/
installables: Installable[];
/**
* Validation error information if pyproject.toml validation failed
*/
validationError?: ValidationError;
}
export interface ValidationError {
/**
* Human-readable error message describing the validation issue
*/
message: string;
/**
* URI to the pyproject.toml file that has the validation error
*/
fileUri: Uri;
}
export async function getWorkspacePackagesToInstall(
api: PythonEnvironmentApi,
options: PackageManagementOptions,
project?: PythonProject[],
environment?: PythonEnvironment,
log?: LogOutputChannel,
): Promise<PipPackages | undefined> {
const installableResult = await getProjectInstallable(api, project);
let common = await getCommonPackages();
let installed: string[] | undefined;
if (environment) {
installed = (await refreshPipPackages(environment, log, { showProgress: true }))?.map((pkg) => pkg.name);
common = mergePackages(common, installed ?? []);
}
return selectWorkspaceOrCommon(installableResult, common, !!options.showSkipOption, installed ?? []);
}
export async function getProjectInstallable(
api: PythonEnvironmentApi,
projects?: PythonProject[],
): Promise<ProjectInstallableResult> {
if (!projects) {
return { installables: [] };
}
const exclude = '**/{.venv*,.git,.nox,.tox,.conda,site-packages,__pypackages__}/**';
const installable: Installable[] = [];
let validationError: { message: string; fileUri: Uri } | undefined;
await withProgress(
{
location: ProgressLocation.Notification,
title: VenvManagerStrings.searchingDependencies,
},
async (_progress, token) => {
const results: Uri[] = (
await Promise.all([
findFiles('**/*requirements*.txt', exclude, undefined, token),
findFiles('*requirements*.txt', exclude, undefined, token),
findFiles('**/requirements/*.txt', exclude, undefined, token),
findFiles('**/pyproject.toml', exclude, undefined, token),
])
).flat();
// Deduplicate by fsPath
const uniqueResults = Array.from(new Map(results.map((uri) => [uri.fsPath, uri])).values());
const fsPaths = projects.map((p) => p.uri.fsPath);
const filtered = uniqueResults
.filter((uri) => {
const p = api.getPythonProject(uri)?.uri.fsPath;
return p && fsPaths.includes(p);
})
.sort((a, b) => {
// Sort by path depth (shallowest first) so top-level files like
// requirements.txt appear before deeply nested ones.
const depthA = a.fsPath.split(path.sep).length;
const depthB = b.fsPath.split(path.sep).length;
if (depthA !== depthB) {
return depthA - depthB;
}
return a.fsPath.localeCompare(b.fsPath);
});
await Promise.all(
filtered.map(async (uri) => {
if (uri.fsPath.endsWith('.toml')) {
const toml = await tomlParse(uri.fsPath);
// Validate pyproject.toml
if (!validationError) {
const error = validatePyprojectToml(toml);
if (error) {
validationError = {
message: error,
fileUri: uri,
};
}
}
installable.push(...getTomlInstallable(toml, uri));
} else {
const name = path.basename(uri.fsPath);
installable.push({
name,
uri,
displayName: name,
group: 'Requirements',
args: ['-r', uri.fsPath],
});
}
}),
);
},
);
return {
installables: installable,
validationError,
};
}
export async function shouldProceedAfterPyprojectValidation(
validationError: ValidationError | undefined,
install: string[],
): Promise<boolean> {
// 1. If no validation error or no installables selected, proceed
if (!validationError || install.length === 0) {
return true;
}
const selectedTomlInstallables = install.some((arg, index, arr) => arg === '-e' && index + 1 < arr.length);
if (!selectedTomlInstallables) {
// 2. If no toml installables selected, proceed
return true;
}
// 3. Otherwise, show error message and ask user what to do
const openButton = { title: Pickers.pyProject.openFile };
const continueButton = { title: Pickers.pyProject.continueAnyway };
const cancelButton = { title: Pickers.pyProject.cancel, isCloseAffordance: true };
const selection = await window.showErrorMessage(
validationError.message + Pickers.pyProject.validationErrorAction,
openButton,
continueButton,
cancelButton,
);
if (selection === continueButton) {
return true;
}
if (selection === openButton) {
await window.showTextDocument(validationError.fileUri);
}
return false;
}
export function isPipInstallCommand(command: string): boolean {
// Regex to match pip install commands, capturing variations like:
// pip install package
// python -m pip install package
// pip3 install package
// py -m pip install package
// pip install -r requirements.txt
// uv pip install package
// poetry run pip install package
// pipx run pip install package
// Any other tool that might wrap pip install
return /(?:^|\s)(?:\S+\s+)*(?:pip\d*)\s+(install|uninstall)\b/.test(command);
}