-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathpipenvManager.ts
More file actions
363 lines (318 loc) · 13.5 KB
/
pipenvManager.ts
File metadata and controls
363 lines (318 loc) · 13.5 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
import { Disposable, EventEmitter, MarkdownString, ProgressLocation, Uri, workspace } from 'vscode';
import {
DidChangeEnvironmentEventArgs,
DidChangeEnvironmentsEventArgs,
EnvironmentChangeKind,
EnvironmentManager,
GetEnvironmentScope,
GetEnvironmentsScope,
IconPath,
PythonEnvironment,
PythonEnvironmentApi,
PythonProject,
RefreshEnvironmentsScope,
ResolveEnvironmentContext,
SetEnvironmentScope,
} from '../../api';
import { PipenvStrings } from '../../common/localize';
import { traceError, traceInfo } from '../../common/logging';
import { StopWatch } from '../../common/stopWatch';
import { EventNames } from '../../common/telemetry/constants';
import { classifyError } from '../../common/telemetry/errorClassifier';
import { sendTelemetryEvent } from '../../common/telemetry/sender';
import { createDeferred, Deferred } from '../../common/utils/deferred';
import { normalizePath } from '../../common/utils/pathUtils';
import { withProgress } from '../../common/window.apis';
import { PythonProjectManager } from '../../internal.api';
import { getProjectFsPathForScope, tryFastPathGet } from '../common/fastPath';
import { NativePythonFinder } from '../common/nativePythonFinder';
import { notifyMissingManagerIfDefault } from '../common/utils';
import {
clearPipenvCache,
getPipenv,
getPipenvForGlobal,
getPipenvForWorkspace,
refreshPipenv,
resolvePipenvPath,
setPipenvForGlobal,
setPipenvForWorkspace,
setPipenvForWorkspaces,
} from './pipenvUtils';
export class PipenvManager implements EnvironmentManager, Disposable {
private collection: PythonEnvironment[] = [];
private fsPathToEnv: Map<string, PythonEnvironment> = new Map();
private globalEnv: PythonEnvironment | undefined;
private readonly _onDidChangeEnvironment = new EventEmitter<DidChangeEnvironmentEventArgs>();
public readonly onDidChangeEnvironment = this._onDidChangeEnvironment.event;
private readonly _onDidChangeEnvironments = new EventEmitter<DidChangeEnvironmentsEventArgs>();
public readonly onDidChangeEnvironments = this._onDidChangeEnvironments.event;
public readonly name: string;
public readonly displayName: string;
public readonly preferredPackageManagerId: string;
public readonly description?: string;
public readonly tooltip: string | MarkdownString;
public readonly iconPath?: IconPath;
private _initialized: Deferred<void> | undefined;
constructor(
public readonly nativeFinder: NativePythonFinder,
public readonly api: PythonEnvironmentApi,
private readonly projectManager?: PythonProjectManager,
) {
this.name = 'pipenv';
this.displayName = 'Pipenv';
this.preferredPackageManagerId = 'ms-python.python:pip';
this.tooltip = new MarkdownString(PipenvStrings.pipenvManager, true);
}
public dispose() {
this.collection = [];
this.fsPathToEnv.clear();
this._onDidChangeEnvironment.dispose();
this._onDidChangeEnvironments.dispose();
}
async initialize(): Promise<void> {
if (this._initialized) {
return this._initialized.promise;
}
this._initialized = createDeferred();
const stopWatch = new StopWatch();
let result: 'success' | 'tool_not_found' | 'error' = 'success';
let envCount = 0;
let toolSource = 'none';
let errorType: string | undefined;
try {
// Check if tool is findable before PET refresh (settings/cache/PATH only, no PET)
const hasExplicitSetting = !!workspace.getConfiguration('python').get<string>('pipenvPath');
const preRefreshTool = await getPipenv();
if (preRefreshTool) {
toolSource = hasExplicitSetting ? 'settings' : 'local';
}
await withProgress(
{
location: ProgressLocation.Window,
title: PipenvStrings.pipenvDiscovering,
},
async () => {
this.collection = (await refreshPipenv(false, this.nativeFinder, this.api, this)) ?? [];
await this.loadEnvMap();
this._onDidChangeEnvironments.fire(
this.collection.map((e) => ({ environment: e, kind: EnvironmentChangeKind.add })),
);
},
);
envCount = this.collection.length;
// If tool wasn't found via local lookup, check if refresh discovered it via PET
if (!preRefreshTool) {
const postRefreshTool = await getPipenv();
toolSource = postRefreshTool ? 'pet' : 'none';
}
if (toolSource === 'none') {
result = 'tool_not_found';
if (this.projectManager) {
await notifyMissingManagerIfDefault('ms-python.python:pipenv', this.projectManager, this.api);
}
}
} catch (ex) {
result = 'error';
errorType = classifyError(ex);
traceError('Pipenv lazy initialization failed', ex);
} finally {
sendTelemetryEvent(EventNames.MANAGER_LAZY_INIT, stopWatch.elapsedTime, {
managerName: 'pipenv',
result,
envCount,
toolSource,
errorType,
});
this._initialized.resolve();
}
}
private async loadEnvMap() {
// Load environment mappings for projects
const projects = this.api.getPythonProjects();
for (const project of projects) {
const envPath = await getPipenvForWorkspace(project.uri.fsPath);
if (envPath) {
const env = this.findEnvironmentByPath(envPath);
if (env) {
this.fsPathToEnv.set(normalizePath(project.uri.fsPath), env);
}
}
}
// Load global environment
const globalEnvPath = await getPipenvForGlobal();
if (globalEnvPath) {
this.globalEnv = this.findEnvironmentByPath(globalEnvPath);
}
}
private findEnvironmentByPath(fsPath: string): PythonEnvironment | undefined {
const normalized = normalizePath(fsPath);
return this.collection.find(
(env) =>
normalizePath(env.environmentPath.fsPath) === normalized ||
(env.execInfo?.run.executable && normalizePath(env.execInfo.run.executable) === normalized),
);
}
async refresh(scope: RefreshEnvironmentsScope): Promise<void> {
const hardRefresh = scope === undefined; // hard refresh when scope is undefined
await withProgress(
{
location: ProgressLocation.Window,
title: PipenvStrings.pipenvRefreshing,
},
async () => {
traceInfo('Refreshing Pipenv Environments');
const oldCollection = [...this.collection];
this.collection = (await refreshPipenv(hardRefresh, this.nativeFinder, this.api, this)) ?? [];
await this.loadEnvMap();
// Fire change events for environments that were added or removed
const changes: { environment: PythonEnvironment; kind: EnvironmentChangeKind }[] = [];
// Find removed environments
oldCollection.forEach((oldEnv) => {
if (!this.collection.find((newEnv) => newEnv.envId.id === oldEnv.envId.id)) {
changes.push({ environment: oldEnv, kind: EnvironmentChangeKind.remove });
}
});
// Find added environments
this.collection.forEach((newEnv) => {
if (!oldCollection.find((oldEnv) => oldEnv.envId.id === newEnv.envId.id)) {
changes.push({ environment: newEnv, kind: EnvironmentChangeKind.add });
}
});
if (changes.length > 0) {
this._onDidChangeEnvironments.fire(changes);
}
},
);
}
async getEnvironments(scope: GetEnvironmentsScope): Promise<PythonEnvironment[]> {
await this.initialize();
if (scope === 'all') {
return Array.from(this.collection);
}
if (scope === 'global') {
// Return all environments for global scope
return Array.from(this.collection);
}
if (scope instanceof Uri) {
const project = this.api.getPythonProject(scope);
if (project) {
const env = this.fsPathToEnv.get(normalizePath(project.uri.fsPath));
return env ? [env] : [];
}
}
return [];
}
async set(scope: SetEnvironmentScope, environment?: PythonEnvironment): Promise<void> {
if (scope === undefined) {
// Global scope
const before = this.globalEnv;
this.globalEnv = environment;
await setPipenvForGlobal(environment?.environmentPath.fsPath);
if (before?.envId.id !== this.globalEnv?.envId.id) {
this._onDidChangeEnvironment.fire({ uri: undefined, old: before, new: this.globalEnv });
}
return;
}
if (scope instanceof Uri) {
// Single project scope
const project = this.api.getPythonProject(scope);
if (!project) {
return;
}
const normalizedPath = normalizePath(project.uri.fsPath);
const before = this.fsPathToEnv.get(normalizedPath);
if (environment) {
this.fsPathToEnv.set(normalizedPath, environment);
} else {
this.fsPathToEnv.delete(normalizedPath);
}
await setPipenvForWorkspace(project.uri.fsPath, environment?.environmentPath.fsPath);
if (before?.envId.id !== environment?.envId.id) {
this._onDidChangeEnvironment.fire({ uri: scope, old: before, new: environment });
}
}
if (Array.isArray(scope) && scope.every((u) => u instanceof Uri)) {
// Multiple projects scope
const projects: PythonProject[] = [];
scope
.map((s) => this.api.getPythonProject(s))
.forEach((p) => {
if (p) {
projects.push(p);
}
});
const before: Map<string, PythonEnvironment | undefined> = new Map();
projects.forEach((p) => {
const normalizedPath = normalizePath(p.uri.fsPath);
before.set(p.uri.fsPath, this.fsPathToEnv.get(normalizedPath));
if (environment) {
this.fsPathToEnv.set(normalizedPath, environment);
} else {
this.fsPathToEnv.delete(normalizedPath);
}
});
await setPipenvForWorkspaces(
projects.map((p) => p.uri.fsPath),
environment?.environmentPath.fsPath,
);
projects.forEach((p) => {
const b = before.get(p.uri.fsPath);
if (b?.envId.id !== environment?.envId.id) {
this._onDidChangeEnvironment.fire({ uri: p.uri, old: b, new: environment });
}
});
}
}
async get(scope: GetEnvironmentScope): Promise<PythonEnvironment | undefined> {
const fastResult = await tryFastPathGet({
initialized: this._initialized,
setInitialized: (deferred) => {
this._initialized = deferred;
},
scope,
label: 'pipenv',
getProjectFsPath: (s) => getProjectFsPathForScope(this.api, s),
getPersistedPath: (fsPath) => getPipenvForWorkspace(fsPath),
resolve: (p) => resolvePipenvPath(p, this.nativeFinder, this.api, this),
startBackgroundInit: () =>
withProgress(
{ location: ProgressLocation.Window, title: PipenvStrings.pipenvDiscovering },
async () => {
this.collection = (await refreshPipenv(false, this.nativeFinder, this.api, this)) ?? [];
await this.loadEnvMap();
this._onDidChangeEnvironments.fire(
this.collection.map((e) => ({
environment: e,
kind: EnvironmentChangeKind.add,
})),
);
},
),
});
if (fastResult) {
return fastResult.env;
}
await this.initialize();
if (scope === undefined) {
return this.globalEnv;
}
if (scope instanceof Uri) {
const project = this.api.getPythonProject(scope);
if (project) {
return this.fsPathToEnv.get(normalizePath(project.uri.fsPath));
}
}
return undefined;
}
async resolve(context: ResolveEnvironmentContext): Promise<PythonEnvironment | undefined> {
await this.initialize();
return resolvePipenvPath(context.fsPath, this.nativeFinder, this.api, this);
}
async clearCache?(): Promise<void> {
await clearPipenvCache();
this.collection = [];
this.fsPathToEnv.clear();
this.globalEnv = undefined;
this._initialized = undefined;
}
}