forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimpleRefactorProvider.ts
More file actions
168 lines (152 loc) · 7.98 KB
/
simpleRefactorProvider.ts
File metadata and controls
168 lines (152 loc) · 7.98 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
import * as vscode from 'vscode';
import { Commands } from '../common/constants';
import { getTextEditsFromPatch } from '../common/editor';
import { IConfigurationService, IInstaller, Product } from '../common/types';
import { StopWatch } from '../common/utils/stopWatch';
import { IServiceContainer } from '../ioc/types';
import { RefactorProxy } from '../refactor/proxy';
import { sendTelemetryWhenDone } from '../telemetry';
import { EventName } from '../telemetry/constants';
type RenameResponse = {
results: [{ diff: string }];
};
let installer: IInstaller;
export function activateSimplePythonRefactorProvider(context: vscode.ExtensionContext, outputChannel: vscode.OutputChannel, serviceContainer: IServiceContainer) {
installer = serviceContainer.get<IInstaller>(IInstaller);
let disposable = vscode.commands.registerCommand(Commands.Refactor_Extract_Variable, () => {
const stopWatch = new StopWatch();
const promise = extractVariable(context.extensionPath,
vscode.window.activeTextEditor!,
vscode.window.activeTextEditor!.selection,
// tslint:disable-next-line:no-empty
outputChannel, serviceContainer).catch(() => { });
sendTelemetryWhenDone(EventName.REFACTOR_EXTRACT_VAR, promise, stopWatch);
});
context.subscriptions.push(disposable);
disposable = vscode.commands.registerCommand(Commands.Refactor_Extract_Method, () => {
const stopWatch = new StopWatch();
const promise = extractMethod(context.extensionPath,
vscode.window.activeTextEditor!,
vscode.window.activeTextEditor!.selection,
// tslint:disable-next-line:no-empty
outputChannel, serviceContainer).catch(() => { });
sendTelemetryWhenDone(EventName.REFACTOR_EXTRACT_FUNCTION, promise, stopWatch);
});
context.subscriptions.push(disposable);
}
// Exported for unit testing
export function extractVariable(extensionDir: string, textEditor: vscode.TextEditor, range: vscode.Range,
// tslint:disable-next-line:no-any
outputChannel: vscode.OutputChannel, serviceContainer: IServiceContainer): Promise<any> {
let workspaceFolder = vscode.workspace.getWorkspaceFolder(textEditor.document.uri);
if (!workspaceFolder && Array.isArray(vscode.workspace.workspaceFolders) && vscode.workspace.workspaceFolders.length > 0) {
workspaceFolder = vscode.workspace.workspaceFolders[0];
}
const workspaceRoot = workspaceFolder ? workspaceFolder.uri.fsPath : __dirname;
const pythonSettings = serviceContainer.get<IConfigurationService>(IConfigurationService).getSettings(workspaceFolder ? workspaceFolder.uri : undefined);
return validateDocumentForRefactor(textEditor).then(() => {
const newName = `newvariable${new Date().getMilliseconds().toString()}`;
const proxy = new RefactorProxy(extensionDir, pythonSettings, workspaceRoot, serviceContainer);
const rename = proxy.extractVariable<RenameResponse>(textEditor.document, newName, textEditor.document.uri.fsPath, range, textEditor.options).then(response => {
return response.results[0].diff;
});
return extractName(textEditor, newName, rename, outputChannel);
});
}
// Exported for unit testing
export function extractMethod(extensionDir: string, textEditor: vscode.TextEditor, range: vscode.Range,
// tslint:disable-next-line:no-any
outputChannel: vscode.OutputChannel, serviceContainer: IServiceContainer): Promise<any> {
let workspaceFolder = vscode.workspace.getWorkspaceFolder(textEditor.document.uri);
if (!workspaceFolder && Array.isArray(vscode.workspace.workspaceFolders) && vscode.workspace.workspaceFolders.length > 0) {
workspaceFolder = vscode.workspace.workspaceFolders[0];
}
const workspaceRoot = workspaceFolder ? workspaceFolder.uri.fsPath : __dirname;
const pythonSettings = serviceContainer.get<IConfigurationService>(IConfigurationService).getSettings(workspaceFolder ? workspaceFolder.uri : undefined);
return validateDocumentForRefactor(textEditor).then(() => {
const newName = `newmethod${new Date().getMilliseconds().toString()}`;
const proxy = new RefactorProxy(extensionDir, pythonSettings, workspaceRoot, serviceContainer);
const rename = proxy.extractMethod<RenameResponse>(textEditor.document, newName, textEditor.document.uri.fsPath, range, textEditor.options).then(response => {
return response.results[0].diff;
});
return extractName(textEditor, newName, rename, outputChannel);
});
}
// tslint:disable-next-line:no-any
function validateDocumentForRefactor(textEditor: vscode.TextEditor): Promise<any> {
if (!textEditor.document.isDirty) {
return Promise.resolve();
}
// tslint:disable-next-line:no-any
return new Promise<any>((resolve, reject) => {
vscode.window.showInformationMessage('Please save changes before refactoring', 'Save').then(item => {
if (item === 'Save') {
textEditor.document.save().then(resolve, reject);
} else {
return reject();
}
});
});
}
function extractName(textEditor: vscode.TextEditor, newName: string,
// tslint:disable-next-line:no-any
renameResponse: Promise<string>, outputChannel: vscode.OutputChannel): Promise<any> {
let changeStartsAtLine = -1;
return renameResponse.then(diff => {
if (diff.length === 0) {
return [];
}
return getTextEditsFromPatch(textEditor.document.getText(), diff);
}).then(edits => {
return textEditor.edit(editBuilder => {
edits.forEach(edit => {
if (changeStartsAtLine === -1 || changeStartsAtLine > edit.range.start.line) {
changeStartsAtLine = edit.range.start.line;
}
editBuilder.replace(edit.range, edit.newText);
});
});
}).then(done => {
if (done && changeStartsAtLine >= 0) {
let newWordPosition: vscode.Position | undefined;
for (let lineNumber = changeStartsAtLine; lineNumber < textEditor.document.lineCount; lineNumber += 1) {
const line = textEditor.document.lineAt(lineNumber);
const indexOfWord = line.text.indexOf(newName);
if (indexOfWord >= 0) {
newWordPosition = new vscode.Position(line.range.start.line, indexOfWord);
break;
}
}
if (newWordPosition) {
textEditor.selections = [new vscode.Selection(newWordPosition, new vscode.Position(newWordPosition.line, newWordPosition.character + newName.length))];
textEditor.revealRange(new vscode.Range(textEditor.selection.start, textEditor.selection.end), vscode.TextEditorRevealType.Default);
}
return newWordPosition;
}
return null;
}).then(newWordPosition => {
if (newWordPosition) {
return textEditor.document.save().then(() => {
// Now that we have selected the new variable, lets invoke the rename command
return vscode.commands.executeCommand('editor.action.rename');
});
}
}).catch(error => {
if (error === 'Not installed') {
installer.promptToInstall(Product.rope, textEditor.document.uri)
.catch(ex => console.error('Python Extension: simpleRefactorProvider.promptToInstall', ex));
return Promise.reject('');
}
let errorMessage = `${error}`;
if (typeof error === 'string') {
errorMessage = error;
}
if (typeof error === 'object' && error.message) {
errorMessage = error.message;
}
outputChannel.appendLine(`${'#'.repeat(10)}Refactor Output${'#'.repeat(10)}`);
outputChannel.appendLine(`Error in refactoring:\n${errorMessage}`);
vscode.window.showErrorMessage(`Cannot perform refactoring using selected element(s). (${errorMessage})`);
return Promise.reject(error);
});
}