forked from microsoft/vscode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlegacyIOC.ts
More file actions
292 lines (259 loc) · 11.6 KB
/
legacyIOC.ts
File metadata and controls
292 lines (259 loc) · 11.6 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
// 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 { FileChangeType } from '../common/platform/fileSystemWatcher';
import { Resource } from '../common/types';
import { IComponentAdapter, ICondaService, PythonEnvironmentsChangedEvent } from '../interpreter/contracts';
import { IServiceManager } from '../ioc/types';
import { PythonEnvInfo, PythonEnvKind, PythonEnvSource } from './base/info';
import {
GetRefreshEnvironmentsOptions,
IDiscoveryAPI,
PythonLocatorQuery,
TriggerRefreshOptions,
} from './base/locator';
import { isMacDefaultPythonPath } from './common/environmentManagers/macDefault';
import { isParentPath } from './common/externalDependencies';
import { EnvironmentType, PythonEnvironment } from './info';
import { toSemverLikeVersion } from './base/info/pythonVersion';
import { PythonVersion } from './info/pythonVersion';
import { createDeferred } from '../common/utils/async';
import { PythonEnvCollectionChangedEvent } from './base/watcher';
import { asyncFilter } from '../common/utils/arrayUtils';
import { CondaEnvironmentInfo, isCondaEnvironment } from './common/environmentManagers/conda';
import { isMicrosoftStoreEnvironment } from './common/environmentManagers/microsoftStoreEnv';
import { CondaService } from './common/environmentManagers/condaService';
import { traceError, traceVerbose } from '../logging';
const convertedKinds = new Map(
Object.entries({
[PythonEnvKind.OtherGlobal]: EnvironmentType.Global,
[PythonEnvKind.System]: EnvironmentType.System,
[PythonEnvKind.MicrosoftStore]: EnvironmentType.MicrosoftStore,
[PythonEnvKind.Pyenv]: EnvironmentType.Pyenv,
[PythonEnvKind.Conda]: EnvironmentType.Conda,
[PythonEnvKind.VirtualEnv]: EnvironmentType.VirtualEnv,
[PythonEnvKind.Pipenv]: EnvironmentType.Pipenv,
[PythonEnvKind.Poetry]: EnvironmentType.Poetry,
[PythonEnvKind.Hatch]: EnvironmentType.Hatch,
[PythonEnvKind.Pixi]: EnvironmentType.Pixi,
[PythonEnvKind.Venv]: EnvironmentType.Venv,
[PythonEnvKind.VirtualEnvWrapper]: EnvironmentType.VirtualEnvWrapper,
[PythonEnvKind.ActiveState]: EnvironmentType.ActiveState,
}),
);
function convertEnvInfo(info: PythonEnvInfo): PythonEnvironment {
const { name, location, executable, arch, kind, version, distro, id } = info;
const { filename, sysPrefix } = executable;
const env: PythonEnvironment = {
id,
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;
env.detailedDisplayName = info.detailedDisplayName;
env.type = info.type;
// We do not worry about using distro.defaultDisplayName.
return env;
}
@injectable()
class ComponentAdapter implements IComponentAdapter {
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,
new: event.new ? convertEnvInfo(event.new) : undefined,
old: event.old ? convertEnvInfo(event.old) : undefined,
resource: event.searchLocation,
});
});
}
public triggerRefresh(query?: PythonLocatorQuery, options?: TriggerRefreshOptions): Promise<void> {
return this.api.triggerRefresh(query, options);
}
public getRefreshPromise(options?: GetRefreshEnvironmentsOptions) {
return this.api.getRefreshPromise(options);
}
public get onProgress() {
return this.api.onProgress;
}
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(`Received event ${JSON.stringify(e)} file change event`);
if (
e.type === FileChangeType.Created &&
isParentPath(e.searchLocation.fsPath, workspaceFolder.uri.fsPath)
) {
callback();
}
});
}
// 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> {
try {
const env = await this.api.resolveEnv(pythonPath);
if (!env) {
return undefined;
}
return convertEnvInfo(env);
} catch (ex) {
traceError(`Failed to resolve interpreter: ${pythonPath}`, ex);
return undefined;
}
}
// 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 isMicrosoftStoreInterpreter(pythonPath: string): Promise<boolean> {
// Eventually we won't be calling 'isMicrosoftStoreInterpreter' in the component adapter, so we won't
// need to use 'isMicrosoftStoreEnvironment' directly here. This is just a temporary implementation.
return isMicrosoftStoreEnvironment(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.new) {
if (await filter(convertEnvInfo(e.new))) {
onAddedToCollection.resolve();
}
}
});
const initialEnvs = await asyncFilter(this.api.getEnvs(), (e) => filter(convertEnvInfo(e)));
if (initialEnvs.length > 0) {
return true;
}
// Wait for an env to be added to the collection until the refresh has finished. Note although it's not
// guaranteed we have initiated discovery in this session, we do trigger refresh in the very first session,
// when Python is not installed, etc. Assuming list is more or less upto date.
await Promise.race([onAddedToCollection.promise, this.api.getRefreshPromise()]);
const envs = await asyncFilter(this.api.getEnvs(), (e) => filter(convertEnvInfo(e)));
return envs.length > 0;
}
public getInterpreters(resource?: vscode.Uri, source?: PythonEnvSource[]): PythonEnvironment[] {
const query: PythonLocatorQuery = {};
let roots: vscode.Uri[] = [];
let wsFolder: vscode.WorkspaceFolder | undefined;
if (resource !== undefined) {
wsFolder = vscode.workspace.getWorkspaceFolder(resource);
if (wsFolder) {
roots = [wsFolder.uri];
}
}
// Untitled files should still use the workspace as the query location
if (
!wsFolder &&
vscode.workspace.workspaceFolders &&
vscode.workspace.workspaceFolders.length > 0 &&
(!resource || resource.scheme === 'untitled')
) {
roots = vscode.workspace.workspaceFolders.map((w) => w.uri);
}
query.searchLocations = {
roots,
};
let envs = this.api.getEnvs(query);
if (source) {
envs = envs.filter((env) => intersection(source, env.source).length > 0);
}
return envs.map(convertEnvInfo);
}
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],
doNotIncludeNonRooted: true,
},
};
if (options?.ignoreCache) {
await this.api.triggerRefresh(query);
}
await this.api.getRefreshPromise();
const envs = this.api.getEnvs(query);
return envs.map(convertEnvInfo);
}
}
export function registerNewDiscoveryForIOC(serviceManager: IServiceManager, api: IDiscoveryAPI): void {
serviceManager.addSingleton<ICondaService>(ICondaService, CondaService);
serviceManager.addSingletonInstance<IComponentAdapter>(IComponentAdapter, new ComponentAdapter(api));
}