forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimportSortProvider.ts
More file actions
184 lines (165 loc) · 7.94 KB
/
importSortProvider.ts
File metadata and controls
184 lines (165 loc) · 7.94 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
import { inject, injectable } from 'inversify';
import { EOL } from 'os';
import * as path from 'path';
import { CancellationToken, TextDocument, Uri, WorkspaceEdit } from 'vscode';
import { IApplicationShell, ICommandManager, IDocumentManager } from '../common/application/types';
import { Commands, PYTHON_LANGUAGE, STANDARD_OUTPUT_CHANNEL } from '../common/constants';
import { traceError } from '../common/logger';
import * as internalScripts from '../common/process/internal/scripts';
import { IProcessServiceFactory, IPythonExecutionFactory, ObservableExecutionResult } from '../common/process/types';
import { IConfigurationService, IDisposableRegistry, IEditorUtils, IOutputChannel } from '../common/types';
import { createDeferred } from '../common/utils/async';
import { noop } from '../common/utils/misc';
import { IServiceContainer } from '../ioc/types';
import { captureTelemetry } from '../telemetry';
import { EventName } from '../telemetry/constants';
import { ISortImportsEditingProvider } from './types';
@injectable()
export class SortImportsEditingProvider implements ISortImportsEditingProvider {
private readonly processServiceFactory: IProcessServiceFactory;
private readonly pythonExecutionFactory: IPythonExecutionFactory;
private readonly shell: IApplicationShell;
private readonly documentManager: IDocumentManager;
private readonly configurationService: IConfigurationService;
private readonly editorUtils: IEditorUtils;
public constructor(@inject(IServiceContainer) private serviceContainer: IServiceContainer) {
this.shell = serviceContainer.get<IApplicationShell>(IApplicationShell);
this.documentManager = serviceContainer.get<IDocumentManager>(IDocumentManager);
this.configurationService = serviceContainer.get<IConfigurationService>(IConfigurationService);
this.pythonExecutionFactory = serviceContainer.get<IPythonExecutionFactory>(IPythonExecutionFactory);
this.processServiceFactory = serviceContainer.get<IProcessServiceFactory>(IProcessServiceFactory);
this.editorUtils = serviceContainer.get<IEditorUtils>(IEditorUtils);
}
@captureTelemetry(EventName.FORMAT_SORT_IMPORTS)
public async provideDocumentSortImportsEdits(
uri: Uri,
token?: CancellationToken
): Promise<WorkspaceEdit | undefined> {
const document = await this.documentManager.openTextDocument(uri);
if (!document) {
return;
}
if (document.lineCount <= 1) {
return;
}
const execIsort = await this.getExecIsort(document, uri, token);
if (token && token.isCancellationRequested) {
return;
}
const diffPatch = await execIsort(document.getText());
return diffPatch
? this.editorUtils.getWorkspaceEditsFromPatch(document.getText(), diffPatch, document.uri)
: undefined;
}
public registerCommands() {
const cmdManager = this.serviceContainer.get<ICommandManager>(ICommandManager);
const disposable = cmdManager.registerCommand(Commands.Sort_Imports, this.sortImports, this);
this.serviceContainer.get<IDisposableRegistry>(IDisposableRegistry).push(disposable);
}
public async sortImports(uri?: Uri): Promise<void> {
if (!uri) {
const activeEditor = this.documentManager.activeTextEditor;
if (!activeEditor || activeEditor.document.languageId !== PYTHON_LANGUAGE) {
this.shell.showErrorMessage('Please open a Python file to sort the imports.').then(noop, noop);
return;
}
uri = activeEditor.document.uri;
}
const document = await this.documentManager.openTextDocument(uri);
if (document.lineCount <= 1) {
return;
}
// 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 = document.lineAt(document.lineCount - 1);
if (lastLine.text.trim().length > 0) {
const edit = new WorkspaceEdit();
edit.insert(uri, lastLine.range.end, EOL);
await this.documentManager.applyEdit(edit);
}
try {
const changes = await this.provideDocumentSortImportsEdits(uri);
if (!changes || changes.entries().length === 0) {
return;
}
await this.documentManager.applyEdit(changes);
} catch (error) {
const message = typeof error === 'string' ? error : error.message ? error.message : error;
const outputChannel = this.serviceContainer.get<IOutputChannel>(IOutputChannel, STANDARD_OUTPUT_CHANNEL);
outputChannel.appendLine(error);
traceError(`Failed to format imports for '${uri.fsPath}'.`, error);
this.shell.showErrorMessage(message).then(noop, noop);
}
}
private async getExecIsort(
document: TextDocument,
uri: Uri,
token?: CancellationToken
): Promise<(documentText: string) => Promise<string>> {
const settings = this.configurationService.getSettings(uri);
const _isort = settings.sortImports.path;
const isort = typeof _isort === 'string' && _isort.length > 0 ? _isort : undefined;
const isortArgs = settings.sortImports.args;
// We pass the content of the file to be sorted via stdin. This avoids
// saving the file (as well as a potential temporary file), but does
// mean that we need another way to tell `isort` where to look for
// configuration. We do that by setting the working directory to the
// directory which contains the file.
const filename = '-';
const spawnOptions = {
token,
throwOnStdErr: true,
cwd: path.dirname(uri.fsPath)
};
if (isort) {
const procService = await this.processServiceFactory.create(document.uri);
// Use isort directly instead of the internal script.
return async (documentText: string) => {
const args = getIsortArgs(filename, isortArgs);
const result = procService.execObservable(isort, args, spawnOptions);
return this.communicateWithIsortProcess(result, documentText);
};
} else {
const procService = await this.pythonExecutionFactory.create({ resource: document.uri });
return async (documentText: string) => {
const [args, parse] = internalScripts.sortImports(filename, isortArgs);
const result = procService.execObservable(args, spawnOptions);
return parse(await this.communicateWithIsortProcess(result, documentText));
};
}
}
private async communicateWithIsortProcess(
observableResult: ObservableExecutionResult<string>,
inputText: string
): Promise<string> {
// Configure our listening to the output from isort ...
let outputBuffer = '';
const isortOutput = createDeferred<string>();
observableResult.out.subscribe({
next: (output) => {
if (output.source === 'stdout') {
outputBuffer += output.out;
}
},
complete: () => {
isortOutput.resolve(outputBuffer);
}
});
// ... then send isort the document content ...
observableResult.proc?.stdin.write(inputText);
observableResult.proc?.stdin.end();
// .. and finally wait for isort to do its thing
await isortOutput.promise;
return outputBuffer;
}
}
function getIsortArgs(filename: string, extraArgs?: string[]): string[] {
// We could just adapt internalScripts.sortImports(). However,
// the following is simpler and the alternative doesn't offer
// any signficant benefit.
const args = [filename, '--diff'];
if (extraArgs) {
args.push(...extraArgs);
}
return args;
}