forked from microsoft/vscode-python-environments
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnativePythonFinder.ts
More file actions
393 lines (359 loc) · 14.7 KB
/
nativePythonFinder.ts
File metadata and controls
393 lines (359 loc) · 14.7 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
import * as ch from 'child_process';
import * as fs from 'fs-extra';
import * as path from 'path';
import { PassThrough } from 'stream';
import { Disposable, ExtensionContext, LogOutputChannel, Uri } from 'vscode';
import * as rpc from 'vscode-jsonrpc/node';
import { PythonProjectApi } from '../../api';
import { ENVS_EXTENSION_ID, PYTHON_EXTENSION_ID } from '../../common/constants';
import { getExtension } from '../../common/extension.apis';
import { traceVerbose } from '../../common/logging';
import { untildify } from '../../common/utils/pathUtils';
import { isWindows } from '../../common/utils/platformUtils';
import { createRunningWorkerPool, WorkerPool } from '../../common/utils/workerPool';
import { getConfiguration } from '../../common/workspace.apis';
import { noop } from './utils';
export async function getNativePythonToolsPath(): Promise<string> {
const envsExt = getExtension(ENVS_EXTENSION_ID);
if (envsExt) {
const petPath = path.join(envsExt.extensionPath, 'python-env-tools', 'bin', isWindows() ? 'pet.exe' : 'pet');
if (await fs.pathExists(petPath)) {
return petPath;
}
}
const python = getExtension(PYTHON_EXTENSION_ID);
if (!python) {
throw new Error('Python extension not found');
}
return path.join(python.extensionPath, 'python-env-tools', 'bin', isWindows() ? 'pet.exe' : 'pet');
}
export interface NativeEnvInfo {
displayName?: string;
name?: string;
executable?: string;
kind?: NativePythonEnvironmentKind;
version?: string;
prefix?: string;
manager?: NativeEnvManagerInfo;
project?: string;
arch?: 'x64' | 'x86';
symlinks?: string[];
}
export interface NativeEnvManagerInfo {
tool: string;
executable: string;
version?: string;
}
export type NativeInfo = NativeEnvInfo | NativeEnvManagerInfo;
export function isNativeEnvInfo(info: NativeInfo): boolean {
return !(info as NativeEnvManagerInfo).tool;
}
export enum NativePythonEnvironmentKind {
conda = 'Conda',
homebrew = 'Homebrew',
pyenv = 'Pyenv',
globalPaths = 'GlobalPaths',
pyenvVirtualEnv = 'PyenvVirtualEnv',
pipenv = 'Pipenv',
poetry = 'Poetry',
macPythonOrg = 'MacPythonOrg',
macCommandLineTools = 'MacCommandLineTools',
linuxGlobal = 'LinuxGlobal',
macXCode = 'MacXCode',
venv = 'Venv',
virtualEnv = 'VirtualEnv',
virtualEnvWrapper = 'VirtualEnvWrapper',
windowsStore = 'WindowsStore',
windowsRegistry = 'WindowsRegistry',
}
export interface NativePythonFinder extends Disposable {
/**
* Refresh the list of python environments.
* Returns an async iterable that can be used to iterate over the list of python environments.
* Internally this will take all of the current workspace folders and search for python environments.
*
* If a Uri is provided, then it will search for python environments in that location (ignoring workspaces).
* Uri can be a file or a folder.
* If a NativePythonEnvironmentKind is provided, then it will search for python environments of that kind (ignoring workspaces).
*/
refresh(hardRefresh: boolean, options?: NativePythonEnvironmentKind | Uri[]): Promise<NativeInfo[]>;
/**
* Will spawn the provided Python executable and return information about the environment.
* @param executable
*/
resolve(executable: string): Promise<NativeEnvInfo>;
}
interface NativeLog {
level: string;
message: string;
}
interface RefreshOptions {
searchKind?: NativePythonEnvironmentKind;
searchPaths?: string[];
}
class NativePythonFinderImpl implements NativePythonFinder {
private readonly connection: rpc.MessageConnection;
private readonly pool: WorkerPool<NativePythonEnvironmentKind | Uri[] | undefined, NativeInfo[]>;
private cache: Map<string, NativeInfo[]> = new Map();
constructor(
private readonly outputChannel: LogOutputChannel,
private readonly toolPath: string,
private readonly api: PythonProjectApi,
private readonly cacheDirectory?: Uri,
) {
this.connection = this.start();
this.pool = createRunningWorkerPool<NativePythonEnvironmentKind | Uri[] | undefined, NativeInfo[]>(
async (options) => await this.doRefresh(options),
1,
'NativeRefresh-task',
);
}
public async resolve(executable: string): Promise<NativeEnvInfo> {
await this.configure();
const environment = await this.connection.sendRequest<NativeEnvInfo>('resolve', {
executable,
});
this.outputChannel.info(`Resolved Python Environment ${environment.executable}`);
return environment;
}
public async refresh(hardRefresh: boolean, options?: NativePythonEnvironmentKind | Uri[]): Promise<NativeInfo[]> {
if (hardRefresh) {
return this.handleHardRefresh(options);
}
return this.handleSoftRefresh(options);
}
private getKey(options?: NativePythonEnvironmentKind | Uri[]): string {
if (options === undefined) {
return 'all';
}
if (typeof options === 'string') {
return options;
}
if (Array.isArray(options)) {
return options.map((item) => item.fsPath).join(',');
}
return 'all';
}
private async handleHardRefresh(options?: NativePythonEnvironmentKind | Uri[]): Promise<NativeInfo[]> {
const key = this.getKey(options);
this.cache.delete(key);
if (!options) {
traceVerbose('Finder - refreshing all environments');
} else {
traceVerbose('Finder - from cache environments', key);
}
const result = await this.pool.addToQueue(options);
this.cache.set(key, result);
return result;
}
private async handleSoftRefresh(options?: NativePythonEnvironmentKind | Uri[]): Promise<NativeInfo[]> {
const key = this.getKey(options);
const cacheResult = this.cache.get(key);
if (!cacheResult) {
return this.handleHardRefresh(options);
}
if (!options) {
traceVerbose('Finder - from cache refreshing all environments');
} else {
traceVerbose('Finder - from cache environments', key);
}
return cacheResult;
}
public dispose() {
this.connection.dispose();
}
private getRefreshOptions(options?: NativePythonEnvironmentKind | Uri[]): RefreshOptions | undefined {
// settings on where else to search
const venvFolders = getPythonSettingAndUntildify<string[]>('venvFolders') ?? [];
if (options) {
if (typeof options === 'string') {
// kind
return { searchKind: options };
}
if (Array.isArray(options)) {
const uriSearchPaths = options.map((item) => item.fsPath);
uriSearchPaths.push(...venvFolders);
return { searchPaths: uriSearchPaths };
}
}
// return undefined to use configured defaults (for nativeFinder refresh)
return undefined;
}
private start(): rpc.MessageConnection {
this.outputChannel.info(`Starting Python Locator ${this.toolPath} server`);
// jsonrpc package cannot handle messages coming through too quickly.
// Lets handle the messages and close the stream only when
// we have got the exit event.
const readable = new PassThrough();
const writable = new PassThrough();
const disposables: Disposable[] = [];
try {
const proc = ch.spawn(this.toolPath, ['server'], { env: process.env });
proc.stdout.pipe(readable, { end: false });
proc.stderr.on('data', (data) => this.outputChannel.error(data.toString()));
writable.pipe(proc.stdin, { end: false });
disposables.push({
dispose: () => {
try {
if (proc.exitCode === null) {
proc.kill();
}
} catch (ex) {
this.outputChannel.error('Error disposing finder', ex);
}
},
});
} catch (ex) {
this.outputChannel.error(`Error starting Python Finder ${this.toolPath} server`, ex);
}
const connection = rpc.createMessageConnection(
new rpc.StreamMessageReader(readable),
new rpc.StreamMessageWriter(writable),
);
disposables.push(
connection,
new Disposable(() => {
readable.end();
writable.end();
}),
connection.onError((ex) => {
this.outputChannel.error('Connection Error:', ex);
}),
connection.onNotification('log', (data: NativeLog) => {
switch (data.level) {
case 'info':
this.outputChannel.info(data.message);
break;
case 'warning':
this.outputChannel.warn(data.message);
break;
case 'error':
this.outputChannel.error(data.message);
break;
case 'debug':
this.outputChannel.debug(data.message);
break;
default:
this.outputChannel.trace(data.message);
}
}),
connection.onNotification('telemetry', (data) => this.outputChannel.info(`Telemetry: `, data)),
connection.onClose(() => {
disposables.forEach((d) => d.dispose());
}),
);
connection.listen();
return connection;
}
private async doRefresh(options?: NativePythonEnvironmentKind | Uri[]): Promise<NativeInfo[]> {
const disposables: Disposable[] = [];
const unresolved: Promise<void>[] = [];
const nativeInfo: NativeInfo[] = [];
try {
await this.configure();
const refreshOptions = this.getRefreshOptions(options);
disposables.push(
this.connection.onNotification('environment', (data: NativeEnvInfo) => {
this.outputChannel.info(`Discovered env: ${data.executable || data.prefix}`);
if (data.executable && (!data.version || !data.prefix)) {
unresolved.push(
this.connection
.sendRequest<NativeEnvInfo>('resolve', {
executable: data.executable,
})
.then((environment: NativeEnvInfo) => {
this.outputChannel.info(`Resolved ${environment.executable}`);
nativeInfo.push(environment);
})
.catch((ex) =>
this.outputChannel.error(`Error in Resolving ${JSON.stringify(data)}`, ex),
),
);
} else {
nativeInfo.push(data);
}
}),
this.connection.onNotification('manager', (data: NativeEnvManagerInfo) => {
this.outputChannel.info(`Discovered manager: (${data.tool}) ${data.executable}`);
nativeInfo.push(data);
}),
);
await this.connection.sendRequest<{ duration: number }>('refresh', refreshOptions);
await Promise.all(unresolved);
} catch (ex) {
this.outputChannel.error('Error refreshing', ex);
throw ex;
} finally {
disposables.forEach((d) => d.dispose());
}
return nativeInfo;
}
private lastConfiguration?: ConfigurationOptions;
/**
* Configuration request, this must always be invoked before any other request.
* Must be invoked when ever there are changes to any data related to the configuration details.
*/
private async configure() {
const options: ConfigurationOptions = {
workspaceDirectories: this.api.getPythonProjects().map((item) => item.uri.fsPath),
// We do not want to mix this with `search_paths`
environmentDirectories: getCustomVirtualEnvDirs(),
condaExecutable: getPythonSettingAndUntildify<string>('condaPath'),
poetryExecutable: getPythonSettingAndUntildify<string>('poetryPath'),
cacheDirectory: this.cacheDirectory?.fsPath,
};
// No need to send a configuration request, is there are no changes.
if (JSON.stringify(options) === JSON.stringify(this.lastConfiguration || {})) {
return;
}
try {
this.lastConfiguration = options;
await this.connection.sendRequest('configure', options);
} catch (ex) {
this.outputChannel.error('Configuration error', ex);
}
}
}
type ConfigurationOptions = {
workspaceDirectories: string[];
environmentDirectories: string[];
condaExecutable: string | undefined;
poetryExecutable: string | undefined;
cacheDirectory?: string;
};
/**
* Gets all custom virtual environment locations to look for environments.
*/
function getCustomVirtualEnvDirs(): string[] {
const venvDirs: string[] = [];
const venvPath = getPythonSettingAndUntildify<string>('venvPath');
if (venvPath) {
venvDirs.push(untildify(venvPath));
}
const venvFolders = getPythonSettingAndUntildify<string[]>('venvFolders') ?? [];
venvFolders.forEach((item) => {
venvDirs.push(item);
});
return Array.from(new Set(venvDirs));
}
function getPythonSettingAndUntildify<T>(name: string, scope?: Uri): T | undefined {
const value = getConfiguration('python', scope).get<T>(name);
if (typeof value === 'string') {
return value ? (untildify(value as string) as unknown as T) : undefined;
}
return value;
}
export function getCacheDirectory(context: ExtensionContext): Uri {
return Uri.joinPath(context.globalStorageUri, 'pythonLocator');
}
export async function clearCacheDirectory(context: ExtensionContext): Promise<void> {
const cacheDirectory = getCacheDirectory(context);
await fs.emptyDir(cacheDirectory.fsPath).catch(noop);
}
export async function createNativePythonFinder(
outputChannel: LogOutputChannel,
api: PythonProjectApi,
context: ExtensionContext,
): Promise<NativePythonFinder> {
return new NativePythonFinderImpl(outputChannel, await getNativePythonToolsPath(), api, getCacheDirectory(context));
}