Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce per user installation of modules and elevated global install as an option #532

Merged
merged 64 commits into from
Jan 5, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
64 commits
Select commit Hold shift + click to select a range
7675901
Basic tokenizer
Dec 1, 2017
eb42669
Fixed property names
Dec 1, 2017
2756974
Tests, round I
Dec 1, 2017
c2c1ced
Tests, round II
Dec 2, 2017
a108c96
merge master
Dec 3, 2017
14864a5
tokenizer test
Dec 4, 2017
0ed51d6
Remove temorary change
Dec 4, 2017
51b544c
Fix merge issue
Dec 4, 2017
3cd11e6
Merge conflict
Dec 4, 2017
82e0ad1
Merge conflict
Dec 4, 2017
9295c1a
Completion test
Dec 4, 2017
06eb1a5
Fix last line
Dec 4, 2017
e9db8e0
Fix javascript math
Dec 4, 2017
d12ca03
Merge master
Dec 5, 2017
d8ab041
Make test await for results
Dec 5, 2017
db75cd0
Add license headers
Dec 5, 2017
9ab2c47
Rename definitions to types
Dec 5, 2017
d587485
License headers
Dec 5, 2017
1da5e0a
Merge branch 'master' of https://github.com/Microsoft/vscode-python
Dec 5, 2017
7668cee
Merge branch 'master' of https://github.com/Microsoft/vscode-python
Dec 11, 2017
1ac4932
Fix typo in completion details (typo)
Dec 11, 2017
2aa5a6c
Fix hover test
Dec 12, 2017
5db31bd
Merge branch 'master' of https://github.com/Microsoft/vscode-python
Dec 12, 2017
560d2af
Russian translations
Dec 13, 2017
c71024d
Merge branch 'master' of https://github.com/Microsoft/vscode-python
Dec 13, 2017
31aa087
Update to better translation
Dec 13, 2017
593ae05
Fix typo
Dec 13, 2017
e6d69bb
#70 How to get all parameter info when filling in a function param list
Dec 13, 2017
b5a23d3
Fix #70 How to get all parameter info when filling in a function para…
Dec 14, 2017
cd200f7
Clean up
Dec 14, 2017
7c33228
Clean imports
Dec 14, 2017
c4a6b90
CR feedback
Dec 14, 2017
f85b848
Trim whitespace for test stability
Dec 14, 2017
37c210b
More tests
Dec 15, 2017
61a5650
Better handle no-parameters documentation
Dec 15, 2017
a10305e
Better handle ellipsis and Python3
Dec 15, 2017
bfcae78
Merge branch 'master' of https://github.com/Microsoft/vscode-python
Dec 15, 2017
42a5f79
Merge branch 'master' of https://github.com/Microsoft/vscode-python
Dec 18, 2017
699c434
Basic services
Dec 20, 2017
dd9ba0a
Install check
Dec 21, 2017
443ad65
Output installer messages
Dec 21, 2017
fdde6b8
Warn default Mac OS interpreter
Dec 23, 2017
e8ea50a
Merge branch 'master' of https://github.com/Microsoft/vscode-python i…
Jan 2, 2018
8b7c920
Remove test change
Jan 2, 2018
253df9e
Add tests
Jan 2, 2018
97ed0a8
PR feedback
Jan 2, 2018
dcfc939
CR feedback
Jan 3, 2018
34790bb
Mock process instead
Jan 3, 2018
b6caacc
Fix Brew detection
Jan 3, 2018
bb648d7
Update test
Jan 3, 2018
a7bca77
Elevated module install
Jan 3, 2018
b1f7fba
Fix path check
Jan 3, 2018
d223410
Add check suppression option & suppress vor VE by default
Jan 3, 2018
6a92e60
Merge branch 'master' of https://github.com/Microsoft/vscode-python i…
Jan 3, 2018
6873309
Fix most linter tests
Jan 3, 2018
9bd8948
Merge conflict
Jan 3, 2018
11c3272
Merge branch 'master' of https://github.com/Microsoft/vscode-python i…
Jan 3, 2018
e0833f7
Merge branch 'inst1' into elev
Jan 4, 2018
29fadba
Per-user install
Jan 4, 2018
2162288
Merge master
Jan 4, 2018
542c1fc
Handle VE/Conda
Jan 4, 2018
0c87c20
Fix tests
Jan 4, 2018
b261282
Remove double service
Jan 4, 2018
57afa7f
Better mocking
Jan 5, 2018
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6,322 changes: 6,322 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -925,6 +925,12 @@
"description": "Whether to check if Python is installed.",
"scope": "resource"
},
"python.globalModuleInstallation": {
"type": "boolean",
"default": false,
"description": "Whether to install Python modules globally.",
"scope": "resource"
},
"python.linting.enabled": {
"type": "boolean",
"default": true,
Expand Down Expand Up @@ -1547,6 +1553,7 @@
"reflect-metadata": "^0.1.10",
"rxjs": "^5.5.2",
"semver": "^5.4.1",
"sudo-prompt": "^8.0.0",
"tmp": "0.0.29",
"tree-kill": "^1.1.0",
"typescript-char": "^0.0.0",
Expand Down
2 changes: 1 addition & 1 deletion pythonFiles/completion.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ def _serialize_completions(self, script, identifier=None, prefix=''):
# we pass 'text' here only for fuzzy matcher
if value:
_completion['snippet'] = '%s=${1:%s}$0' % (name, value)
_completion['text'] = '%s=%s' % (name, value)
_completion['text'] = '%s=' % (name)
else:
_completion['snippet'] = '%s=$1$0' % name
_completion['text'] = name
Expand Down
5 changes: 5 additions & 0 deletions src/client/common/configSettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export interface IPythonSettings {
envFile: string;
disablePromptForFeatures: string[];
disableInstallationChecks: boolean;
globalModuleInstallation: boolean;
}
export interface ISortImportSettings {
path: string;
Expand Down Expand Up @@ -147,6 +148,7 @@ export class PythonSettings extends EventEmitter implements IPythonSettings {
public sortImports: ISortImportSettings;
public workspaceSymbols: IWorkspaceSymbolSettings;
public disableInstallationChecks: boolean;
public globalModuleInstallation: boolean;

private workspaceRoot: vscode.Uri;
private disposables: vscode.Disposable[] = [];
Expand Down Expand Up @@ -224,7 +226,10 @@ export class PythonSettings extends EventEmitter implements IPythonSettings {
} else {
this.linting = lintingSettings;
}

this.disableInstallationChecks = pythonSettings.get<boolean>('disableInstallationCheck') === true;
this.globalModuleInstallation = pythonSettings.get<boolean>('globalModuleInstallation') === true;

// tslint:disable-next-line:no-backbone-get-set-outside-model no-non-null-assertion
const sortImportSettings = systemVariables.resolveAny(pythonSettings.get<ISortImportSettings>('sortImports'))!;
if (this.sortImports) {
Expand Down
2 changes: 1 addition & 1 deletion src/client/common/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export function isNotInstalledError(error: Error): boolean {
return true;
}

const isModuleNoInstalledError = errorObj.code === 1 && error.message.indexOf('No module named') >= 0;
const isModuleNoInstalledError = error.message.indexOf('No module named') >= 0;
return errorObj.code === 'ENOENT' || errorObj.code === 127 || isModuleNoInstalledError;
}

Expand Down
84 changes: 77 additions & 7 deletions src/client/common/installer/moduleInstaller.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,97 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

// tslint:disable-next-line:no-require-imports no-var-requires
const sudo = require('sudo-prompt');

import * as fs from 'fs';
import { injectable } from 'inversify';
import { Uri } from 'vscode';
import * as path from 'path';
import * as vscode from 'vscode';
import { IInterpreterLocatorService, INTERPRETER_LOCATOR_SERVICE, InterpreterType } from '../../interpreter/contracts';
import { IServiceContainer } from '../../ioc/types';
import { PythonSettings } from '../configSettings';
import { STANDARD_OUTPUT_CHANNEL } from '../constants';
import { IFileSystem } from '../platform/types';
import { ITerminalService } from '../terminal/types';
import { ExecutionInfo } from '../types';
import { ExecutionInfo, IOutputChannel } from '../types';

@injectable()
export abstract class ModuleInstaller {
constructor(protected serviceContainer: IServiceContainer) { }
public async installModule(name: string, resource?: Uri): Promise<void> {
public async installModule(name: string, resource?: vscode.Uri): Promise<void> {
const executionInfo = await this.getExecutionInfo(name, resource);
const terminalService = this.serviceContainer.get<ITerminalService>(ITerminalService);

if (executionInfo.moduleName) {
const pythonPath = PythonSettings.getInstance(resource).pythonPath;
await terminalService.sendCommand(pythonPath, ['-m', 'pip'].concat(executionInfo.args));
const settings = PythonSettings.getInstance(resource);
const args = ['-m', 'pip'].concat(executionInfo.args);
const pythonPath = settings.pythonPath;

const locator = this.serviceContainer.get<IInterpreterLocatorService>(IInterpreterLocatorService, INTERPRETER_LOCATOR_SERVICE);
const fileSystem = this.serviceContainer.get<IFileSystem>(IFileSystem);
const interpreters = await locator.getInterpreters(resource);

const currentInterpreter = interpreters.length > 1
? interpreters.filter(x => fileSystem.arePathsSame(x.path, pythonPath))[0]
: interpreters[0];

if (!currentInterpreter || currentInterpreter.type !== InterpreterType.Unknown) {
await terminalService.sendCommand(pythonPath, args);
} else if (settings.globalModuleInstallation) {
if (await this.isPathWritableAsync(path.dirname(pythonPath))) {
await terminalService.sendCommand(pythonPath, args);
} else {
this.elevatedInstall(pythonPath, args);
}
} else {
await terminalService.sendCommand(pythonPath, args.concat(['--user']));
}
} else {
await terminalService.sendCommand(executionInfo.execPath!, executionInfo.args);
}
}
public abstract isSupported(resource?: Uri): Promise<boolean>;
protected abstract getExecutionInfo(moduleName: string, resource?: Uri): Promise<ExecutionInfo>;
public abstract isSupported(resource?: vscode.Uri): Promise<boolean>;
protected abstract getExecutionInfo(moduleName: string, resource?: vscode.Uri): Promise<ExecutionInfo>;

private async isPathWritableAsync(directoryPath: string): Promise<boolean> {
const filePath = `${directoryPath}${path.sep}___vscpTest___`;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Something to be moved into IFileSystem interface?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am a bit concerned that if it is inside FileSystem and uses same file name for all requests (possibly concurrent), it can give false results. To be inside the FS it would need unique names per request.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or we generate a random name everytime.
But we can do that the next time this will be used elsewhere.

return new Promise<boolean>(resolve => {
fs.open(filePath, fs.constants.O_CREAT | fs.constants.O_RDWR, (error, fd) => {
if (!error) {
fs.close(fd, (e) => {
fs.unlink(filePath);
});
}
return resolve(!error);
});
});
}

private elevatedInstall(execPath: string, args: string[]) {
const options = {
name: 'VS Code Python'
};
const outputChannel = this.serviceContainer.get<vscode.OutputChannel>(IOutputChannel, STANDARD_OUTPUT_CHANNEL);
const command = `"${execPath.replace(/\\/g, '/')}" ${args.join(' ')}`;

outputChannel.appendLine('');
outputChannel.appendLine(`[Elevated] ${command}`);

sudo.exec(command, options, (error, stdout, stderr) => {
if (error) {
vscode.window.showErrorMessage(error);
} else {
outputChannel.show();
if (stdout) {
outputChannel.appendLine('');
outputChannel.append(stdout);
}
if (stderr) {
outputChannel.appendLine('');
outputChannel.append(`Warning: ${stderr}`);
}
}
});
}
}
4 changes: 4 additions & 0 deletions src/client/common/serviceRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ import { Installer } from './installer/installer';
import { Logger } from './logger';
import { PersistentStateFactory } from './persistentState';
import { IS_64_BIT, IS_WINDOWS } from './platform/constants';
import { FileSystem } from './platform/fileSystem';
import { PathUtils } from './platform/pathUtils';
import { PlatformService } from './platform/platformService';
import { IFileSystem, IPlatformService } from './platform/types';
import { CurrentProcess } from './process/currentProcess';
import { TerminalService } from './terminal/service';
import { ITerminalService } from './terminal/types';
Expand All @@ -25,4 +28,5 @@ export function registerTypes(serviceManager: IServiceManager) {
serviceManager.addSingleton<IApplicationShell>(IApplicationShell, ApplicationShell);
serviceManager.addSingleton<ICurrentProcess>(ICurrentProcess, CurrentProcess);
serviceManager.addSingleton<IInstaller>(IInstaller, Installer);
serviceManager.addSingleton<IFileSystem>(IFileSystem, FileSystem);
}
2 changes: 1 addition & 1 deletion src/client/common/terminal/types.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

export const ITerminalService = Symbol('ITerminalCommandService');
export const ITerminalService = Symbol('ITerminalService');

export interface ITerminalService {
sendCommand(command: string, args: string[]): Promise<void>;
Expand Down
2 changes: 1 addition & 1 deletion src/client/formatters/baseFormatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ export abstract class BaseFormatter {
if (isNotInstalledError(error)) {
const installer = this.serviceContainer.get<IInstaller>(IInstaller);
const isInstalled = await installer.isInstalled(this.product, resource);
if (isInstalled) {
if (!isInstalled) {
customError += `\nYou could either install the '${this.Id}' formatter, turn it off or use another formatter.`;
installer.promptToInstall(this.product, resource).catch(ex => console.error('Python Extension: promptToInstall', ex));
}
Expand Down
15 changes: 13 additions & 2 deletions src/test/common/moduleInstaller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,16 @@ import { PipInstaller } from '../../client/common/installer/pipInstaller';
import { IModuleInstaller } from '../../client/common/installer/types';
import { Logger } from '../../client/common/logger';
import { PersistentStateFactory } from '../../client/common/persistentState';
import { FileSystem } from '../../client/common/platform/fileSystem';
import { PathUtils } from '../../client/common/platform/pathUtils';
import { Architecture } from '../../client/common/platform/types';
import { PlatformService } from '../../client/common/platform/platformService';
import { Architecture, IFileSystem, IPlatformService } from '../../client/common/platform/types';
import { CurrentProcess } from '../../client/common/process/currentProcess';
import { IProcessService, IPythonExecutionFactory } from '../../client/common/process/types';
import { ITerminalService } from '../../client/common/terminal/types';
import { ICurrentProcess, IInstaller, ILogger, IPathUtils, IPersistentStateFactory, IsWindows } from '../../client/common/types';
import { ICondaLocatorService, IInterpreterLocatorService, INTERPRETER_LOCATOR_SERVICE, InterpreterType } from '../../client/interpreter/contracts';
import { PythonInterpreterLocatorService } from '../../client/interpreter/locators/index';
import { updateSetting } from '../common';
import { rootWorkspaceUri } from '../common';
import { MockProvider } from '../interpreters/mocks';
Expand Down Expand Up @@ -60,6 +63,8 @@ suite('Module Installer', () => {
ioc.serviceManager.addSingleton<ICondaLocatorService>(ICondaLocatorService, MockCondaLocator);
ioc.serviceManager.addSingleton<IPathUtils>(IPathUtils, PathUtils);
ioc.serviceManager.addSingleton<ICurrentProcess>(ICurrentProcess, CurrentProcess);
ioc.serviceManager.addSingleton<IFileSystem>(IFileSystem, FileSystem);
ioc.serviceManager.addSingleton<IPlatformService>(IPlatformService, PlatformService);

ioc.registerMockProcessTypes();
ioc.serviceManager.addSingleton<ITerminalService>(ITerminalService, MockTerminalService);
Expand Down Expand Up @@ -136,6 +141,9 @@ suite('Module Installer', () => {
});

test('Validate pip install arguments', async () => {
const mockInterpreterLocator = new MockProvider([{ path: await getCurrentPythonPath(), type: InterpreterType.Unknown }]);
ioc.serviceManager.addSingletonInstance<IInterpreterLocatorService>(IInterpreterLocatorService, mockInterpreterLocator, INTERPRETER_LOCATOR_SERVICE);

const moduleName = 'xyz';
const terminalService = ioc.serviceContainer.get<MockTerminalService>(ITerminalService);

Expand All @@ -148,10 +156,13 @@ suite('Module Installer', () => {
const commandSent = await terminalService.commandSent;
const commandParts = commandSent.split(' ');
commandParts.shift();
expect(commandParts.join(' ')).equal(`-m pip install -U ${moduleName}`, 'Invalid command sent to terminal for installation.');
expect(commandParts.join(' ')).equal(`-m pip install -U ${moduleName} --user`, 'Invalid command sent to terminal for installation.');
});

test('Validate Conda install arguments', async () => {
const mockInterpreterLocator = new MockProvider([{ path: await getCurrentPythonPath(), type: InterpreterType.Conda }]);
ioc.serviceManager.addSingletonInstance<IInterpreterLocatorService>(IInterpreterLocatorService, mockInterpreterLocator, INTERPRETER_LOCATOR_SERVICE);

const moduleName = 'xyz';
const terminalService = ioc.serviceContainer.get<MockTerminalService>(ITerminalService);

Expand Down