-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathinterpreterSelection.ts
More file actions
470 lines (432 loc) · 19.4 KB
/
interpreterSelection.ts
File metadata and controls
470 lines (432 loc) · 19.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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import * as path from 'path';
import { commands, ConfigurationChangeEvent, Disposable, l10n, Uri } from 'vscode';
import { PythonEnvironment, PythonEnvironmentApi } from '../api';
import { SYSTEM_MANAGER_ID, VENV_MANAGER_ID } from '../common/constants';
import { traceError, traceInfo, traceVerbose, traceWarn } from '../common/logging';
import { resolveVariables } from '../common/utils/internalVariables';
import { showWarningMessage } from '../common/window.apis';
import {
getConfiguration,
getWorkspaceFolder,
getWorkspaceFolders,
onDidChangeConfiguration,
} from '../common/workspace.apis';
import { getUserConfiguredSetting } from '../helpers';
import {
EnvironmentManagers,
InternalEnvironmentManager,
PythonProjectManager,
PythonProjectSettings,
} from '../internal.api';
import { NativeEnvInfo, NativePythonFinder } from '../managers/common/nativePythonFinder';
/**
* Result from the priority chain resolution.
*/
export interface PriorityChainResult {
/** The environment manager to use */
manager: InternalEnvironmentManager;
/** Optional specific environment - if undefined, let the manager decide via get() */
environment?: PythonEnvironment;
/** Which priority level matched */
source: 'pythonProjects' | 'defaultEnvManager' | 'defaultInterpreterPath' | 'autoDiscovery';
}
/**
* Error information when a user-configured setting could not be applied.
*/
export interface SettingResolutionError {
/** The setting that failed */
setting: 'pythonProjects' | 'defaultEnvManager' | 'defaultInterpreterPath';
/** The configured value */
configuredValue: string;
/** Reason for failure */
reason: string;
}
/**
* Core priority chain logic shared between workspace folder and global resolution.
*
* @param scope - The workspace folder URI (for workspace scope) or undefined (for global scope)
* @param envManagers - The environment managers registry
* @param projectManager - The project manager for pythonProjects[] lookups (only used for workspace scope)
* @param nativeFinder - Native Python finder for path resolution
* @param api - The Python environment API
* @returns The resolved PriorityChainResult and any errors encountered
*/
async function resolvePriorityChainCore(
scope: Uri | undefined,
envManagers: EnvironmentManagers,
projectManager: PythonProjectManager | undefined,
nativeFinder: NativePythonFinder,
api: PythonEnvironmentApi,
): Promise<{ result: PriorityChainResult; errors: SettingResolutionError[] }> {
const errors: SettingResolutionError[] = [];
const logPrefix = scope ? `[priorityChain] ${scope.fsPath}` : '[priorityChain:global]';
// PRIORITY 1: Check pythonProjects[] for this workspace path (workspace scope only)
if (scope && projectManager) {
const projectManagerId = getProjectSpecificEnvManager(projectManager, scope);
if (projectManagerId) {
const manager = envManagers.getEnvironmentManager(projectManagerId);
if (manager) {
traceVerbose(`${logPrefix} Priority 1: Using pythonProjects[] manager: ${projectManagerId}`);
return { result: { manager, source: 'pythonProjects' }, errors };
}
const error: SettingResolutionError = {
setting: 'pythonProjects',
configuredValue: projectManagerId,
reason: `Environment manager '${projectManagerId}' is not registered`,
};
errors.push(error);
traceWarn(`${logPrefix} pythonProjects[] manager '${projectManagerId}' not found, trying next priority`);
}
}
// PRIORITY 2: User-configured defaultEnvManager (skip if only fallback)
const userConfiguredManager = getUserConfiguredSetting<string>('python-envs', 'defaultEnvManager', scope);
if (userConfiguredManager) {
const manager = envManagers.getEnvironmentManager(userConfiguredManager);
if (manager) {
traceVerbose(`${logPrefix} Priority 2: Using user-configured defaultEnvManager: ${userConfiguredManager}`);
return { result: { manager, source: 'defaultEnvManager' }, errors };
}
const error: SettingResolutionError = {
setting: 'defaultEnvManager',
configuredValue: userConfiguredManager,
reason: `Environment manager '${userConfiguredManager}' is not registered`,
};
errors.push(error);
traceWarn(`${logPrefix} defaultEnvManager '${userConfiguredManager}' not found, trying next priority`);
}
// PRIORITY 3: User-configured python.defaultInterpreterPath
const userInterpreterPath = getUserConfiguredSetting<string>('python', 'defaultInterpreterPath', scope);
if (userInterpreterPath) {
const expandedInterpreterPath = resolveVariables(userInterpreterPath, scope);
if (expandedInterpreterPath.includes('${')) {
traceWarn(
`${logPrefix} defaultInterpreterPath '${userInterpreterPath}' contains unresolved variables, falling back to auto-discovery`,
);
const error: SettingResolutionError = {
setting: 'defaultInterpreterPath',
configuredValue: userInterpreterPath,
reason: `Path contains unresolved variables`,
};
errors.push(error);
} else {
const resolved = await tryResolveInterpreterPath(
nativeFinder,
api,
expandedInterpreterPath,
envManagers,
);
if (resolved) {
traceVerbose(`${logPrefix} Priority 3: Using defaultInterpreterPath: ${userInterpreterPath}`);
return { result: resolved, errors };
}
const error: SettingResolutionError = {
setting: 'defaultInterpreterPath',
configuredValue: userInterpreterPath,
reason: `Could not resolve interpreter path '${userInterpreterPath}'`,
};
errors.push(error);
traceWarn(
`${logPrefix} defaultInterpreterPath '${userInterpreterPath}' unresolvable, falling back to auto-discovery`,
);
}
}
// PRIORITY 4: Auto-discovery (no user-configured settings matched)
const autoDiscoverResult = await autoDiscoverEnvironment(scope, envManagers);
return { result: autoDiscoverResult, errors };
}
/**
* Determine the environment for a workspace folder by walking the priority chain:
*
* PRIORITY 1: pythonProjects[] entry for this path
* PRIORITY 2: User-configured defaultEnvManager (not fallback)
* PRIORITY 3: User-configured python.defaultInterpreterPath
* PRIORITY 4: Auto-discovery (local venv → global Python)
*
* Returns the manager (and optionally specific environment) without persisting to settings.
*
* @param scope - The workspace folder URI to resolve
* @param envManagers - The environment managers registry
* @param projectManager - The project manager for pythonProjects[] lookups
* @param nativeFinder - Native Python finder for path resolution
* @param api - The Python environment API
*/
export async function resolveEnvironmentByPriority(
scope: Uri,
envManagers: EnvironmentManagers,
projectManager: PythonProjectManager,
nativeFinder: NativePythonFinder,
api: PythonEnvironmentApi,
): Promise<PriorityChainResult> {
const { result } = await resolvePriorityChainCore(scope, envManagers, projectManager, nativeFinder, api);
return result;
}
/**
* Determine the environment for global scope (no workspace folder) by walking the priority chain:
*
* PRIORITY 1: (Skipped - pythonProjects[] doesn't apply to global scope)
* PRIORITY 2: User-configured defaultEnvManager (not fallback)
* PRIORITY 3: User-configured python.defaultInterpreterPath
* PRIORITY 4: Auto-discovery (system Python)
*
* Returns the manager (and optionally specific environment) without persisting to settings.
*
* @param envManagers - The environment managers registry
* @param nativeFinder - Native Python finder for path resolution
* @param api - The Python environment API
*/
export async function resolveGlobalEnvironmentByPriority(
envManagers: EnvironmentManagers,
nativeFinder: NativePythonFinder,
api: PythonEnvironmentApi,
): Promise<PriorityChainResult> {
const { result } = await resolvePriorityChainCore(undefined, envManagers, undefined, nativeFinder, api);
return result;
}
/**
* Auto-discovery for any scope: try local venv first (if scope provided), then fall back to system manager.
*/
async function autoDiscoverEnvironment(
scope: Uri | undefined,
envManagers: EnvironmentManagers,
): Promise<PriorityChainResult> {
// Try venv manager first for local environments (workspace scope only)
if (scope) {
const venvManager = envManagers.getEnvironmentManager(VENV_MANAGER_ID);
if (venvManager) {
try {
const localEnv = await venvManager.get(scope);
if (localEnv) {
return { manager: venvManager, environment: localEnv, source: 'autoDiscovery' };
}
} catch (err) {
traceError(`[autoDiscover] Failed to check venv manager: ${err}`);
}
}
}
// Fall back to system manager
const systemManager = envManagers.getEnvironmentManager(SYSTEM_MANAGER_ID);
if (systemManager) {
return { manager: systemManager, source: 'autoDiscovery' };
}
// Last resort: use any available manager
const anyManager = envManagers.managers[0];
if (anyManager) {
traceWarn(`[autoDiscover] No venv or system manager available, using fallback manager: ${anyManager.id}`);
return { manager: anyManager, source: 'autoDiscovery' };
}
// This should never happen if managers are registered properly
throw new Error('No environment managers available');
}
/**
* Called once at extension activation. Runs priority chain for all workspace folders
* AND the global scope, and caches results WITHOUT writing to settings.json.
*
* This ensures users see an interpreter immediately while respecting:
* - Existing project-specific settings (pythonProjects[])
* - User's defaultEnvManager preference
* - Legacy defaultInterpreterPath migration
* - Auto-discovered local environments
*
* If user-configured settings cannot be applied, shows a warning notification
* with an option to open settings.
*
* @param envManagers - The environment managers registry
* @param projectManager - The project manager
* @param nativeFinder - Native Python finder for path resolution
* @param api - The Python environment API
*/
export async function applyInitialEnvironmentSelection(
envManagers: EnvironmentManagers,
projectManager: PythonProjectManager,
nativeFinder: NativePythonFinder,
api: PythonEnvironmentApi,
): Promise<void> {
const folders = getWorkspaceFolders() ?? [];
traceInfo(
`[interpreterSelection] Applying initial environment selection for ${folders.length} workspace folder(s)`,
);
const allErrors: SettingResolutionError[] = [];
for (const folder of folders) {
try {
const { result, errors } = await resolvePriorityChainCore(
folder.uri,
envManagers,
projectManager,
nativeFinder,
api,
);
allErrors.push(...errors);
// Get the specific environment if not already resolved
const env = result.environment ?? (await result.manager.get(folder.uri));
// Cache only — NO settings.json write (shouldPersistSettings = false)
await envManagers.setEnvironment(folder.uri, env, false);
traceInfo(
`[interpreterSelection] ${folder.name}: ${env?.displayName ?? 'none'} (source: ${result.source})`,
);
} catch (err) {
traceError(`[interpreterSelection] Failed to set environment for ${folder.uri.fsPath}: ${err}`);
}
}
// Also apply initial selection for global scope (no workspace folder)
// This ensures defaultInterpreterPath is respected even without a workspace
try {
const { result, errors } = await resolvePriorityChainCore(undefined, envManagers, undefined, nativeFinder, api);
allErrors.push(...errors);
// Get the specific environment if not already resolved
const env = result.environment ?? (await result.manager.get(undefined));
// Cache only — NO settings.json write (shouldPersistSettings = false)
await envManagers.setEnvironments('global', env, false);
traceInfo(`[interpreterSelection] global: ${env?.displayName ?? 'none'} (source: ${result.source})`);
} catch (err) {
traceError(`[interpreterSelection] Failed to set global environment: ${err}`);
}
// Notify user if any settings could not be applied
if (allErrors.length > 0) {
await notifyUserOfSettingErrors(allErrors);
}
}
/**
* Notify the user when their configured settings could not be applied.
* Shows a warning message with an option to open settings.
*/
async function notifyUserOfSettingErrors(errors: SettingResolutionError[]): Promise<void> {
// Group errors by setting type to avoid spamming the user
const uniqueSettings = [...new Set(errors.map((e) => e.setting))];
for (const setting of uniqueSettings) {
const settingErrors = errors.filter((e) => e.setting === setting);
const firstError = settingErrors[0];
let message: string;
let settingKey: string;
switch (setting) {
case 'pythonProjects':
message = l10n.t(
"Python project setting for environment manager '{0}' could not be applied: {1}",
firstError.configuredValue,
firstError.reason,
);
settingKey = 'python-envs.pythonProjects';
break;
case 'defaultEnvManager':
message = l10n.t(
"Default environment manager '{0}' could not be applied: {1}",
firstError.configuredValue,
firstError.reason,
);
settingKey = 'python-envs.defaultEnvManager';
break;
case 'defaultInterpreterPath':
message = l10n.t(
"Default interpreter path '{0}' could not be resolved: {1}",
firstError.configuredValue,
firstError.reason,
);
settingKey = 'python.defaultInterpreterPath';
break;
default:
continue;
}
const openSettings = l10n.t('Open Settings');
const result = await showWarningMessage(message, openSettings);
if (result === openSettings) {
await commands.executeCommand('workbench.action.openSettings', settingKey);
}
}
}
/**
* Extract the pythonProjects[] setting lookup into a dedicated function.
* Returns the manager ID if found in pythonProjects[] for the given scope, else undefined.
*/
function getProjectSpecificEnvManager(projectManager: PythonProjectManager, scope: Uri): string | undefined {
const config = getConfiguration('python-envs', scope);
const overrides = config.get<PythonProjectSettings[]>('pythonProjects', []);
if (overrides.length > 0) {
const pw = projectManager.get(scope);
const w = getWorkspaceFolder(scope);
if (pw && w) {
const pwPath = path.resolve(pw.uri.fsPath);
const matching = overrides.find((s) => path.resolve(w.uri.fsPath, s.path) === pwPath);
if (matching && matching.envManager && matching.envManager.length > 0) {
return matching.envManager;
}
}
}
return undefined;
}
/**
* Try to resolve an interpreter path via nativeFinder and return a PriorityChainResult.
* Returns undefined if resolution fails.
*/
async function tryResolveInterpreterPath(
nativeFinder: NativePythonFinder,
api: PythonEnvironmentApi,
interpreterPath: string,
envManagers: EnvironmentManagers,
): Promise<PriorityChainResult | undefined> {
try {
const resolved: NativeEnvInfo = await nativeFinder.resolve(interpreterPath);
if (resolved && resolved.executable) {
const resolvedEnv = await api.resolveEnvironment(Uri.file(resolved.executable));
// Find the appropriate manager - prefer the one from the resolved env, fall back to system
let manager = envManagers.managers.find((m) => m.id === resolvedEnv?.envId.managerId);
if (!manager) {
manager = envManagers.getEnvironmentManager(SYSTEM_MANAGER_ID);
}
if (manager && resolvedEnv) {
// Create a wrapper environment that uses the user's specified path
const newEnv: PythonEnvironment = {
envId: {
id: `defaultInterpreterPath:${interpreterPath}`,
managerId: manager.id,
},
name: 'defaultInterpreterPath: ' + (resolved.version ?? ''),
displayName: 'defaultInterpreterPath: ' + (resolved.version ?? ''),
version: resolved.version ?? '',
displayPath: interpreterPath,
environmentPath: Uri.file(interpreterPath),
sysPrefix: resolved.prefix ?? '',
execInfo: {
run: {
executable: interpreterPath,
},
},
};
traceVerbose(
`[tryResolveInterpreterPath] Resolved '${interpreterPath}' to ${resolved.executable} (${resolved.version})`,
);
return { manager, environment: newEnv, source: 'defaultInterpreterPath' };
}
}
traceVerbose(
`[tryResolveInterpreterPath] Could not resolve '${interpreterPath}' - no executable or manager found`,
);
} catch (err) {
traceVerbose(`[tryResolveInterpreterPath] Resolution failed for '${interpreterPath}': ${err}`);
}
return undefined;
}
/**
* Register a configuration change listener for interpreter-related settings. When relevant settings change (defaultInterpreterPath, defaultEnvManager, pythonProjects),
* re-run the priority chain to apply the new settings immediately.
*/
export function registerInterpreterSettingsChangeListener(
envManagers: EnvironmentManagers,
projectManager: PythonProjectManager,
nativeFinder: NativePythonFinder,
api: PythonEnvironmentApi,
): Disposable {
return onDidChangeConfiguration(async (e: ConfigurationChangeEvent) => {
const relevantSettingsChanged =
e.affectsConfiguration('python.defaultInterpreterPath') ||
e.affectsConfiguration('python-envs.defaultEnvManager') ||
e.affectsConfiguration('python-envs.pythonProjects');
if (relevantSettingsChanged) {
traceInfo(
'[interpreterSelection] Interpreter settings changed, re-evaluating priority chain for all scopes',
);
// Re-run the interpreter selection priority chain to apply new settings immediately
await applyInitialEnvironmentSelection(envManagers, projectManager, nativeFinder, api);
}
});
}