-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathextension.ts
More file actions
511 lines (478 loc) · 23.7 KB
/
extension.ts
File metadata and controls
511 lines (478 loc) · 23.7 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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
import { commands, ExtensionContext, extensions, LogOutputChannel, Terminal, Uri, window, workspace } from 'vscode';
import { PythonEnvironment, PythonEnvironmentApi, PythonProjectCreator } from './api';
import { ensureCorrectVersion } from './common/extVersion';
import { registerLogger, traceError, traceInfo } from './common/logging';
import { clearPersistentState, setPersistentState } from './common/persistentState';
import { newProjectSelection } from './common/pickers/managers';
import { StopWatch } from './common/stopWatch';
import { EventNames } from './common/telemetry/constants';
import { sendManagerSelectionTelemetry } from './common/telemetry/helpers';
import { sendTelemetryEvent } from './common/telemetry/sender';
import { createDeferred } from './common/utils/deferred';
import {
activeTerminal,
createLogOutputChannel,
onDidChangeActiveTerminal,
onDidChangeTerminalShellIntegration,
} from './common/window.apis';
import { createManagerReady } from './features/common/managerReady';
import { AutoFindProjects } from './features/creators/autoFindProjects';
import { ExistingProjects } from './features/creators/existingProjects';
import { NewPackageProject } from './features/creators/newPackageProject';
import { NewScriptProject } from './features/creators/newScriptProject';
import { ProjectCreatorsImpl } from './features/creators/projectCreators';
import {
addPythonProjectCommand,
copyPathToClipboard,
createAnyEnvironmentCommand,
createEnvironmentCommand,
createTerminalCommand,
getPackageCommandOptions,
handlePackageUninstall,
refreshPackagesCommand,
removeEnvironmentCommand,
removePythonProject,
revealProjectInExplorer,
runAsTaskCommand,
runInDedicatedTerminalCommand,
runInTerminalCommand,
setEnvironmentCommand,
setEnvManagerCommand,
setPackageManagerCommand,
} from './features/envCommands';
import { PythonEnvironmentManagers } from './features/envManagers';
import { EnvVarManager, PythonEnvVariableManager } from './features/execution/envVariableManager';
import { PythonProjectManagerImpl } from './features/projectManager';
import { getPythonApi, setPythonApi } from './features/pythonApi';
import { registerCompletionProvider } from './features/settings/settingCompletions';
import { setActivateMenuButtonContext } from './features/terminal/activateMenuButton';
import { normalizeShellPath } from './features/terminal/shells/common/shellUtils';
import {
clearShellProfileCache,
createShellEnvProviders,
createShellStartupProviders,
} from './features/terminal/shells/providers';
import { ShellStartupActivationVariablesManagerImpl } from './features/terminal/shellStartupActivationVariablesManager';
import { cleanupStartupScripts } from './features/terminal/shellStartupSetupHandlers';
import { TerminalActivationImpl } from './features/terminal/terminalActivationState';
import { TerminalManager, TerminalManagerImpl } from './features/terminal/terminalManager';
import { getEnvironmentForTerminal } from './features/terminal/utils';
import { EnvManagerView } from './features/views/envManagersView';
import { ProjectView } from './features/views/projectView';
import { PythonStatusBarImpl } from './features/views/pythonStatusBar';
import { updateViewsAndStatus } from './features/views/revealHandler';
import { ProjectItem } from './features/views/treeViewItems';
import { EnvironmentManagers, ProjectCreators, PythonProjectManager } from './internal.api';
import { registerSystemPythonFeatures } from './managers/builtin/main';
import { SysPythonManager } from './managers/builtin/sysPythonManager';
import { createNativePythonFinder, NativePythonFinder } from './managers/common/nativePythonFinder';
import { registerCondaFeatures } from './managers/conda/main';
import { registerPoetryFeatures } from './managers/poetry/main';
import { registerPyenvFeatures } from './managers/pyenv/main';
/**
* Collects relevant Python environment information for issue reporting
*/
async function collectEnvironmentInfo(
context: ExtensionContext,
envManagers: EnvironmentManagers,
projectManager: PythonProjectManager,
): Promise<string> {
const info: string[] = [];
try {
// Extension version
const extensionVersion = context.extension?.packageJSON?.version || 'unknown';
info.push(`Extension Version: ${extensionVersion}`);
// Python extension version
const pythonExtension = extensions.getExtension('ms-python.python');
const pythonVersion = pythonExtension?.packageJSON?.version || 'not installed';
info.push(`Python Extension Version: ${pythonVersion}`);
// Environment managers
const managers = envManagers.managers;
info.push(`\nRegistered Environment Managers (${managers.length}):`);
managers.forEach((manager) => {
info.push(` - ${manager.id} (${manager.displayName})`);
});
// Available environments
const allEnvironments: PythonEnvironment[] = [];
for (const manager of managers) {
try {
const envs = await manager.getEnvironments('all');
allEnvironments.push(...envs);
} catch (err) {
info.push(` Error getting environments from ${manager.id}: ${err}`);
}
}
info.push(`\nTotal Available Environments: ${allEnvironments.length}`);
if (allEnvironments.length > 0) {
info.push('Environment Details:');
allEnvironments.slice(0, 10).forEach((env, index) => {
info.push(` ${index + 1}. ${env.displayName} (${env.version}) - ${env.displayPath}`);
});
if (allEnvironments.length > 10) {
info.push(` ... and ${allEnvironments.length - 10} more environments`);
}
}
// Python projects
const projects = projectManager.getProjects();
info.push(`\nPython Projects (${projects.length}):`);
for (let index = 0; index < projects.length; index++) {
const project = projects[index];
info.push(` ${index + 1}. ${project.uri.fsPath}`);
try {
const env = await envManagers.getEnvironment(project.uri);
if (env) {
info.push(` Environment: ${env.displayName}`);
}
} catch (err) {
info.push(` Error getting environment: ${err}`);
}
}
// Current settings (non-sensitive)
const config = workspace.getConfiguration('python-envs');
info.push('\nExtension Settings:');
info.push(` Default Environment Manager: ${config.get('defaultEnvManager')}`);
info.push(` Default Package Manager: ${config.get('defaultPackageManager')}`);
info.push(` Terminal Auto Activation: ${config.get('terminal.autoActivationType')}`);
} catch (err) {
info.push(`\nError collecting environment information: ${err}`);
}
return info.join('\n');
}
export async function activate(context: ExtensionContext): Promise<PythonEnvironmentApi> {
const start = new StopWatch();
// Attempt to set setting of config.python.useEnvironmentsExtension to true
try {
const config = workspace.getConfiguration('python');
await config.update('useEnvironmentsExtension', true, true);
} catch (err) {
traceError(
'Failed to set config.python.useEnvironmentsExtension to true. Please do so manually in your user settings now to ensure the Python environment extension is enabled during upcoming experimentation.',
err,
);
}
// Logging should be set up before anything else.
const outputChannel: LogOutputChannel = createLogOutputChannel('Python Environments');
context.subscriptions.push(outputChannel, registerLogger(outputChannel));
ensureCorrectVersion();
// Setup the persistent state for the extension.
setPersistentState(context);
const statusBar = new PythonStatusBarImpl();
context.subscriptions.push(statusBar);
const projectManager: PythonProjectManager = new PythonProjectManagerImpl();
context.subscriptions.push(projectManager);
// Helper function to check if a resource is an existing Python project
const isExistingProject = (uri: Uri | undefined): boolean => {
if (!uri) {
return false;
}
return projectManager.get(uri) !== undefined;
};
const envVarManager: EnvVarManager = new PythonEnvVariableManager(projectManager);
context.subscriptions.push(envVarManager);
const envManagers: EnvironmentManagers = new PythonEnvironmentManagers(projectManager);
createManagerReady(envManagers, projectManager, context.subscriptions);
context.subscriptions.push(envManagers);
const terminalActivation = new TerminalActivationImpl();
const shellEnvsProviders = createShellEnvProviders();
const shellStartupProviders = createShellStartupProviders();
const terminalManager: TerminalManager = new TerminalManagerImpl(
terminalActivation,
shellEnvsProviders,
shellStartupProviders,
);
context.subscriptions.push(terminalActivation, terminalManager);
const projectCreators: ProjectCreators = new ProjectCreatorsImpl();
context.subscriptions.push(
projectCreators,
projectCreators.registerPythonProjectCreator(new ExistingProjects(projectManager)),
projectCreators.registerPythonProjectCreator(new AutoFindProjects(projectManager)),
projectCreators.registerPythonProjectCreator(new NewPackageProject(envManagers, projectManager)),
projectCreators.registerPythonProjectCreator(new NewScriptProject(projectManager)),
);
setPythonApi(envManagers, projectManager, projectCreators, terminalManager, envVarManager);
const api = await getPythonApi();
const sysPythonManager = createDeferred<SysPythonManager>();
const managerView = new EnvManagerView(envManagers);
context.subscriptions.push(managerView);
const workspaceView = new ProjectView(envManagers, projectManager);
context.subscriptions.push(workspaceView);
workspaceView.initialize();
const monitoredTerminals = new Map<Terminal, PythonEnvironment>();
const shellStartupVarsMgr = new ShellStartupActivationVariablesManagerImpl(
context.environmentVariableCollection,
shellEnvsProviders,
api,
);
context.subscriptions.push(
shellStartupVarsMgr,
registerCompletionProvider(envManagers),
commands.registerCommand('python-envs.terminal.revertStartupScriptChanges', async () => {
await cleanupStartupScripts(shellStartupProviders);
}),
commands.registerCommand('python-envs.viewLogs', () => outputChannel.show()),
commands.registerCommand('python-envs.refreshAllManagers', async () => {
await Promise.all(envManagers.managers.map((m) => m.refresh(undefined)));
}),
commands.registerCommand('python-envs.refreshPackages', async (item) => {
await refreshPackagesCommand(item, envManagers);
}),
commands.registerCommand('python-envs.create', async (item) => {
// Telemetry: record environment creation attempt with selected manager
let managerId = 'unknown';
if (item && item.manager && item.manager.id) {
managerId = item.manager.id;
}
sendTelemetryEvent(EventNames.CREATE_ENVIRONMENT, undefined, {
manager: managerId,
triggeredLocation: 'createSpecifiedCommand',
});
return await createEnvironmentCommand(item, envManagers, projectManager);
}),
commands.registerCommand('python-envs.createAny', async (options) => {
// Telemetry: record environment creation attempt with no specific manager
sendTelemetryEvent(EventNames.CREATE_ENVIRONMENT, undefined, {
manager: 'none',
triggeredLocation: 'createAnyCommand',
});
return await createAnyEnvironmentCommand(
envManagers,
projectManager,
options ?? { selectEnvironment: true },
);
}),
commands.registerCommand('python-envs.remove', async (item) => {
await removeEnvironmentCommand(item, envManagers);
}),
commands.registerCommand('python-envs.packages', async (options: unknown) => {
const { environment, packageManager } = await getPackageCommandOptions(
options,
envManagers,
projectManager,
);
try {
packageManager.manage(environment, { install: [] });
} catch (err) {
traceError('Error when running command python-envs.packages', err);
}
}),
commands.registerCommand('python-envs.uninstallPackage', async (context: unknown) => {
await handlePackageUninstall(context, envManagers);
}),
commands.registerCommand('python-envs.set', async (item) => {
await setEnvironmentCommand(item, envManagers, projectManager);
}),
commands.registerCommand('python-envs.setEnv', async (item) => {
await setEnvironmentCommand(item, envManagers, projectManager);
}),
commands.registerCommand('python-envs.setEnvManager', async () => {
await setEnvManagerCommand(envManagers, projectManager);
}),
commands.registerCommand('python-envs.setPkgManager', async () => {
await setPackageManagerCommand(envManagers, projectManager);
}),
commands.registerCommand('python-envs.addPythonProject', async () => {
await addPythonProjectCommand(undefined, projectManager, envManagers, projectCreators);
const totalProjectCount = projectManager.getProjects().length + 1;
sendTelemetryEvent(EventNames.ADD_PROJECT, undefined, {
template: 'none',
quickCreate: false,
totalProjectCount,
triggeredLocation: 'add',
});
}),
commands.registerCommand('python-envs.addPythonProjectGivenResource', async (resource) => {
// Set context to show/hide menu item depending on whether the resource is already a Python project
if (resource instanceof Uri) {
commands.executeCommand('setContext', 'python-envs:isExistingProject', isExistingProject(resource));
}
await addPythonProjectCommand(resource, projectManager, envManagers, projectCreators);
const totalProjectCount = projectManager.getProjects().length + 1;
sendTelemetryEvent(EventNames.ADD_PROJECT, undefined, {
template: 'none',
quickCreate: false,
totalProjectCount,
triggeredLocation: 'addGivenResource',
});
}),
commands.registerCommand('python-envs.removePythonProject', async (item) => {
// Clear environment association before removing project
if (item instanceof ProjectItem) {
const uri = item.project.uri;
const manager = envManagers.getEnvironmentManager(uri);
if (manager) {
manager.set(uri, undefined);
} else {
traceError(`No environment manager found for ${uri.fsPath}`);
}
}
await removePythonProject(item, projectManager);
}),
commands.registerCommand('python-envs.clearCache', async () => {
await clearPersistentState();
await envManagers.clearCache(undefined);
await clearShellProfileCache(shellStartupProviders);
}),
commands.registerCommand('python-envs.runInTerminal', (item) => {
return runInTerminalCommand(item, api, terminalManager);
}),
commands.registerCommand('python-envs.runInDedicatedTerminal', (item) => {
return runInDedicatedTerminalCommand(item, api, terminalManager);
}),
commands.registerCommand('python-envs.runAsTask', (item) => {
return runAsTaskCommand(item, api);
}),
commands.registerCommand('python-envs.createTerminal', (item) => {
return createTerminalCommand(item, api, terminalManager);
}),
commands.registerCommand('python-envs.copyEnvPath', async (item) => {
await copyPathToClipboard(item);
}),
commands.registerCommand('python-envs.copyProjectPath', async (item) => {
await copyPathToClipboard(item);
}),
commands.registerCommand('python-envs.revealProjectInExplorer', async (item) => {
await revealProjectInExplorer(item);
}),
commands.registerCommand('python-envs.terminal.activate', async () => {
const terminal = activeTerminal();
if (terminal) {
const env = await getEnvironmentForTerminal(api, terminal);
if (env) {
await terminalManager.activate(terminal, env);
}
}
}),
commands.registerCommand('python-envs.terminal.deactivate', async () => {
const terminal = activeTerminal();
if (terminal) {
await terminalManager.deactivate(terminal);
}
}),
commands.registerCommand(
'python-envs.createNewProjectFromTemplate',
async (projectType: string, quickCreate: boolean, newProjectName: string, newProjectPath: string) => {
let projectTemplateName = projectType || 'unknown';
let triggeredLocation: 'templateCreate' = 'templateCreate';
let totalProjectCount = projectManager.getProjects().length + 1;
if (quickCreate) {
if (!projectType || !newProjectName || !newProjectPath) {
throw new Error('Project type, name, and path are required for quick create.');
}
const creators = projectCreators.getProjectCreators();
let selected: PythonProjectCreator | undefined;
if (projectType === 'python-package') {
selected = creators.find((c) => c.name === 'newPackage');
}
if (projectType === 'python-script') {
selected = creators.find((c) => c.name === 'newScript');
}
if (!selected) {
throw new Error(`Project creator for type "${projectType}" not found.`);
}
await selected.create({
quickCreate: true,
name: newProjectName,
rootUri: Uri.file(newProjectPath),
});
} else {
const selected = await newProjectSelection(projectCreators.getProjectCreators());
if (selected) {
projectTemplateName = selected.name || 'unknown';
await selected.create();
}
}
sendTelemetryEvent(EventNames.ADD_PROJECT, undefined, {
template: projectTemplateName,
quickCreate: quickCreate,
totalProjectCount,
triggeredLocation,
});
},
),
commands.registerCommand('python-envs.reportIssue', async () => {
try {
const issueData = await collectEnvironmentInfo(context, envManagers, projectManager);
await commands.executeCommand('workbench.action.openIssueReporter', {
extensionId: 'ms-python.vscode-python-envs',
issueTitle: '[Python Environments] ',
issueBody: `<!-- Please describe the issue you're experiencing -->\n\n<!-- The following information was automatically generated -->\n\n<details>\n<summary>Environment Information</summary>\n\n\`\`\`\n${issueData}\n\`\`\`\n\n</details>`,
});
} catch (error) {
window.showErrorMessage(`Failed to open issue reporter: ${error}`);
}
}),
terminalActivation.onDidChangeTerminalActivationState(async (e) => {
await setActivateMenuButtonContext(e.terminal, e.environment, e.activated);
}),
onDidChangeActiveTerminal(async (t) => {
if (t) {
const env = terminalActivation.getEnvironment(t) ?? (await getEnvironmentForTerminal(api, t));
if (env) {
await setActivateMenuButtonContext(t, env, terminalActivation.isActivated(t));
}
}
}),
window.onDidChangeActiveTextEditor(async () => {
updateViewsAndStatus(statusBar, workspaceView, managerView, api);
}),
envManagers.onDidChangeEnvironment(async () => {
updateViewsAndStatus(statusBar, workspaceView, managerView, api);
}),
envManagers.onDidChangeEnvironments(async () => {
updateViewsAndStatus(statusBar, workspaceView, managerView, api);
}),
envManagers.onDidChangeEnvironmentFiltered(async (e) => {
managerView.environmentChanged(e);
const location = e.uri?.fsPath ?? 'global';
traceInfo(
`Internal: Changed environment from ${e.old?.displayName} to ${e.new?.displayName} for: ${location}`,
);
updateViewsAndStatus(statusBar, workspaceView, managerView, api);
}),
onDidChangeTerminalShellIntegration(async (e) => {
const shellEnv = e.shellIntegration?.env;
if (!shellEnv) {
return;
}
const envVar = shellEnv.value;
if (envVar) {
if (envVar['VIRTUAL_ENV']) {
const envPath = normalizeShellPath(envVar['VIRTUAL_ENV'], e.terminal.state.shell);
const env = await api.resolveEnvironment(Uri.file(envPath));
if (env) {
monitoredTerminals.set(e.terminal, env);
terminalActivation.updateActivationState(e.terminal, env, true);
}
} else if (monitoredTerminals.has(e.terminal)) {
const env = monitoredTerminals.get(e.terminal);
if (env) {
terminalActivation.updateActivationState(e.terminal, env, false);
}
}
}
}),
);
/**
* Below are all the contributed features using the APIs.
*/
setImmediate(async () => {
// This is the finder that is used by all the built in environment managers
const nativeFinder: NativePythonFinder = await createNativePythonFinder(outputChannel, api, context);
context.subscriptions.push(nativeFinder);
const sysMgr = new SysPythonManager(nativeFinder, api, outputChannel);
sysPythonManager.resolve(sysMgr);
await Promise.all([
registerSystemPythonFeatures(nativeFinder, context.subscriptions, outputChannel, sysMgr),
registerCondaFeatures(nativeFinder, context.subscriptions, outputChannel),
registerPyenvFeatures(nativeFinder, context.subscriptions),
registerPoetryFeatures(nativeFinder, context.subscriptions, outputChannel),
shellStartupVarsMgr.initialize(),
]);
sendTelemetryEvent(EventNames.EXTENSION_MANAGER_REGISTRATION_DURATION, start.elapsedTime);
await terminalManager.initialize(api);
sendManagerSelectionTelemetry(projectManager);
});
sendTelemetryEvent(EventNames.EXTENSION_ACTIVATION_DURATION, start.elapsedTime);
return api;
}
export function deactivate() {}