-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathnativePythonFinder.ts
349 lines (321 loc) · 13.8 KB
/
nativePythonFinder.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
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { Disposable, EventEmitter, Event, workspace, Uri } from 'vscode';
import * as ch from 'child_process';
import * as path from 'path';
import * as rpc from 'vscode-jsonrpc/node';
import { PassThrough } from 'stream';
import { isWindows } from '../../../../common/platform/platformService';
import { EXTENSION_ROOT_DIR } from '../../../../constants';
import { traceError, traceInfo, traceLog, traceVerbose, traceWarn } from '../../../../logging';
import { createDeferred, createDeferredFrom } from '../../../../common/utils/async';
import { DisposableBase, DisposableStore } from '../../../../common/utils/resourceLifecycle';
import { DEFAULT_INTERPRETER_PATH_SETTING_KEY } from '../lowLevel/customWorkspaceLocator';
import { noop } from '../../../../common/utils/misc';
import { getConfiguration } from '../../../../common/vscodeApis/workspaceApis';
import { CONDAPATH_SETTING_KEY } from '../../../common/environmentManagers/conda';
import { VENVFOLDERS_SETTING_KEY, VENVPATH_SETTING_KEY } from '../lowLevel/customVirtualEnvLocator';
import { getUserHomeDir } from '../../../../common/utils/platform';
const untildify = require('untildify');
const NATIVE_LOCATOR = isWindows()
? path.join(EXTENSION_ROOT_DIR, 'native_locator', 'bin', 'pet.exe')
: path.join(EXTENSION_ROOT_DIR, 'native_locator', 'bin', 'pet');
export interface NativeEnvInfo {
displayName?: string;
name?: string;
executable?: string;
category: string;
version?: string;
prefix?: string;
manager?: NativeEnvManagerInfo;
/**
* Path to the project directory when dealing with pipenv virtual environments.
*/
project?: string;
arch?: 'x64' | 'x86';
symlinks?: string[];
}
export interface NativeEnvManagerInfo {
tool: string;
executable: string;
version?: string;
}
export interface NativeGlobalPythonFinder extends Disposable {
resolve(executable: string): Promise<NativeEnvInfo>;
refresh(): AsyncIterable<NativeEnvInfo>;
}
interface NativeLog {
level: string;
message: string;
}
class NativeGlobalPythonFinderImpl extends DisposableBase implements NativeGlobalPythonFinder {
private readonly connection: rpc.MessageConnection;
private firstRefreshResults: undefined | (() => AsyncGenerator<NativeEnvInfo, void, unknown>);
constructor() {
super();
this.connection = this.start();
this.firstRefreshResults = this.refreshFirstTime();
}
public async resolve(executable: string): Promise<NativeEnvInfo> {
const { environment, duration } = await this.connection.sendRequest<{
duration: number;
environment: NativeEnvInfo;
}>('resolve', {
executable,
});
traceInfo(`Resolved Python Environment ${environment.executable} in ${duration}ms`);
return environment;
}
async *refresh(): AsyncIterable<NativeEnvInfo> {
if (this.firstRefreshResults) {
// If this is the first time we are refreshing,
// Then get the results from the first refresh.
// Those would have started earlier and cached in memory.
const results = this.firstRefreshResults();
this.firstRefreshResults = undefined;
yield* results;
} else {
const result = this.doRefresh();
let completed = false;
void result.completed.finally(() => {
completed = true;
});
const envs: NativeEnvInfo[] = [];
let discovered = createDeferred();
const disposable = result.discovered((data) => {
envs.push(data);
discovered.resolve();
});
do {
if (!envs.length) {
await Promise.race([result.completed, discovered.promise]);
}
if (envs.length) {
const dataToSend = [...envs];
envs.length = 0;
for (const data of dataToSend) {
yield data;
}
}
if (!completed) {
discovered = createDeferred();
}
} while (!completed);
disposable.dispose();
}
}
refreshFirstTime() {
const result = this.doRefresh();
const completed = createDeferredFrom(result.completed);
const envs: NativeEnvInfo[] = [];
let discovered = createDeferred();
const disposable = result.discovered((data) => {
envs.push(data);
discovered.resolve();
});
const iterable = async function* () {
do {
if (!envs.length) {
await Promise.race([completed.promise, discovered.promise]);
}
if (envs.length) {
const dataToSend = [...envs];
envs.length = 0;
for (const data of dataToSend) {
yield data;
}
}
if (!completed.completed) {
discovered = createDeferred();
}
} while (!completed.completed);
disposable.dispose();
};
return iterable.bind(this);
}
// eslint-disable-next-line class-methods-use-this
private start(): rpc.MessageConnection {
const proc = ch.spawn(NATIVE_LOCATOR, ['server'], { env: process.env });
const disposables: Disposable[] = [];
// 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();
proc.stdout.pipe(readable, { end: false });
proc.stderr.on('data', (data) => {
const err = data.toString();
traceError('Native Python Finder', err);
});
const writable = new PassThrough();
writable.pipe(proc.stdin, { end: false });
const disposeStreams = new Disposable(() => {
readable.end();
writable.end();
});
const connection = rpc.createMessageConnection(
new rpc.StreamMessageReader(readable),
new rpc.StreamMessageWriter(writable),
);
disposables.push(
connection,
disposeStreams,
connection.onError((ex) => {
disposeStreams.dispose();
traceError('Error in Native Python Finder', ex);
}),
connection.onNotification('log', (data: NativeLog) => {
switch (data.level) {
case 'info':
traceInfo(`Native Python Finder: ${data.message}`);
break;
case 'warning':
traceWarn(`Native Python Finder: ${data.message}`);
break;
case 'error':
traceError(`Native Python Finder: ${data.message}`);
break;
case 'debug':
traceVerbose(`Native Python Finder: ${data.message}`);
break;
default:
traceLog(`Native Python Finder: ${data.message}`);
}
}),
connection.onClose(() => {
disposables.forEach((d) => d.dispose());
}),
{
dispose: () => {
try {
if (proc.exitCode === null) {
proc.kill();
}
} catch (ex) {
traceVerbose('Error while disposing Native Python Finder', ex);
}
},
},
);
connection.listen();
this._register(Disposable.from(...disposables));
return connection;
}
private doRefresh(): { completed: Promise<void>; discovered: Event<NativeEnvInfo> } {
const disposable = this._register(new DisposableStore());
const discovered = disposable.add(new EventEmitter<NativeEnvInfo>());
const completed = createDeferred<void>();
const pendingPromises: Promise<void>[] = [];
const notifyUponCompletion = () => {
const initialCount = pendingPromises.length;
Promise.all(pendingPromises)
.then(() => {
if (initialCount === pendingPromises.length) {
completed.resolve();
} else {
setTimeout(notifyUponCompletion, 0);
}
})
.catch(noop);
};
const trackPromiseAndNotifyOnCompletion = (promise: Promise<void>) => {
pendingPromises.push(promise);
notifyUponCompletion();
};
disposable.add(
this.connection.onNotification('environment', (data: NativeEnvInfo) => {
// We know that in the Python extension if either Version of Prefix is not provided by locator
// Then we end up resolving the information.
// Lets do that here,
// This is a hack, as the other part of the code that resolves the version information
// doesn't work as expected, as its still a WIP.
if (data.executable && (!data.version || !data.prefix)) {
// HACK = TEMPORARY WORK AROUND, TO GET STUFF WORKING
// HACK = TEMPORARY WORK AROUND, TO GET STUFF WORKING
// HACK = TEMPORARY WORK AROUND, TO GET STUFF WORKING
// HACK = TEMPORARY WORK AROUND, TO GET STUFF WORKING
const promise = this.connection
.sendRequest<{ duration: number; environment: NativeEnvInfo }>('resolve', {
executable: data.executable,
})
.then(({ environment, duration }) => {
traceInfo(`Resolved Python Environment ${environment.executable} in ${duration}ms`);
discovered.fire(environment);
})
.catch((ex) => traceError(`Error in Resolving Python Environment ${JSON.stringify(data)}`, ex));
trackPromiseAndNotifyOnCompletion(promise);
} else {
discovered.fire(data);
}
}),
);
trackPromiseAndNotifyOnCompletion(
this.sendRefreshRequest()
.then(({ duration }) => traceInfo(`Native Python Finder completed in ${duration}ms`))
.catch((ex) => traceError('Error in Native Python Finder', ex)),
);
completed.promise.finally(() => disposable.dispose());
return {
completed: completed.promise,
discovered: discovered.event,
};
}
private sendRefreshRequest() {
const pythonPathSettings = (workspace.workspaceFolders || []).map((w) =>
getPythonSettingAndUntildify<string>(DEFAULT_INTERPRETER_PATH_SETTING_KEY, w.uri),
);
pythonPathSettings.push(getPythonSettingAndUntildify<string>(DEFAULT_INTERPRETER_PATH_SETTING_KEY));
// We can have multiple workspaces, each with its own setting.
const pythonSettings = Array.from(
new Set(
pythonPathSettings
.filter((item) => !!item)
// We only want the parent directories.
.map((p) => path.dirname(p!))
/// If setting value is 'python', then `path.dirname('python')` will yield `.`
.filter((item) => item !== '.'),
),
);
return this.connection.sendRequest<{ duration: number }>(
'refresh',
// Send configuration information to the Python finder.
{
// This has a special meaning in locator, its lot a low priority
// as we treat this as workspace folders that can contain a large number of files.
search_paths: (workspace.workspaceFolders || []).map((w) => w.uri.fsPath),
// Also send the python paths that are configured in the settings.
python_interpreter_paths: pythonSettings,
// We do not want to mix this with `search_paths`
virtual_env_paths: getCustomVirtualEnvDirs(),
conda_executable: getPythonSettingAndUntildify<string>(CONDAPATH_SETTING_KEY),
poetry_executable: getPythonSettingAndUntildify<string>('poetryPath'),
pipenv_executable: getPythonSettingAndUntildify<string>('pipenvPath'),
},
);
}
}
/**
* Gets all custom virtual environment locations to look for environments.
*/
async function getCustomVirtualEnvDirs(): Promise<string[]> {
const venvDirs: string[] = [];
const venvPath = getPythonSettingAndUntildify<string>(VENVPATH_SETTING_KEY);
if (venvPath) {
venvDirs.push(untildify(venvPath));
}
const venvFolders = getPythonSettingAndUntildify<string[]>(VENVFOLDERS_SETTING_KEY) ?? [];
const homeDir = getUserHomeDir();
if (homeDir) {
venvFolders.map((item) => path.join(homeDir, item)).forEach((d) => venvDirs.push(d));
}
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 createNativeGlobalPythonFinder(): NativeGlobalPythonFinder {
return new NativeGlobalPythonFinderImpl();
}