forked from microsoft/vscode-python
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpythonInterpreter.ts
More file actions
326 lines (305 loc) · 14.6 KB
/
pythonInterpreter.ts
File metadata and controls
326 lines (305 loc) · 14.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
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// eslint-disable-next-line max-classes-per-file
import { inject, injectable } from 'inversify';
import { DiagnosticSeverity, l10n } from 'vscode';
import '../../../common/extensions';
import * as path from 'path';
import { IConfigurationService, IDisposableRegistry, IInterpreterPathService, Resource } from '../../../common/types';
import { IInterpreterService } from '../../../interpreter/contracts';
import { IServiceContainer } from '../../../ioc/types';
import { BaseDiagnostic, BaseDiagnosticsService } from '../base';
import { IDiagnosticsCommandFactory } from '../commands/types';
import { DiagnosticCodes } from '../constants';
import { DiagnosticCommandPromptHandlerServiceId, MessageCommandPrompt } from '../promptHandler';
import {
DiagnosticScope,
IDiagnostic,
IDiagnosticCommand,
IDiagnosticHandlerService,
IDiagnosticMessageOnCloseHandler,
} from '../types';
import { Common, Interpreters } from '../../../common/utils/localize';
import { Commands } from '../../../common/constants';
import { ICommandManager, IWorkspaceService } from '../../../common/application/types';
import { sendTelemetryEvent } from '../../../telemetry';
import { EventName } from '../../../telemetry/constants';
import { IExtensionSingleActivationService } from '../../../activation/types';
import { cache } from '../../../common/utils/decorators';
import { noop } from '../../../common/utils/misc';
import { getEnvironmentVariable, getOSType, OSType } from '../../../common/utils/platform';
import { IFileSystem } from '../../../common/platform/types';
import { traceError, traceWarn } from '../../../logging';
import { getExecutable } from '../../../common/process/internal/python';
import { getSearchPathEnvVarNames } from '../../../common/utils/exec';
import { IProcessServiceFactory } from '../../../common/process/types';
import { normCasePath } from '../../../common/platform/fs-paths';
import { useEnvExtension } from '../../../envExt/api.internal';
const messages = {
[DiagnosticCodes.NoPythonInterpretersDiagnostic]: l10n.t(
'No Python interpreter is selected. Please select a Python interpreter to enable features such as IntelliSense, linting, and debugging.',
),
[DiagnosticCodes.InvalidPythonInterpreterDiagnostic]: l10n.t(
'An Invalid Python interpreter is selected{0}, please try changing it to enable features such as IntelliSense, linting, and debugging. See output for more details regarding why the interpreter is invalid.',
),
[DiagnosticCodes.InvalidComspecDiagnostic]: l10n.t(
'We detected an issue with one of your environment variables that breaks features such as IntelliSense, linting and debugging. Try setting the "ComSpec" variable to a valid Command Prompt path in your system to fix it.',
),
[DiagnosticCodes.IncompletePathVarDiagnostic]: l10n.t(
'We detected an issue with "Path" environment variable that breaks features such as IntelliSense, linting and debugging. Please edit it to make sure it contains the "System32" subdirectories.',
),
[DiagnosticCodes.DefaultShellErrorDiagnostic]: l10n.t(
'We detected an issue with your default shell that breaks features such as IntelliSense, linting and debugging. Try resetting "ComSpec" and "Path" environment variables to fix it.',
),
};
export class InvalidPythonInterpreterDiagnostic extends BaseDiagnostic {
constructor(
code: DiagnosticCodes.NoPythonInterpretersDiagnostic | DiagnosticCodes.InvalidPythonInterpreterDiagnostic,
resource: Resource,
workspaceService: IWorkspaceService,
scope = DiagnosticScope.WorkspaceFolder,
) {
let formatArg = '';
if (
workspaceService.workspaceFile &&
workspaceService.workspaceFolders &&
workspaceService.workspaceFolders?.length > 1
) {
// Specify folder name in case of multiroot scenarios
const folder = workspaceService.getWorkspaceFolder(resource);
if (folder) {
formatArg = ` ${l10n.t('for workspace')} ${path.basename(folder.uri.fsPath)}`;
}
}
super(code, messages[code].format(formatArg), DiagnosticSeverity.Error, scope, resource, undefined, 'always');
}
}
type DefaultShellDiagnostics =
| DiagnosticCodes.InvalidComspecDiagnostic
| DiagnosticCodes.IncompletePathVarDiagnostic
| DiagnosticCodes.DefaultShellErrorDiagnostic;
export class DefaultShellDiagnostic extends BaseDiagnostic {
constructor(code: DefaultShellDiagnostics, resource: Resource, scope = DiagnosticScope.Global) {
super(code, messages[code], DiagnosticSeverity.Error, scope, resource, undefined, 'always');
}
}
export const InvalidPythonInterpreterServiceId = 'InvalidPythonInterpreterServiceId';
@injectable()
export class InvalidPythonInterpreterService extends BaseDiagnosticsService
implements IExtensionSingleActivationService {
public readonly supportedWorkspaceTypes = { untrustedWorkspace: false, virtualWorkspace: true };
constructor(
@inject(IServiceContainer) serviceContainer: IServiceContainer,
@inject(IDisposableRegistry) disposableRegistry: IDisposableRegistry,
) {
super(
[
DiagnosticCodes.NoPythonInterpretersDiagnostic,
DiagnosticCodes.InvalidPythonInterpreterDiagnostic,
DiagnosticCodes.InvalidComspecDiagnostic,
DiagnosticCodes.IncompletePathVarDiagnostic,
DiagnosticCodes.DefaultShellErrorDiagnostic,
],
serviceContainer,
disposableRegistry,
false,
);
}
public async activate(): Promise<void> {
const commandManager = this.serviceContainer.get<ICommandManager>(ICommandManager);
this.disposableRegistry.push(
commandManager.registerCommand(Commands.TriggerEnvironmentSelection, (resource: Resource) =>
this.triggerEnvSelectionIfNecessary(resource),
),
);
const interpreterService = this.serviceContainer.get<IInterpreterService>(IInterpreterService);
this.disposableRegistry.push(
interpreterService.onDidChangeInterpreterConfiguration((e) =>
commandManager.executeCommand(Commands.TriggerEnvironmentSelection, e).then(noop, noop),
),
);
}
public async diagnose(resource: Resource): Promise<IDiagnostic[]> {
return this.diagnoseDefaultShell(resource);
}
public async _manualDiagnose(resource: Resource): Promise<IDiagnostic[]> {
const workspaceService = this.serviceContainer.get<IWorkspaceService>(IWorkspaceService);
const interpreterService = this.serviceContainer.get<IInterpreterService>(IInterpreterService);
const diagnostics = await this.diagnoseDefaultShell(resource);
if (diagnostics.length > 0) {
return diagnostics;
}
const hasInterpreters = await interpreterService.hasInterpreters();
const interpreterPathService = this.serviceContainer.get<IInterpreterPathService>(IInterpreterPathService);
const isInterpreterSetToDefault = interpreterPathService.get(resource) === 'python';
if (!hasInterpreters && isInterpreterSetToDefault) {
if (useEnvExtension()) {
traceWarn(Interpreters.envExtDiscoveryNoEnvironments);
}
return [
new InvalidPythonInterpreterDiagnostic(
DiagnosticCodes.NoPythonInterpretersDiagnostic,
resource,
workspaceService,
DiagnosticScope.Global,
),
];
}
const currentInterpreter = await interpreterService.getActiveInterpreter(resource);
if (!currentInterpreter) {
if (useEnvExtension()) {
traceWarn(Interpreters.envExtNoActiveEnvironment);
}
return [
new InvalidPythonInterpreterDiagnostic(
DiagnosticCodes.InvalidPythonInterpreterDiagnostic,
resource,
workspaceService,
),
];
}
return [];
}
public async triggerEnvSelectionIfNecessary(resource: Resource): Promise<boolean> {
const diagnostics = await this._manualDiagnose(resource);
if (!diagnostics.length) {
return true;
}
this.handle(diagnostics).ignoreErrors();
return false;
}
private async diagnoseDefaultShell(resource: Resource): Promise<IDiagnostic[]> {
if (getOSType() !== OSType.Windows) {
return [];
}
const interpreterService = this.serviceContainer.get<IInterpreterService>(IInterpreterService);
const currentInterpreter = await interpreterService.getActiveInterpreter(resource);
if (currentInterpreter) {
return [];
}
try {
await this.shellExecPython();
} catch (ex) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if ((ex as any).errno === -4058) {
// ENOENT (-4058) error is thrown by Node when the default shell is invalid.
traceError('ComSpec is likely set to an invalid value', getEnvironmentVariable('ComSpec'));
if (await this.isComspecInvalid()) {
return [new DefaultShellDiagnostic(DiagnosticCodes.InvalidComspecDiagnostic, resource)];
}
if (this.isPathVarIncomplete()) {
traceError('PATH env var appears to be incomplete', process.env.Path, process.env.PATH);
return [new DefaultShellDiagnostic(DiagnosticCodes.IncompletePathVarDiagnostic, resource)];
}
return [new DefaultShellDiagnostic(DiagnosticCodes.DefaultShellErrorDiagnostic, resource)];
}
}
return [];
}
private async isComspecInvalid() {
const comSpec = getEnvironmentVariable('ComSpec') ?? '';
const fs = this.serviceContainer.get<IFileSystem>(IFileSystem);
return fs.fileExists(comSpec).then((exists) => !exists);
}
// eslint-disable-next-line class-methods-use-this
private isPathVarIncomplete() {
const envVars = getSearchPathEnvVarNames();
const systemRoot = getEnvironmentVariable('SystemRoot') ?? 'C:\\WINDOWS';
const system32 = path.join(systemRoot, 'system32');
for (const envVar of envVars) {
const value = getEnvironmentVariable(envVar);
if (value && normCasePath(value).includes(normCasePath(system32))) {
return false;
}
}
return true;
}
@cache(-1, true)
// eslint-disable-next-line class-methods-use-this
private async shellExecPython() {
const configurationService = this.serviceContainer.get<IConfigurationService>(IConfigurationService);
const { pythonPath } = configurationService.getSettings();
const [args] = getExecutable();
const argv = [pythonPath, ...args];
// Concat these together to make a set of quoted strings
const quoted = argv.reduce(
(p, c) => (p ? `${p} ${c.toCommandArgumentForPythonExt()}` : `${c.toCommandArgumentForPythonExt()}`),
'',
);
const processServiceFactory = this.serviceContainer.get<IProcessServiceFactory>(IProcessServiceFactory);
const service = await processServiceFactory.create();
return service.shellExec(quoted, { timeout: 15000 });
}
@cache(1000, true) // This is to handle throttling of multiple events.
protected async onHandle(diagnostics: IDiagnostic[]): Promise<void> {
if (diagnostics.length === 0) {
return;
}
const messageService = this.serviceContainer.get<IDiagnosticHandlerService<MessageCommandPrompt>>(
IDiagnosticHandlerService,
DiagnosticCommandPromptHandlerServiceId,
);
await Promise.all(
diagnostics.map(async (diagnostic) => {
if (!this.canHandle(diagnostic)) {
return;
}
const commandPrompts = this.getCommandPrompts(diagnostic);
const onClose = getOnCloseHandler(diagnostic);
await messageService.handle(diagnostic, { commandPrompts, message: diagnostic.message, onClose });
}),
);
}
private getCommandPrompts(diagnostic: IDiagnostic): { prompt: string; command?: IDiagnosticCommand }[] {
const commandFactory = this.serviceContainer.get<IDiagnosticsCommandFactory>(IDiagnosticsCommandFactory);
if (
diagnostic.code === DiagnosticCodes.InvalidComspecDiagnostic ||
diagnostic.code === DiagnosticCodes.IncompletePathVarDiagnostic ||
diagnostic.code === DiagnosticCodes.DefaultShellErrorDiagnostic
) {
const links: Record<DefaultShellDiagnostics, string> = {
InvalidComspecDiagnostic: 'https://aka.ms/AAk3djo',
IncompletePathVarDiagnostic: 'https://aka.ms/AAk744c',
DefaultShellErrorDiagnostic: 'https://aka.ms/AAk7qix',
};
return [
{
prompt: Common.seeInstructions,
command: commandFactory.createCommand(diagnostic, {
type: 'launch',
options: links[diagnostic.code],
}),
},
];
}
const prompts = [
{
prompt: Common.selectPythonInterpreter,
command: commandFactory.createCommand(diagnostic, {
type: 'executeVSCCommand',
options: Commands.Set_Interpreter,
}),
},
];
if (diagnostic.code === DiagnosticCodes.InvalidPythonInterpreterDiagnostic) {
prompts.push({
prompt: Common.openOutputPanel,
command: commandFactory.createCommand(diagnostic, {
type: 'executeVSCCommand',
options: Commands.ViewOutput,
}),
});
}
return prompts;
}
}
function getOnCloseHandler(diagnostic: IDiagnostic): IDiagnosticMessageOnCloseHandler | undefined {
if (diagnostic.code === DiagnosticCodes.NoPythonInterpretersDiagnostic) {
return (response?: string) => {
sendTelemetryEvent(EventName.PYTHON_NOT_INSTALLED_PROMPT, undefined, {
selection: response ? 'Download' : 'Ignore',
});
};
}
return undefined;
}