-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathutils.ts
More file actions
309 lines (282 loc) · 10.4 KB
/
utils.ts
File metadata and controls
309 lines (282 loc) · 10.4 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
import { CancellationToken, LogOutputChannel, ProgressLocation, QuickPickItem, Uri, window } from 'vscode';
import {
EnvironmentManager,
Package,
PackageManagementOptions,
PackageManager,
PythonEnvironment,
PythonEnvironmentApi,
PythonEnvironmentInfo,
} from '../../api';
import { showErrorMessageWithLogs } from '../../common/errors/utils';
import { SysManagerStrings } from '../../common/localize';
import { withProgress } from '../../common/window.apis';
import {
isNativeEnvInfo,
NativeEnvInfo,
NativePythonEnvironmentKind,
NativePythonFinder,
} from '../common/nativePythonFinder';
import { shortVersion, sortEnvironments } from '../common/utils';
import { runPython, runUV, shouldUseUv } from './helpers';
import { parsePipList, PipPackage } from './pipListUtils';
function asPackageQuickPickItem(name: string, version?: string): QuickPickItem {
return {
label: name,
description: version,
};
}
export async function pickPackages(uninstall: boolean, packages: string[] | Package[]): Promise<string[]> {
const items = packages.map((pkg) => {
if (typeof pkg === 'string') {
return asPackageQuickPickItem(pkg);
}
return asPackageQuickPickItem(pkg.name, pkg.version);
});
const result = await window.showQuickPick(items, {
placeHolder: uninstall ? SysManagerStrings.selectUninstall : SysManagerStrings.selectInstall,
canPickMany: true,
ignoreFocusOut: true,
});
if (Array.isArray(result)) {
return result.map((e) => e.label);
}
return [];
}
function getKindName(kind: NativePythonEnvironmentKind | undefined): string | undefined {
switch (kind) {
case NativePythonEnvironmentKind.homebrew:
return 'homebrew';
case NativePythonEnvironmentKind.macXCode:
return 'xcode';
case NativePythonEnvironmentKind.windowsStore:
return 'store';
case NativePythonEnvironmentKind.macCommandLineTools:
case NativePythonEnvironmentKind.macPythonOrg:
case NativePythonEnvironmentKind.globalPaths:
case NativePythonEnvironmentKind.linuxGlobal:
case NativePythonEnvironmentKind.windowsRegistry:
default:
return undefined;
}
}
function getPythonInfo(env: NativeEnvInfo): PythonEnvironmentInfo {
if (env.executable && env.version && env.prefix) {
const kindName = getKindName(env.kind);
const sv = shortVersion(env.version);
const name = kindName ? `Python ${sv} (${kindName})` : `Python ${sv}`;
const displayName = kindName ? `Python ${sv} (${kindName})` : `Python ${sv}`;
const shortDisplayName = kindName ? `${sv} (${kindName})` : `${sv}`;
return {
name: env.name ?? name,
displayName: env.displayName ?? displayName,
shortDisplayName: shortDisplayName,
displayPath: env.executable,
version: env.version,
description: undefined,
tooltip: env.executable,
environmentPath: Uri.file(env.executable),
sysPrefix: env.prefix,
execInfo: {
run: {
executable: env.executable,
args: [],
},
},
};
} else {
throw new Error(`Invalid python info: ${JSON.stringify(env)}`);
}
}
export async function refreshPythons(
hardRefresh: boolean,
nativeFinder: NativePythonFinder,
api: PythonEnvironmentApi,
log: LogOutputChannel,
manager: EnvironmentManager,
uris?: Uri[],
): Promise<PythonEnvironment[]> {
const collection: PythonEnvironment[] = [];
const data = await nativeFinder.refresh(hardRefresh, uris);
const envs = data
.filter((e) => isNativeEnvInfo(e))
.map((e) => e as NativeEnvInfo)
.filter(
(e) =>
e.kind === undefined ||
(e.kind &&
[
NativePythonEnvironmentKind.globalPaths,
NativePythonEnvironmentKind.homebrew,
NativePythonEnvironmentKind.linuxGlobal,
NativePythonEnvironmentKind.macCommandLineTools,
NativePythonEnvironmentKind.macPythonOrg,
NativePythonEnvironmentKind.macXCode,
NativePythonEnvironmentKind.windowsRegistry,
NativePythonEnvironmentKind.windowsStore,
].includes(e.kind)),
);
envs.forEach((env) => {
try {
const envInfo = getPythonInfo(env);
const python = api.createPythonEnvironmentItem(envInfo, manager);
collection.push(python);
} catch (e) {
log.error((e as Error).message);
}
});
return sortEnvironments(collection);
}
async function refreshPipPackagesRaw(environment: PythonEnvironment, log?: LogOutputChannel): Promise<string> {
// Use environmentPath directly for consistency with UV environment tracking
const useUv = await shouldUseUv(log, environment.environmentPath.fsPath);
if (useUv) {
return await runUV(['pip', 'list', '--python', environment.execInfo.run.executable], undefined, log);
}
try {
return await runPython(environment.execInfo.run.executable, ['-m', 'pip', 'list'], undefined, log);
} catch (ex) {
log?.error('Error running pip list', ex);
log?.info(
'Installation attempted using pip, action can be done with uv if installed and setting `alwaysUseUv` is enabled.',
);
throw ex;
}
}
export async function refreshPipPackages(
environment: PythonEnvironment,
log?: LogOutputChannel,
options?: { showProgress: boolean },
): Promise<PipPackage[] | undefined> {
let data: string;
try {
if (options?.showProgress) {
data = await withProgress(
{
location: ProgressLocation.Notification,
},
async () => {
return await refreshPipPackagesRaw(environment, log);
},
);
} else {
data = await refreshPipPackagesRaw(environment, log);
}
return parsePipList(data);
} catch (e) {
log?.error('Error refreshing packages', e);
showErrorMessageWithLogs(SysManagerStrings.packageRefreshError, log);
return undefined;
}
}
export async function refreshPackages(
environment: PythonEnvironment,
api: PythonEnvironmentApi,
manager: PackageManager,
): Promise<Package[]> {
const data = await refreshPipPackages(environment, manager.log);
return (data ?? []).map((pkg) => api.createPackageItem(pkg, environment, manager));
}
export async function managePackages(
environment: PythonEnvironment,
options: PackageManagementOptions,
api: PythonEnvironmentApi,
manager: PackageManager,
token?: CancellationToken,
): Promise<Package[]> {
if (environment.version.startsWith('2.')) {
throw new Error('Python 2.* is not supported (deprecated)');
}
// Use environmentPath directly for consistency with UV environment tracking
const useUv = await shouldUseUv(manager.log, environment.environmentPath.fsPath);
const uninstallArgs = ['pip', 'uninstall'];
if (options.uninstall && options.uninstall.length > 0) {
if (useUv) {
await runUV(
[...uninstallArgs, '--python', environment.execInfo.run.executable, ...options.uninstall],
undefined,
manager.log,
token,
);
} else {
uninstallArgs.push('--yes');
await runPython(
environment.execInfo.run.executable,
['-m', ...uninstallArgs, ...options.uninstall],
undefined,
manager.log,
token,
);
}
}
const installArgs = ['pip', 'install'];
if (options.upgrade) {
installArgs.push('--upgrade');
}
if (options.install && options.install.length > 0) {
const processedInstallArgs = processEditableInstallArgs(options.install);
if (useUv) {
await runUV(
[...installArgs, '--python', environment.execInfo.run.executable, ...processedInstallArgs],
undefined,
manager.log,
token,
);
} else {
await runPython(
environment.execInfo.run.executable,
['-m', ...installArgs, ...processedInstallArgs],
undefined,
manager.log,
token,
);
}
}
return await refreshPackages(environment, api, manager);
}
/**
* Process pip install arguments to correctly handle editable installs with extras
* This function will combine consecutive -e arguments that represent the same package with extras
*/
export function processEditableInstallArgs(args: string[]): string[] {
const processedArgs: string[] = [];
let i = 0;
while (i < args.length) {
if (args[i] === '-e') {
const packagePath = args[i + 1];
if (!packagePath) {
processedArgs.push(args[i]);
i++;
continue;
}
if (i + 2 < args.length && args[i + 2] === '-e' && i + 3 < args.length) {
const nextArg = args[i + 3];
if (nextArg.startsWith('.[') && nextArg.includes(']')) {
const combinedPath = packagePath + nextArg.substring(1);
processedArgs.push('-e', combinedPath);
i += 4;
continue;
}
}
processedArgs.push(args[i], packagePath);
i += 2;
} else {
processedArgs.push(args[i]);
i++;
}
}
return processedArgs;
}
export async function resolveSystemPythonEnvironmentPath(
fsPath: string,
nativeFinder: NativePythonFinder,
api: PythonEnvironmentApi,
manager: EnvironmentManager,
): Promise<PythonEnvironment | undefined> {
const resolved = await nativeFinder.resolve(fsPath);
// This is supposed to handle a python interpreter as long as we know some basic things about it
if (resolved.executable && resolved.version && resolved.prefix) {
const envInfo = getPythonInfo(resolved);
return api.createPythonEnvironmentItem(envInfo, manager);
}
}