forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsortImports.ts
More file actions
50 lines (46 loc) · 2.5 KB
/
sortImports.ts
File metadata and controls
50 lines (46 loc) · 2.5 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
import * as os from 'os';
import * as vscode from 'vscode';
import { IProcessService, IPythonExecutionFactory } from './common/process/types';
import { IServiceContainer } from './ioc/types';
import * as sortProvider from './providers/importSortProvider';
export function activate(context: vscode.ExtensionContext, outChannel: vscode.OutputChannel, serviceContainer: IServiceContainer) {
const rootDir = context.asAbsolutePath('.');
const disposable = vscode.commands.registerCommand('python.sortImports', () => {
const activeEditor = vscode.window.activeTextEditor;
if (!activeEditor || activeEditor.document.languageId !== 'python') {
vscode.window.showErrorMessage('Please open a Python source file to sort the imports.');
return Promise.resolve();
}
if (activeEditor.document.lineCount <= 1) {
return Promise.resolve();
}
// Hack, if the document doesn't contain an empty line at the end, then add it
// Else the library strips off the last line
const lastLine = activeEditor.document.lineAt(activeEditor.document.lineCount - 1);
let emptyLineAdded = Promise.resolve(true);
if (lastLine.text.trim().length > 0) {
// tslint:disable-next-line:no-any
emptyLineAdded = new Promise<any>((resolve, reject) => {
activeEditor.edit(builder => {
builder.insert(lastLine.range.end, os.EOL);
}).then(resolve, reject);
});
}
return emptyLineAdded.then(() => {
const processService = serviceContainer.get<IProcessService>(IProcessService);
const pythonExecutionFactory = serviceContainer.get<IPythonExecutionFactory>(IPythonExecutionFactory);
return new sortProvider.PythonImportSortProvider(pythonExecutionFactory, processService).sortImports(rootDir, activeEditor.document);
}).then(changes => {
if (!changes || changes!.length === 0) {
return;
}
return new Promise((resolve, reject) => activeEditor.edit(builder => changes.forEach(change => builder.replace(change.range, change.newText))).then(resolve, reject));
}).catch(error => {
const message = typeof error === 'string' ? error : (error.message ? error.message : error);
outChannel.appendLine(error);
outChannel.show();
vscode.window.showErrorMessage(message);
});
});
context.subscriptions.push(disposable);
}