forked from microsoft/vscode-python-installer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmoduleInstaller.ts
More file actions
211 lines (200 loc) · 9.28 KB
/
Copy pathmoduleInstaller.ts
File metadata and controls
211 lines (200 loc) · 9.28 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { injectable } from 'inversify';
import * as path from 'path';
import { CancellationToken, ProgressLocation, ProgressOptions } from 'vscode';
import { IInterpreterService } from '../../interpreter/contracts';
import { IServiceContainer } from '../../ioc/types';
import { traceError, traceLog } from '../../logging';
import { EnvironmentType, ModuleInstallerType } from '../../pythonEnvironments/info';
import { sendTelemetryEvent } from '../../telemetry';
import { EventName } from '../../telemetry/constants';
import { IApplicationShell } from '../application/types';
import { wrapCancellationTokens } from '../cancellation';
import { STANDARD_OUTPUT_CHANNEL } from '../constants';
import { IFileSystem } from '../platform/types';
import * as internalPython from '../process/internal/python';
import { ITerminalServiceFactory, TerminalCreationOptions } from '../terminal/types';
import { ExecutionInfo, IConfigurationService, IOutputChannel, Product } from '../types';
import { Products } from '../utils/localize';
import { isResource } from '../utils/misc';
import { ProductNames } from './productNames';
import { IModuleInstaller, InterpreterUri, ModuleInstallFlags } from './types';
@injectable()
export abstract class ModuleInstaller implements IModuleInstaller {
public abstract get priority(): number;
public abstract get name(): string;
public abstract get displayName(): string;
public abstract get type(): ModuleInstallerType;
constructor(protected serviceContainer: IServiceContainer) {}
public async installModule(
productOrModuleName: Product | string,
resource?: InterpreterUri,
cancel?: CancellationToken,
flags?: ModuleInstallFlags,
): Promise<void> {
const name =
typeof productOrModuleName == 'string'
? productOrModuleName
: translateProductToModule(productOrModuleName);
const productName = typeof productOrModuleName === 'string' ? name : ProductNames.get(productOrModuleName);
sendTelemetryEvent(EventName.PYTHON_INSTALL_PACKAGE, undefined, { installer: this.displayName, productName });
const uri = isResource(resource) ? resource : undefined;
const options: TerminalCreationOptions = {};
if (isResource(resource)) {
options.resource = uri;
} else {
options.interpreter = resource;
}
const executionInfo = await this.getExecutionInfo(name, resource, flags);
const terminalService = this.serviceContainer
.get<ITerminalServiceFactory>(ITerminalServiceFactory)
.getTerminalService(options);
const install = async (token?: CancellationToken) => {
const executionInfoArgs = await this.processInstallArgs(executionInfo.args, resource);
if (executionInfo.moduleName) {
const configService = this.serviceContainer.get<IConfigurationService>(IConfigurationService);
const settings = configService.getSettings(uri);
const interpreterService = this.serviceContainer.get<IInterpreterService>(IInterpreterService);
const interpreter = isResource(resource)
? await interpreterService.getActiveInterpreter(resource)
: resource;
const pythonPath = isResource(resource) ? settings.pythonPath : resource.path;
const args = internalPython.execModule(executionInfo.moduleName, executionInfoArgs);
if (!interpreter || interpreter.envType !== EnvironmentType.Unknown) {
await terminalService.sendCommand(pythonPath, args, token);
} else if (settings.globalModuleInstallation) {
const fs = this.serviceContainer.get<IFileSystem>(IFileSystem);
if (await fs.isDirReadonly(path.dirname(pythonPath)).catch((_err) => true)) {
this.elevatedInstall(pythonPath, args);
} else {
await terminalService.sendCommand(pythonPath, args, token);
}
} else if (name === translateProductToModule(Product.pip)) {
// Pip should always be installed into the specified environment.
await terminalService.sendCommand(pythonPath, args, token);
} else {
await terminalService.sendCommand(pythonPath, args.concat(['--user']), token);
}
} else {
await terminalService.sendCommand(executionInfo.execPath!, executionInfoArgs, token);
}
};
// Display progress indicator if we have ability to cancel this operation from calling code.
// This is required as its possible the installation can take a long time.
// (i.e. if installation takes a long time in terminal or like, a progress indicator is necessary to let user know what is being waited on).
if (cancel) {
const shell = this.serviceContainer.get<IApplicationShell>(IApplicationShell);
const options: ProgressOptions = {
location: ProgressLocation.Notification,
cancellable: true,
title: Products.installingModule().format(name),
};
await shell.withProgress(options, async (_, token: CancellationToken) =>
install(wrapCancellationTokens(token, cancel)),
);
} else {
await install(cancel);
}
}
public abstract isSupported(resource?: InterpreterUri): Promise<boolean>;
protected elevatedInstall(execPath: string, args: string[]) {
const options = {
name: 'VS Code Python',
};
const outputChannel = this.serviceContainer.get<IOutputChannel>(IOutputChannel, STANDARD_OUTPUT_CHANNEL);
const command = `"${execPath.replace(/\\/g, '/')}" ${args.join(' ')}`;
traceLog(`[Elevated] ${command}`);
const sudo = require('sudo-prompt');
sudo.exec(command, options, async (error: string, stdout: string, stderr: string) => {
if (error) {
const shell = this.serviceContainer.get<IApplicationShell>(IApplicationShell);
await shell.showErrorMessage(error);
} else {
outputChannel.show();
if (stdout) {
traceLog(stdout);
}
if (stderr) {
traceError(`Warning: ${stderr}`);
}
}
});
}
protected abstract getExecutionInfo(
moduleName: string,
resource?: InterpreterUri,
flags?: ModuleInstallFlags,
): Promise<ExecutionInfo>;
private async processInstallArgs(args: string[], resource?: InterpreterUri): Promise<string[]> {
const indexOfPylint = args.findIndex((arg) => arg.toUpperCase() === 'PYLINT');
if (indexOfPylint === -1) {
return args;
}
const interpreterService = this.serviceContainer.get<IInterpreterService>(IInterpreterService);
const interpreter = isResource(resource) ? await interpreterService.getActiveInterpreter(resource) : resource;
// If installing pylint on python 2.x, then use pylint~=1.9.0
if (interpreter && interpreter.version && interpreter.version.major === 2) {
const newArgs = [...args];
// This command could be sent to the terminal, hence '<' needs to be escaped for UNIX.
newArgs[indexOfPylint] = '"pylint<2.0.0"';
return newArgs;
}
return args;
}
}
export function translateProductToModule(product: Product): string {
switch (product) {
case Product.mypy:
return 'mypy';
case Product.pylama:
return 'pylama';
case Product.prospector:
return 'prospector';
case Product.pylint:
return 'pylint';
case Product.pytest:
return 'pytest';
case Product.autopep8:
return 'autopep8';
case Product.black:
return 'black';
case Product.pycodestyle:
return 'pycodestyle';
case Product.pydocstyle:
return 'pydocstyle';
case Product.yapf:
return 'yapf';
case Product.flake8:
return 'flake8';
case Product.unittest:
return 'unittest';
case Product.bandit:
return 'bandit';
case Product.jupyter:
return 'jupyter';
case Product.notebook:
return 'notebook';
case Product.pandas:
return 'pandas';
case Product.ipykernel:
return 'ipykernel';
case Product.nbconvert:
return 'nbconvert';
case Product.kernelspec:
return 'kernelspec';
case Product.tensorboard:
return 'tensorboard';
case Product.torchProfilerInstallName:
return 'torch-tb-profiler';
case Product.torchProfilerImportName:
return 'torch_tb_profiler';
case Product.pip:
return 'pip';
case Product.ensurepip:
return 'ensurepip';
default: {
throw new Error(`Product ${product} cannot be installed as a Python Module.`);
}
}
}