forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlegacyIOC.ts
More file actions
443 lines (403 loc) · 18.4 KB
/
legacyIOC.ts
File metadata and controls
443 lines (403 loc) · 18.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
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { injectable } from 'inversify';
import { intersection } from 'lodash';
import * as vscode from 'vscode';
import { DiscoveryVariants } from '../common/experiments/groups';
import { traceError, traceVerbose } from '../common/logger';
import { FileChangeType } from '../common/platform/fileSystemWatcher';
import { Resource } from '../common/types';
import {
CONDA_ENV_FILE_SERVICE,
CONDA_ENV_SERVICE,
CURRENT_PATH_SERVICE,
GLOBAL_VIRTUAL_ENV_SERVICE,
IComponentAdapter,
ICondaService,
ICondaLocatorService,
IInterpreterLocatorHelper,
IInterpreterLocatorProgressService,
IInterpreterLocatorService,
IInterpreterWatcher,
IInterpreterWatcherBuilder,
IKnownSearchPathsForInterpreters,
INTERPRETER_LOCATOR_SERVICE,
IVirtualEnvironmentsSearchPathProvider,
KNOWN_PATH_SERVICE,
PIPENV_SERVICE,
WINDOWS_REGISTRY_SERVICE,
WORKSPACE_VIRTUAL_ENV_SERVICE,
PythonEnvironmentsChangedEvent,
} from '../interpreter/contracts';
import { IPipEnvServiceHelper, IPythonInPathCommandProvider } from '../interpreter/locators/types';
import { VirtualEnvironmentManager } from '../interpreter/virtualEnvs';
import { IVirtualEnvironmentManager } from '../interpreter/virtualEnvs/types';
import { IServiceManager } from '../ioc/types';
import { PythonEnvInfo, PythonEnvKind, PythonEnvSource } from './base/info';
import { IDiscoveryAPI, PythonLocatorQuery } from './base/locator';
import { isMacDefaultPythonPath } from './base/locators/lowLevel/macDefaultLocator';
import { inExperiment, isParentPath } from './common/externalDependencies';
import { PythonInterpreterLocatorService } from './discovery/locators';
import { InterpreterLocatorHelper } from './discovery/locators/helpers';
import { InterpreterLocatorProgressService } from './discovery/locators/progressService';
import { CondaEnvironmentInfo, isCondaEnvironment } from './common/environmentManagers/conda';
import { CondaEnvFileService } from './discovery/locators/services/condaEnvFileService';
import { CondaEnvService } from './discovery/locators/services/condaEnvService';
import { CondaService } from './discovery/locators/services/condaService';
import { CondaLocatorService } from './discovery/locators/services/condaLocatorService';
import { CurrentPathService, PythonInPathCommandProvider } from './discovery/locators/services/currentPathService';
import {
GlobalVirtualEnvironmentsSearchPathProvider,
GlobalVirtualEnvService,
} from './discovery/locators/services/globalVirtualEnvService';
import { InterpreterWatcherBuilder } from './discovery/locators/services/interpreterWatcherBuilder';
import { KnownPathsService, KnownSearchPathsForInterpreters } from './discovery/locators/services/KnownPathsService';
import { PipEnvService } from './discovery/locators/services/pipEnvService';
import { PipEnvServiceHelper } from './discovery/locators/services/pipEnvServiceHelper';
import { WindowsRegistryService } from './discovery/locators/services/windowsRegistryService';
import { isWindowsStoreEnvironment } from './common/environmentManagers/windowsStoreEnv';
import {
WorkspaceVirtualEnvironmentsSearchPathProvider,
WorkspaceVirtualEnvService,
} from './discovery/locators/services/workspaceVirtualEnvService';
import { WorkspaceVirtualEnvWatcherService } from './discovery/locators/services/workspaceVirtualEnvWatcherService';
import { EnvironmentType, PythonEnvironment } from './info';
import { toSemverLikeVersion } from './base/info/pythonVersion';
import { PythonVersion } from './info/pythonVersion';
import { IExtensionSingleActivationService } from '../activation/types';
import { EnvironmentInfoServiceQueuePriority, getEnvironmentInfoService } from './base/info/environmentInfoService';
import { createDeferred } from '../common/utils/async';
import { PythonEnvCollectionChangedEvent } from './base/watcher';
import { asyncFilter } from '../common/utils/arrayUtils';
const convertedKinds = new Map(
Object.entries({
[PythonEnvKind.OtherGlobal]: EnvironmentType.Global,
[PythonEnvKind.System]: EnvironmentType.System,
[PythonEnvKind.MacDefault]: EnvironmentType.System,
[PythonEnvKind.WindowsStore]: EnvironmentType.WindowsStore,
[PythonEnvKind.Pyenv]: EnvironmentType.Pyenv,
[PythonEnvKind.Conda]: EnvironmentType.Conda,
[PythonEnvKind.CondaBase]: EnvironmentType.Conda,
[PythonEnvKind.VirtualEnv]: EnvironmentType.VirtualEnv,
[PythonEnvKind.Pipenv]: EnvironmentType.Pipenv,
[PythonEnvKind.Poetry]: EnvironmentType.Poetry,
[PythonEnvKind.Venv]: EnvironmentType.Venv,
[PythonEnvKind.VirtualEnvWrapper]: EnvironmentType.VirtualEnvWrapper,
}),
);
function convertEnvInfo(info: PythonEnvInfo): PythonEnvironment {
const { name, location, executable, arch, kind, version, distro } = info;
const { filename, sysPrefix } = executable;
const env: PythonEnvironment = {
sysPrefix,
envType: EnvironmentType.Unknown,
envName: name,
envPath: location,
path: filename,
architecture: arch,
};
const envType = convertedKinds.get(kind);
if (envType !== undefined) {
env.envType = envType;
}
// Otherwise it stays Unknown.
if (version !== undefined) {
const { release, sysVersion } = version;
if (release === undefined) {
env.sysVersion = '';
} else {
env.sysVersion = sysVersion;
}
const semverLikeVersion: PythonVersion = toSemverLikeVersion(version);
env.version = semverLikeVersion;
}
if (distro !== undefined && distro.org !== '') {
env.companyDisplayName = distro.org;
}
env.displayName = info.display;
// We do not worry about using distro.defaultDisplayName.
return env;
}
export async function isComponentEnabled(): Promise<boolean> {
const results = await Promise.all([
inExperiment(DiscoveryVariants.discoverWithFileWatching),
inExperiment(DiscoveryVariants.discoveryWithoutFileWatching),
]);
return results.includes(true);
}
@injectable()
class ComponentAdapter implements IComponentAdapter {
private readonly refreshing = new vscode.EventEmitter<void>();
private readonly refreshed = new vscode.EventEmitter<void>();
private readonly changed = new vscode.EventEmitter<PythonEnvironmentsChangedEvent>();
constructor(
// The adapter only wraps one thing: the component API.
private readonly api: IDiscoveryAPI,
) {
this.api.onChanged((event) => {
this.changed.fire({
type: event.type,
update: event.update ? convertEnvInfo(event.update) : undefined,
old: event.old ? convertEnvInfo(event.old) : undefined,
resource: event.searchLocation,
});
});
}
public triggerRefresh(query?: PythonLocatorQuery): Promise<void> {
return this.api.triggerRefresh(query);
}
public get refreshPromise() {
return this.api.refreshPromise;
}
public get onRefreshStart(): vscode.Event<void> {
return this.api.onRefreshStart;
}
public get onChanged() {
return this.changed.event;
}
// For use in VirtualEnvironmentPrompt.activate()
// Call callback if an environment gets created within the resource provided.
public onDidCreate(resource: Resource, callback: () => void): vscode.Disposable {
const workspaceFolder = resource ? vscode.workspace.getWorkspaceFolder(resource) : undefined;
return this.api.onChanged((e) => {
if (!workspaceFolder || !e.searchLocation) {
return;
}
traceVerbose(`Recieved event ${JSON.stringify(e)} file change event`);
if (
e.type === FileChangeType.Created &&
isParentPath(e.searchLocation.fsPath, workspaceFolder.uri.fsPath)
) {
callback();
}
});
}
// Implements IInterpreterLocatorProgressHandler
public get onRefreshing(): vscode.Event<void> {
return this.refreshing.event;
}
public get onRefreshed(): vscode.Event<void> {
return this.refreshed.event;
}
// Implements IInterpreterHelper
public async getInterpreterInformation(pythonPath: string): Promise<Partial<PythonEnvironment> | undefined> {
const env = await this.api.resolveEnv(pythonPath);
return env ? convertEnvInfo(env) : undefined;
}
// eslint-disable-next-line class-methods-use-this
public async isMacDefaultPythonPath(pythonPath: string): Promise<boolean> {
// While `ComponentAdapter` represents how the component would be used in the rest of the
// extension, we cheat here for the sake of performance. This is not a problem because when
// we start using the component's public API directly we will be dealing with `PythonEnvInfo`
// instead of just `pythonPath`.
return isMacDefaultPythonPath(pythonPath);
}
// Implements IInterpreterService
// We use the same getInterpreters() here as for IInterpreterLocatorService.
public async getInterpreterDetails(pythonPath: string): Promise<PythonEnvironment | undefined> {
const env = await this.api.resolveEnv(pythonPath);
if (!env) {
return undefined;
}
if (env?.executable.sysPrefix) {
const execInfoService = getEnvironmentInfoService();
const info = await execInfoService.getEnvironmentInfo(pythonPath, EnvironmentInfoServiceQueuePriority.High);
if (info) {
env.executable.sysPrefix = info.executable.sysPrefix;
env.version = info.version;
}
}
return convertEnvInfo(env);
}
// Implements ICondaService
// eslint-disable-next-line class-methods-use-this
public async isCondaEnvironment(interpreterPath: string): Promise<boolean> {
// While `ComponentAdapter` represents how the component would be used in the rest of the
// extension, we cheat here for the sake of performance. This is not a problem because when
// we start using the component's public API directly we will be dealing with `PythonEnvInfo`
// instead of just `pythonPath`.
return isCondaEnvironment(interpreterPath);
}
public async getCondaEnvironment(interpreterPath: string): Promise<CondaEnvironmentInfo | undefined> {
if (!(await isCondaEnvironment(interpreterPath))) {
// Undefined is expected here when the env is not Conda env.
return undefined;
}
// The API getCondaEnvironment() is not called automatically, unless user attempts to install or activate environments
// So calling resolveEnv() which although runs python unnecessarily, is not that expensive here.
const env = await this.api.resolveEnv(interpreterPath);
if (!env) {
return undefined;
}
return { name: env.name, path: env.location };
}
// eslint-disable-next-line class-methods-use-this
public async isWindowsStoreInterpreter(pythonPath: string): Promise<boolean> {
// Eventually we won't be calling 'isWindowsStoreInterpreter' in the component adapter, so we won't
// need to use 'isWindowsStoreEnvironment' directly here. This is just a temporary implementation.
return isWindowsStoreEnvironment(pythonPath);
}
// Implements IInterpreterLocatorService
public async hasInterpreters(
filter: (e: PythonEnvironment) => Promise<boolean> = async () => true,
): Promise<boolean> {
const onAddedToCollection = createDeferred();
// Watch for collection changed events.
this.api.onChanged(async (e: PythonEnvCollectionChangedEvent) => {
if (e.update) {
if (await filter(convertEnvInfo(e.update))) {
onAddedToCollection.resolve();
}
}
});
const initialEnvs = this.api.getEnvs();
if (initialEnvs.length > 0) {
return true;
}
// We should already have initiated discovery. Wait for an env to be added
// to the collection until the refresh has finished.
await Promise.race([onAddedToCollection.promise, this.api.refreshPromise]);
const envs = await asyncFilter(this.api.getEnvs(), (e) => filter(convertEnvInfo(e)));
return envs.length > 0;
}
public getInterpreters(resource?: vscode.Uri, source?: PythonEnvSource[]): PythonEnvironment[] {
// Notify locators are locating.
this.refreshing.fire();
const query: PythonLocatorQuery = {};
if (resource !== undefined) {
const wsFolder = vscode.workspace.getWorkspaceFolder(resource);
if (wsFolder !== undefined) {
query.searchLocations = {
roots: [wsFolder.uri],
};
}
} else {
query.searchLocations = {
roots: [],
};
}
let envs = this.api.getEnvs(query);
if (source) {
envs = envs.filter((env) => intersection(source, env.source).length > 0);
}
const legacyEnvs = envs.map(convertEnvInfo);
// Notify all locators have completed locating. Note it's crucial to notify this even when getInterpretersViaAPI
// fails, to ensure "Python extension loading..." text disappears.
this.refreshed.fire();
return legacyEnvs;
}
public async getWorkspaceVirtualEnvInterpreters(
resource: vscode.Uri,
options?: { ignoreCache?: boolean },
): Promise<PythonEnvironment[]> {
const workspaceFolder = vscode.workspace.getWorkspaceFolder(resource);
if (!workspaceFolder) {
return [];
}
const query: PythonLocatorQuery = {
searchLocations: {
roots: [workspaceFolder.uri],
},
};
if (options?.ignoreCache) {
await this.api.triggerRefresh(query);
}
await this.api.refreshPromise;
const envs = this.api.getEnvs(query);
return envs.map(convertEnvInfo);
}
}
export async function registerLegacyDiscoveryForIOC(serviceManager: IServiceManager): Promise<void> {
const inExp = await isComponentEnabled().catch((ex) => {
// This is mainly to support old tests, where IExperimentService was registered
// out of sequence / or not registered, so this throws an error. But we do not
// care about that error as we don't care about IExperimentService in old tests.
// But if this fails in other cases, it's a major error. Hence log it anyways.
traceError('Failed to not register old code when in Discovery experiment', ex);
return false;
});
if (!inExp) {
serviceManager.addSingleton<IInterpreterLocatorHelper>(IInterpreterLocatorHelper, InterpreterLocatorHelper);
serviceManager.addSingleton<IInterpreterLocatorService>(
IInterpreterLocatorService,
PythonInterpreterLocatorService,
INTERPRETER_LOCATOR_SERVICE,
);
serviceManager.addSingleton<IInterpreterLocatorService>(
IInterpreterLocatorService,
CondaEnvFileService,
CONDA_ENV_FILE_SERVICE,
);
serviceManager.addSingleton<IInterpreterLocatorService>(
IInterpreterLocatorService,
CondaEnvService,
CONDA_ENV_SERVICE,
);
serviceManager.addSingleton<IInterpreterLocatorService>(
IInterpreterLocatorService,
GlobalVirtualEnvService,
GLOBAL_VIRTUAL_ENV_SERVICE,
);
serviceManager.addSingleton<IVirtualEnvironmentsSearchPathProvider>(
IVirtualEnvironmentsSearchPathProvider,
GlobalVirtualEnvironmentsSearchPathProvider,
'global',
);
serviceManager.addSingleton<IInterpreterLocatorService>(
IInterpreterLocatorService,
KnownPathsService,
KNOWN_PATH_SERVICE,
);
serviceManager.addSingleton<IKnownSearchPathsForInterpreters>(
IKnownSearchPathsForInterpreters,
KnownSearchPathsForInterpreters,
);
serviceManager.addSingleton<IInterpreterLocatorProgressService>(
IInterpreterLocatorProgressService,
InterpreterLocatorProgressService,
);
serviceManager.addBinding(IInterpreterLocatorProgressService, IExtensionSingleActivationService);
serviceManager.addSingleton<IInterpreterLocatorService>(
IInterpreterLocatorService,
WorkspaceVirtualEnvService,
WORKSPACE_VIRTUAL_ENV_SERVICE,
);
serviceManager.addSingleton<IVirtualEnvironmentsSearchPathProvider>(
IVirtualEnvironmentsSearchPathProvider,
WorkspaceVirtualEnvironmentsSearchPathProvider,
'workspace',
);
serviceManager.addSingleton<IInterpreterWatcherBuilder>(IInterpreterWatcherBuilder, InterpreterWatcherBuilder);
serviceManager.add<IInterpreterWatcher>(
IInterpreterWatcher,
WorkspaceVirtualEnvWatcherService,
WORKSPACE_VIRTUAL_ENV_SERVICE,
);
serviceManager.addSingleton<IInterpreterLocatorService>(
IInterpreterLocatorService,
CurrentPathService,
CURRENT_PATH_SERVICE,
);
serviceManager.addSingleton<IPythonInPathCommandProvider>(
IPythonInPathCommandProvider,
PythonInPathCommandProvider,
);
serviceManager.addSingleton<IInterpreterLocatorService>(
IInterpreterLocatorService,
WindowsRegistryService,
WINDOWS_REGISTRY_SERVICE,
);
serviceManager.addSingleton<IVirtualEnvironmentManager>(IVirtualEnvironmentManager, VirtualEnvironmentManager);
serviceManager.addSingleton<IInterpreterLocatorService>(
IInterpreterLocatorService,
PipEnvService,
PIPENV_SERVICE,
);
serviceManager.addSingleton<IPipEnvServiceHelper>(IPipEnvServiceHelper, PipEnvServiceHelper);
serviceManager.addSingleton<ICondaLocatorService>(ICondaLocatorService, CondaLocatorService);
}
serviceManager.addSingleton<ICondaService>(ICondaService, CondaService);
}
export function registerNewDiscoveryForIOC(serviceManager: IServiceManager, api: IDiscoveryAPI): void {
serviceManager.addSingletonInstance<IComponentAdapter>(IComponentAdapter, new ComponentAdapter(api));
}