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

Prototype TS/JS Refactoring Provider #27166

Merged
merged 4 commits into from
Jun 16, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
128 changes: 128 additions & 0 deletions extensions/typescript/src/features/refactorProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

'use strict';

import { CodeActionProvider, TextDocument, Range, CancellationToken, CodeActionContext, Command, commands, workspace, WorkspaceEdit, window, QuickPickItem } from 'vscode';

import * as Proto from '../protocol';
import { ITypescriptServiceClient } from '../typescriptService';


export default class TypeScriptRefactorProvider implements CodeActionProvider {
private doRefactorCommandId: string;
private selectRefactorCommandId: string;

constructor(
private readonly client: ITypescriptServiceClient,
mode: string
) {
this.doRefactorCommandId = `_typescript.applyRefactoring.${mode}`;
this.selectRefactorCommandId = `_typescript.selectRefactoring.${mode}`;

commands.registerCommand(this.doRefactorCommandId, this.doRefactoring, this);
commands.registerCommand(this.selectRefactorCommandId, this.selectRefactoring, this);

}

public async provideCodeActions(
document: TextDocument,
range: Range,
_context: CodeActionContext,
token: CancellationToken
): Promise<Command[]> {
if (!this.client.apiVersion.has240Features()) {
return [];
}

const file = this.client.normalizePath(document.uri);
if (!file) {
return [];
}

const args: Proto.GetApplicableRefactorsRequestArgs = {
file: file,
startLine: range.start.line + 1,
startOffset: range.start.character + 1,
endLine: range.end.line + 1,
endOffset: range.end.character + 1
};

try {
const response = await this.client.execute('getApplicableRefactors', args, token);
if (!response || !response.body) {
return [];
}

const actions: Command[] = [];
for (const info of response.body) {
if (info.inlineable === false) {
actions.push({
title: info.description,
command: this.selectRefactorCommandId,
arguments: [file, info, range]
});
} else {
for (const action of info.actions) {
actions.push({
title: action.description,
command: this.doRefactorCommandId,
arguments: [file, info.name, action.name, range]
});
}
}
}
return actions;
} catch (err) {
return [];
}
}

private toWorkspaceEdit(edits: Proto.FileCodeEdits[]): WorkspaceEdit {
const workspaceEdit = new WorkspaceEdit();
for (const edit of edits) {
for (const textChange of edit.textChanges) {
workspaceEdit.replace(this.client.asUrl(edit.fileName),
new Range(
textChange.start.line - 1, textChange.start.offset - 1,
textChange.end.line - 1, textChange.end.offset - 1),
textChange.newText);
}
}
return workspaceEdit;
}

private async selectRefactoring(file: string, info: Proto.ApplicableRefactorInfo, range: Range): Promise<boolean> {
return window.showQuickPick(info.actions.map((action): QuickPickItem => ({
label: action.name,
description: action.description
}))).then(selected => {
if (!selected) {
return false;
}
return this.doRefactoring(file, info.name, selected.label, range);
});
}

private async doRefactoring(file: string, refactor: string, action: string, range: Range): Promise<boolean> {
const args: Proto.GetEditsForRefactorRequestArgs = {
file,
refactor,
action,
startLine: range.start.line + 1,
startOffset: range.start.character + 1,
endLine: range.end.line + 1,
endOffset: range.end.character + 1
};

const response = await this.client.execute('getEditsForRefactor', args);
if (!response || !response.body || !response.body.edits.length) {
return false;
}

const edit = this.toWorkspaceEdit(response.body.edits);
return workspace.applyEdit(edit);
}
}
5 changes: 3 additions & 2 deletions extensions/typescript/src/typescriptMain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ import BufferSyncSupport from './features/bufferSyncSupport';
import CompletionItemProvider from './features/completionItemProvider';
import WorkspaceSymbolProvider from './features/workspaceSymbolProvider';
import CodeActionProvider from './features/codeActionProvider';
import RefactorProvider from './features/refactorProvider';
import ReferenceCodeLensProvider from './features/referencesCodeLensProvider';
import { JsDocCompletionProvider, TryCompleteJsDocCommand } from './features/jsDocCompletionProvider';
import { DirectiveCommentCompletionProvider } from './features/directiveCommentCompletionProvider';
import TypeScriptTaskProviderManager from './features/taskProvider';

import ImplementationCodeLensProvider from './features/implementationsCodeLensProvider';

import * as ProjectStatus from './utils/projectStatus';
Expand Down Expand Up @@ -167,6 +167,7 @@ export function activate(context: ExtensionContext): void {
const validateSetting = 'validate.enable';

class LanguageProvider {

private syntaxDiagnostics: ObjectMap<Diagnostic[]>;
private readonly currentDiagnostics: DiagnosticCollection;
private readonly bufferSyncSupport: BufferSyncSupport;
Expand Down Expand Up @@ -263,7 +264,7 @@ class LanguageProvider {
this.disposables.push(languages.registerRenameProvider(selector, new RenameProvider(client)));

this.disposables.push(languages.registerCodeActionsProvider(selector, new CodeActionProvider(client, this.description.id)));

this.disposables.push(languages.registerCodeActionsProvider(selector, new RefactorProvider(client, this.description.id)));
this.registerVersionDependentProviders();

this.description.modeIds.forEach(modeId => {
Expand Down
5 changes: 5 additions & 0 deletions extensions/typescript/src/typescriptService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ export class API {
public has234Features(): boolean {
return semver.gte(this._version, '2.3.4');
}
public has240Features(): boolean {
return semver.gte(this._version, '2.4.0');
}
}

export interface ITypescriptServiceClient {
Expand Down Expand Up @@ -115,6 +118,8 @@ export interface ITypescriptServiceClient {
execute(command: 'getCodeFixes', args: Proto.CodeFixRequestArgs, token?: CancellationToken): Promise<Proto.GetCodeFixesResponse>;
execute(command: 'getSupportedCodeFixes', args: null, token?: CancellationToken): Promise<Proto.GetSupportedCodeFixesResponse>;
execute(command: 'docCommentTemplate', args: Proto.FileLocationRequestArgs, token?: CancellationToken): Promise<Proto.DocCommandTemplateResponse>;
execute(command: 'getApplicableRefactors', args: Proto.GetApplicableRefactorsRequestArgs, token?: CancellationToken): Promise<Proto.GetApplicableRefactorsResponse>;
execute(command: 'getEditsForRefactor', args: Proto.GetEditsForRefactorRequestArgs, token?: CancellationToken): Promise<Proto.GetEditsForRefactorResponse>;
// execute(command: 'compileOnSaveAffectedFileList', args: Proto.CompileOnSaveEmitFileRequestArgs, token?: CancellationToken): Promise<Proto.CompileOnSaveAffectedFileListResponse>;
// execute(command: 'compileOnSaveEmitFile', args: Proto.CompileOnSaveEmitFileRequestArgs, token?: CancellationToken): Promise<any>;
execute(command: string, args: any, expectedResult: boolean | CancellationToken, token?: CancellationToken): Promise<any>;
Expand Down