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
49 lines (44 loc) · 2.02 KB
/
sortImports.ts
File metadata and controls
49 lines (44 loc) · 2.02 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
'use strict';
import * as vscode from 'vscode';
import * as sortProvider from './providers/importSortProvider';
import * as os from 'os';
export function activate(context: vscode.ExtensionContext, outChannel: vscode.OutputChannel) {
let rootDir = context.asAbsolutePath('.');
let disposable = vscode.commands.registerCommand('python.sortImports', () => {
let 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) {
emptyLineAdded = new Promise<any>((resolve, reject) => {
activeEditor.edit(builder => {
builder.insert(lastLine.range.end, os.EOL);
}).then(resolve, reject);
});
}
return emptyLineAdded.then(() => {
return new sortProvider.PythonImportSortProvider().sortImports(rootDir, activeEditor.document);
}).then(changes => {
if (changes.length === 0) {
return;
}
return activeEditor.edit(builder => {
changes.forEach(change => builder.replace(change.range, change.newText));
});
}).catch(error => {
let message = typeof error === 'string' ? error : (error.message ? error.message : error);
outChannel.appendLine(error);
outChannel.show();
vscode.window.showErrorMessage(message);
});
});
context.subscriptions.push(disposable);
}