From 9ae6d43f642a8c491841b1f2978274cf31113c62 Mon Sep 17 00:00:00 2001 From: Aswin M Prabhu Date: Wed, 21 Nov 2018 20:27:40 +0530 Subject: [PATCH 01/13] Add godoctor extract function command and code action --- src/goDoctor.ts | 73 +++++++++++++++++++++++++++++++++++++++++++++++ src/goMain.ts | 9 ++++++ src/goRefactor.ts | 27 ++++++++++++++++++ 3 files changed, 109 insertions(+) create mode 100644 src/goDoctor.ts create mode 100644 src/goRefactor.ts diff --git a/src/goDoctor.ts b/src/goDoctor.ts new file mode 100644 index 000000000..b18264a78 --- /dev/null +++ b/src/goDoctor.ts @@ -0,0 +1,73 @@ +/*--------------------------------------------------------- + * 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 vscode = require('vscode'); +import cp = require('child_process'); +import { getBinPath, getToolsEnvVars } from './util'; +import { promptForMissingTool } from './goInstallTools'; +import { dirname } from 'path'; +import { resolve } from 'dns'; + +/** + * Extracts function out of current selection and replaces the current selection with a call to the extracted function. + */ +export function extractFunction() { + let activeEditor = vscode.window.activeTextEditor; + if (!activeEditor) { + vscode.window.showInformationMessage('No editor is active.'); + return; + } + if (activeEditor.selections.length !== 1) { + vscode.window.showInformationMessage('You need to have a single selection for extracting method'); + return; + } + let showInputBoxPromise = vscode.window.showInputBox({ placeHolder: 'Plese enter a name for the extracted function.' }); + showInputBoxPromise.then((functionName: string) => { + runGoDoctorExtract(functionName, activeEditor.selection, activeEditor).then(errorMessage => { + if (errorMessage) { + vscode.window.showErrorMessage(errorMessage); + } + }); + }); +} +/** +* @param functionName name for the extracted method +* @param selection the editor selection from which method is to be extracted +* @param activeEditor the editor that will be used to apply the changes from godoctor +* @returns errorMessage in case the method fails, null otherwise +*/ +export function runGoDoctorExtract(functionName: string, selection: vscode.Selection, activeEditor: vscode.TextEditor): Thenable { + let godoctor = getBinPath('godoctor'); + + return new Promise((resolve, reject) => { + if (typeof functionName === 'undefined') { + return resolve('Function Name is undefined'); + } + let args = [ + '-w', + '-pos', + `${selection.start.line + 1},${selection.start.character + 1}:${selection.end.line + 1},${selection.end.character + 1}`, + '-file', + activeEditor.document.fileName, + 'extract', + functionName, + ]; + let p = cp.execFile(godoctor, args, { env: getToolsEnvVars(), cwd: dirname(activeEditor.document.fileName) }, (err, stdout, stderr) => { + if (err && (err).code === 'ENOENT') { + promptForMissingTool('godoctor'); + return resolve('Could not find godoctor'); + } + if (err) { + return resolve(`Could not extract function : \n\n${stderr}`); + } + }); + if (p.pid) { + p.stdin.end(); + } + + }); +} \ No newline at end of file diff --git a/src/goMain.ts b/src/goMain.ts index 31229fd3e..345622dc3 100644 --- a/src/goMain.ts +++ b/src/goMain.ts @@ -44,6 +44,7 @@ import { runFillStruct } from './goFillStruct'; import { parseLiveFile } from './goLiveErrors'; import { GoReferencesCodeLensProvider } from './goReferencesCodelens'; import { implCursor } from './goImpl'; +import { extractFunction } from './goDoctor'; import { browsePackages } from './goBrowsePackage'; import { goGetPackage } from './goGetPackage'; import { GoDebugConfigurationProvider } from './goDebugConfiguration'; @@ -53,8 +54,12 @@ import { vetCode } from './goVet'; import { buildCode } from './goBuild'; import { installCurrentPackage } from './goInstall'; import { setGlobalState } from './stateUtils'; +<<<<<<< HEAD import { ProvideTypeDefinitionSignature } from 'vscode-languageclient/lib/typeDefinition'; import { ProvideImplementationSignature } from 'vscode-languageclient/lib/implementation'; +======= +import { GoRefactorProvider } from './goRefactor'; +>>>>>>> Add godoctor extract function command and code action export let buildDiagnosticCollection: vscode.DiagnosticCollection; export let lintDiagnosticCollection: vscode.DiagnosticCollection; @@ -271,6 +276,7 @@ export function activate(ctx: vscode.ExtensionContext): void { ctx.subscriptions.push(vscode.languages.registerCodeActionsProvider(GO_MODE, new GoCodeActionProvider())); + ctx.subscriptions.push(vscode.languages.registerCodeActionsProvider(GO_MODE, new GoRefactorProvider())); ctx.subscriptions.push(vscode.languages.registerCodeLensProvider(GO_MODE, testCodeLensProvider)); ctx.subscriptions.push(vscode.languages.registerCodeLensProvider(GO_MODE, referencesCodeLensProvider)); ctx.subscriptions.push(vscode.debug.registerDebugConfigurationProvider('go', new GoDebugConfigurationProvider())); @@ -324,6 +330,9 @@ export function activate(ctx: vscode.ExtensionContext): void { ctx.subscriptions.push(vscode.commands.registerCommand('go.impl.cursor', () => { implCursor(); })); + ctx.subscriptions.push(vscode.commands.registerCommand('go.godoctor.extract', () => { + extractFunction(); + })); ctx.subscriptions.push(vscode.commands.registerCommand('go.test.cursor', (args) => { const goConfig = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null); diff --git a/src/goRefactor.ts b/src/goRefactor.ts new file mode 100644 index 000000000..f2724b8c7 --- /dev/null +++ b/src/goRefactor.ts @@ -0,0 +1,27 @@ +/*--------------------------------------------------------- + * 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 vscode = require('vscode'); + +export class GoRefactorProvider implements vscode.CodeActionProvider { + public provideCodeActions(document: vscode.TextDocument, range: vscode.Range, context: vscode.CodeActionContext, token: vscode.CancellationToken): vscode.ProviderResult { + const extractFunction = new vscode.CodeAction( + 'Extract Function', + vscode.CodeActionKind.RefactorExtract + ); + extractFunction.command = { + title: 'Extract Function', + command: 'go.godoctor.extract', + arguments: [ + document, + range, + ], + }; + + return [extractFunction]; + } +} \ No newline at end of file From e47ade2ce06233a252c8ee0ab3beacd0b3448de6 Mon Sep 17 00:00:00 2001 From: Aswin M Prabhu Date: Wed, 21 Nov 2018 20:47:20 +0530 Subject: [PATCH 02/13] Add extract to var command and code action --- src/goDoctor.ts | 151 ++++++++++++++++++++++++++++++++-------------- src/goMain.ts | 5 +- src/goRefactor.ts | 18 +++--- 3 files changed, 122 insertions(+), 52 deletions(-) diff --git a/src/goDoctor.ts b/src/goDoctor.ts index b18264a78..2d017272d 100644 --- a/src/goDoctor.ts +++ b/src/goDoctor.ts @@ -16,24 +16,49 @@ import { resolve } from 'dns'; * Extracts function out of current selection and replaces the current selection with a call to the extracted function. */ export function extractFunction() { - let activeEditor = vscode.window.activeTextEditor; - if (!activeEditor) { - vscode.window.showInformationMessage('No editor is active.'); - return; - } - if (activeEditor.selections.length !== 1) { - vscode.window.showInformationMessage('You need to have a single selection for extracting method'); - return; - } - let showInputBoxPromise = vscode.window.showInputBox({ placeHolder: 'Plese enter a name for the extracted function.' }); - showInputBoxPromise.then((functionName: string) => { - runGoDoctorExtract(functionName, activeEditor.selection, activeEditor).then(errorMessage => { - if (errorMessage) { - vscode.window.showErrorMessage(errorMessage); - } - }); - }); + let activeEditor = vscode.window.activeTextEditor; + if (!activeEditor) { + vscode.window.showInformationMessage('No editor is active.'); + return; + } + if (activeEditor.selections.length !== 1) { + vscode.window.showInformationMessage('You need to have a single selection for extracting method'); + return; + } + let showInputBoxPromise = vscode.window.showInputBox({ placeHolder: 'Plese enter a name for the extracted function.' }); + showInputBoxPromise.then((functionName: string) => { + runGoDoctorExtract(functionName, activeEditor.selection, activeEditor).then(errorMessage => { + if (errorMessage) { + vscode.window.showErrorMessage(errorMessage); + } + }); + }); } + +/** + * Extracts expression out of current selection into a var in the local scope and + * replaces the current selection with the new var. + */ +export function extractVariable() { + let activeEditor = vscode.window.activeTextEditor; + if (!activeEditor) { + vscode.window.showInformationMessage('No editor is active.'); + return; + } + if (activeEditor.selections.length !== 1) { + vscode.window.showInformationMessage('You need to have a single selection for extracting method'); + return; + } + let showInputBoxPromise = vscode.window.showInputBox({ placeHolder: 'Plese enter a name for the extracted variable.' }); + showInputBoxPromise.then((varName: string) => { + runGoDoctorVar(varName, activeEditor.selection, activeEditor).then(errorMessage => { + if (errorMessage) { + vscode.window.showErrorMessage(errorMessage); + } + }); + }); +} + /** * @param functionName name for the extracted method * @param selection the editor selection from which method is to be extracted @@ -41,33 +66,71 @@ export function extractFunction() { * @returns errorMessage in case the method fails, null otherwise */ export function runGoDoctorExtract(functionName: string, selection: vscode.Selection, activeEditor: vscode.TextEditor): Thenable { - let godoctor = getBinPath('godoctor'); + let godoctor = getBinPath('godoctor'); + + return new Promise((resolve, reject) => { + if (typeof functionName === 'undefined') { + return resolve('Function Name is undefined'); + } + let args = [ + '-w', + '-pos', + `${selection.start.line + 1},${selection.start.character + 1}:${selection.end.line + 1},${selection.end.character + 1}`, + '-file', + activeEditor.document.fileName, + 'extract', + functionName, + ]; + let p = cp.execFile(godoctor, args, { env: getToolsEnvVars(), cwd: dirname(activeEditor.document.fileName) }, (err, stdout, stderr) => { + if (err && (err).code === 'ENOENT') { + promptForMissingTool('godoctor'); + return resolve('Could not find godoctor'); + } + if (err) { + return resolve(`Could not extract function : \n\n${stderr}`); + } + }); + if (p.pid) { + p.stdin.end(); + } + + }); +} + +/** +* @param varName name for the extracted method +* @param selection the editor selection from which method is to be extracted +* @param activeEditor the editor that will be used to apply the changes from godoctor +* @returns errorMessage in case the method fails, null otherwise +*/ +export function runGoDoctorVar(varName: string, selection: vscode.Selection, activeEditor: vscode.TextEditor): Thenable { + let godoctor = getBinPath('godoctor'); - return new Promise((resolve, reject) => { - if (typeof functionName === 'undefined') { - return resolve('Function Name is undefined'); - } - let args = [ - '-w', - '-pos', - `${selection.start.line + 1},${selection.start.character + 1}:${selection.end.line + 1},${selection.end.character + 1}`, - '-file', - activeEditor.document.fileName, - 'extract', - functionName, - ]; - let p = cp.execFile(godoctor, args, { env: getToolsEnvVars(), cwd: dirname(activeEditor.document.fileName) }, (err, stdout, stderr) => { - if (err && (err).code === 'ENOENT') { - promptForMissingTool('godoctor'); - return resolve('Could not find godoctor'); - } - if (err) { - return resolve(`Could not extract function : \n\n${stderr}`); - } - }); - if (p.pid) { - p.stdin.end(); - } + return new Promise((resolve, reject) => { + if (typeof varName === 'undefined') { + return resolve('Function Name is undefined'); + } + let args = [ + '-w', + '-pos', + `${selection.start.line + 1},${selection.start.character + 1}:${selection.end.line + 1},${selection.end.character + 1}`, + '-file', + activeEditor.document.fileName, + 'var', + varName, + ]; + let p = cp.execFile(godoctor, args, { env: getToolsEnvVars(), cwd: dirname(activeEditor.document.fileName) }, (err, stdout, stderr) => { + if (err && (err).code === 'ENOENT') { + promptForMissingTool('godoctor'); + return resolve('Could not find godoctor'); + } + if (err) { + return resolve(`Could not extract variable : \n\n${stderr}`); + } + }); + if (p.pid) { + p.stdin.end(); + } - }); + }); } \ No newline at end of file diff --git a/src/goMain.ts b/src/goMain.ts index 345622dc3..57b67935d 100644 --- a/src/goMain.ts +++ b/src/goMain.ts @@ -44,7 +44,7 @@ import { runFillStruct } from './goFillStruct'; import { parseLiveFile } from './goLiveErrors'; import { GoReferencesCodeLensProvider } from './goReferencesCodelens'; import { implCursor } from './goImpl'; -import { extractFunction } from './goDoctor'; +import { extractFunction, extractVariable } from './goDoctor'; import { browsePackages } from './goBrowsePackage'; import { goGetPackage } from './goGetPackage'; import { GoDebugConfigurationProvider } from './goDebugConfiguration'; @@ -333,6 +333,9 @@ export function activate(ctx: vscode.ExtensionContext): void { ctx.subscriptions.push(vscode.commands.registerCommand('go.godoctor.extract', () => { extractFunction(); })); + ctx.subscriptions.push(vscode.commands.registerCommand('go.godoctor.var', () => { + extractVariable(); + })); ctx.subscriptions.push(vscode.commands.registerCommand('go.test.cursor', (args) => { const goConfig = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null); diff --git a/src/goRefactor.ts b/src/goRefactor.ts index f2724b8c7..92a1b5ebf 100644 --- a/src/goRefactor.ts +++ b/src/goRefactor.ts @@ -10,18 +10,22 @@ import vscode = require('vscode'); export class GoRefactorProvider implements vscode.CodeActionProvider { public provideCodeActions(document: vscode.TextDocument, range: vscode.Range, context: vscode.CodeActionContext, token: vscode.CancellationToken): vscode.ProviderResult { const extractFunction = new vscode.CodeAction( - 'Extract Function', + 'Extract to function in package scope', + vscode.CodeActionKind.RefactorExtract + ); + const extractVar = new vscode.CodeAction( + 'Extract to variable in local scope', vscode.CodeActionKind.RefactorExtract ); extractFunction.command = { - title: 'Extract Function', + title: '', command: 'go.godoctor.extract', - arguments: [ - document, - range, - ], + }; + extractVar.command = { + title: 'Extract to variable in local scope', + command: 'go.godoctor.var', }; - return [extractFunction]; + return [extractFunction, extractVar]; } } \ No newline at end of file From 70b2cd47ab1aea6c36ce65c994facfc1d58ac845 Mon Sep 17 00:00:00 2001 From: Aswin M Prabhu Date: Wed, 21 Nov 2018 20:53:16 +0530 Subject: [PATCH 03/13] Add godoctor to tools to install --- src/goInstallTools.ts | 4 +++- src/goRefactor.ts | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/goInstallTools.ts b/src/goInstallTools.ts index 2806db8b4..acde7ddd5 100644 --- a/src/goInstallTools.ts +++ b/src/goInstallTools.ts @@ -41,6 +41,7 @@ const _allTools: { [key: string]: string } = { 'go-langserver': 'github.com/sourcegraph/go-langserver', 'dlv': 'github.com/go-delve/delve/cmd/dlv', 'fillstruct': 'github.com/davidrjenni/reftools/cmd/fillstruct', + 'godoctor': 'github.com/godoctor/godoctor', }; function getToolImportPath(tool: string, goVersion: SemVersion) { @@ -183,7 +184,8 @@ export function installAllTools(updateExistingToolsOnly: boolean = false) { 'staticcheck': '\t(Linter)', 'go-langserver': '(Language Server)', 'dlv': '\t\t\t(Debugging)', - 'fillstruct': '\t\t(Fill structs with defaults)' + 'fillstruct': '\t\t(Fill structs with defaults)', + 'godoctor': '\t\t(Extract to functions and variables)' }; getGoVersion().then((goVersion) => { diff --git a/src/goRefactor.ts b/src/goRefactor.ts index 92a1b5ebf..6a300a333 100644 --- a/src/goRefactor.ts +++ b/src/goRefactor.ts @@ -18,7 +18,7 @@ export class GoRefactorProvider implements vscode.CodeActionProvider { vscode.CodeActionKind.RefactorExtract ); extractFunction.command = { - title: '', + title: 'Extract to function in package scope', command: 'go.godoctor.extract', }; extractVar.command = { From bd25252214fcd10db1af3495cf9af28a0944e978 Mon Sep 17 00:00:00 2001 From: Aswin M Prabhu Date: Wed, 21 Nov 2018 20:54:35 +0530 Subject: [PATCH 04/13] Change refactor error message --- src/goDoctor.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/goDoctor.ts b/src/goDoctor.ts index 2d017272d..6e7752f8c 100644 --- a/src/goDoctor.ts +++ b/src/goDoctor.ts @@ -46,7 +46,7 @@ export function extractVariable() { return; } if (activeEditor.selections.length !== 1) { - vscode.window.showInformationMessage('You need to have a single selection for extracting method'); + vscode.window.showInformationMessage('You need to have a single selection for extracting variable'); return; } let showInputBoxPromise = vscode.window.showInputBox({ placeHolder: 'Plese enter a name for the extracted variable.' }); From 72d5422cfa6591c9e0086e63520fa569b721245c Mon Sep 17 00:00:00 2001 From: Aswin M Prabhu Date: Thu, 22 Nov 2018 23:11:32 +0530 Subject: [PATCH 05/13] Fix tslint errors --- src/goDoctor.ts | 176 ++++++++++++++++++++++++------------------------ 1 file changed, 88 insertions(+), 88 deletions(-) diff --git a/src/goDoctor.ts b/src/goDoctor.ts index 6e7752f8c..149f91e23 100644 --- a/src/goDoctor.ts +++ b/src/goDoctor.ts @@ -16,23 +16,23 @@ import { resolve } from 'dns'; * Extracts function out of current selection and replaces the current selection with a call to the extracted function. */ export function extractFunction() { - let activeEditor = vscode.window.activeTextEditor; - if (!activeEditor) { - vscode.window.showInformationMessage('No editor is active.'); - return; - } - if (activeEditor.selections.length !== 1) { - vscode.window.showInformationMessage('You need to have a single selection for extracting method'); - return; - } - let showInputBoxPromise = vscode.window.showInputBox({ placeHolder: 'Plese enter a name for the extracted function.' }); - showInputBoxPromise.then((functionName: string) => { - runGoDoctorExtract(functionName, activeEditor.selection, activeEditor).then(errorMessage => { - if (errorMessage) { - vscode.window.showErrorMessage(errorMessage); - } - }); - }); + let activeEditor = vscode.window.activeTextEditor; + if (!activeEditor) { + vscode.window.showInformationMessage('No editor is active.'); + return; + } + if (activeEditor.selections.length !== 1) { + vscode.window.showInformationMessage('You need to have a single selection for extracting method'); + return; + } + let showInputBoxPromise = vscode.window.showInputBox({ placeHolder: 'Plese enter a name for the extracted function.' }); + showInputBoxPromise.then((functionName: string) => { + runGoDoctorExtract(functionName, activeEditor.selection, activeEditor).then(errorMessage => { + if (errorMessage) { + vscode.window.showErrorMessage(errorMessage); + } + }); + }); } /** @@ -40,23 +40,23 @@ export function extractFunction() { * replaces the current selection with the new var. */ export function extractVariable() { - let activeEditor = vscode.window.activeTextEditor; - if (!activeEditor) { - vscode.window.showInformationMessage('No editor is active.'); - return; - } - if (activeEditor.selections.length !== 1) { - vscode.window.showInformationMessage('You need to have a single selection for extracting variable'); - return; - } - let showInputBoxPromise = vscode.window.showInputBox({ placeHolder: 'Plese enter a name for the extracted variable.' }); - showInputBoxPromise.then((varName: string) => { - runGoDoctorVar(varName, activeEditor.selection, activeEditor).then(errorMessage => { - if (errorMessage) { - vscode.window.showErrorMessage(errorMessage); - } - }); - }); + let activeEditor = vscode.window.activeTextEditor; + if (!activeEditor) { + vscode.window.showInformationMessage('No editor is active.'); + return; + } + if (activeEditor.selections.length !== 1) { + vscode.window.showInformationMessage('You need to have a single selection for extracting variable'); + return; + } + let showInputBoxPromise = vscode.window.showInputBox({ placeHolder: 'Plese enter a name for the extracted variable.' }); + showInputBoxPromise.then((varName: string) => { + runGoDoctorVar(varName, activeEditor.selection, activeEditor).then(errorMessage => { + if (errorMessage) { + vscode.window.showErrorMessage(errorMessage); + } + }); + }); } /** @@ -66,35 +66,35 @@ export function extractVariable() { * @returns errorMessage in case the method fails, null otherwise */ export function runGoDoctorExtract(functionName: string, selection: vscode.Selection, activeEditor: vscode.TextEditor): Thenable { - let godoctor = getBinPath('godoctor'); + let godoctor = getBinPath('godoctor'); - return new Promise((resolve, reject) => { - if (typeof functionName === 'undefined') { - return resolve('Function Name is undefined'); - } - let args = [ - '-w', - '-pos', - `${selection.start.line + 1},${selection.start.character + 1}:${selection.end.line + 1},${selection.end.character + 1}`, - '-file', - activeEditor.document.fileName, - 'extract', - functionName, - ]; - let p = cp.execFile(godoctor, args, { env: getToolsEnvVars(), cwd: dirname(activeEditor.document.fileName) }, (err, stdout, stderr) => { - if (err && (err).code === 'ENOENT') { - promptForMissingTool('godoctor'); - return resolve('Could not find godoctor'); - } - if (err) { - return resolve(`Could not extract function : \n\n${stderr}`); - } - }); - if (p.pid) { - p.stdin.end(); - } + return new Promise((resolve, reject) => { + if (typeof functionName === 'undefined') { + return resolve('Function Name is undefined'); + } + let args = [ + '-w', + '-pos', + `${selection.start.line + 1},${selection.start.character + 1}:${selection.end.line + 1},${selection.end.character + 1}`, + '-file', + activeEditor.document.fileName, + 'extract', + functionName, + ]; + let p = cp.execFile(godoctor, args, { env: getToolsEnvVars(), cwd: dirname(activeEditor.document.fileName) }, (err, stdout, stderr) => { + if (err && (err).code === 'ENOENT') { + promptForMissingTool('godoctor'); + return resolve('Could not find godoctor'); + } + if (err) { + return resolve(`Could not extract function : \n\n${stderr}`); + } + }); + if (p.pid) { + p.stdin.end(); + } - }); + }); } /** @@ -104,33 +104,33 @@ export function runGoDoctorExtract(functionName: string, selection: vscode.Selec * @returns errorMessage in case the method fails, null otherwise */ export function runGoDoctorVar(varName: string, selection: vscode.Selection, activeEditor: vscode.TextEditor): Thenable { - let godoctor = getBinPath('godoctor'); + let godoctor = getBinPath('godoctor'); - return new Promise((resolve, reject) => { - if (typeof varName === 'undefined') { - return resolve('Function Name is undefined'); - } - let args = [ - '-w', - '-pos', - `${selection.start.line + 1},${selection.start.character + 1}:${selection.end.line + 1},${selection.end.character + 1}`, - '-file', - activeEditor.document.fileName, - 'var', - varName, - ]; - let p = cp.execFile(godoctor, args, { env: getToolsEnvVars(), cwd: dirname(activeEditor.document.fileName) }, (err, stdout, stderr) => { - if (err && (err).code === 'ENOENT') { - promptForMissingTool('godoctor'); - return resolve('Could not find godoctor'); - } - if (err) { - return resolve(`Could not extract variable : \n\n${stderr}`); - } - }); - if (p.pid) { - p.stdin.end(); - } + return new Promise((resolve, reject) => { + if (typeof varName === 'undefined') { + return resolve('Function Name is undefined'); + } + let args = [ + '-w', + '-pos', + `${selection.start.line + 1},${selection.start.character + 1}:${selection.end.line + 1},${selection.end.character + 1}`, + '-file', + activeEditor.document.fileName, + 'var', + varName, + ]; + let p = cp.execFile(godoctor, args, { env: getToolsEnvVars(), cwd: dirname(activeEditor.document.fileName) }, (err, stdout, stderr) => { + if (err && (err).code === 'ENOENT') { + promptForMissingTool('godoctor'); + return resolve('Could not find godoctor'); + } + if (err) { + return resolve(`Could not extract variable : \n\n${stderr}`); + } + }); + if (p.pid) { + p.stdin.end(); + } - }); + }); } \ No newline at end of file From 373c22845e42e1088b20312a275c967d65f42e39 Mon Sep 17 00:00:00 2001 From: Aswin M Prabhu Date: Sat, 16 Feb 2019 22:46:28 +0530 Subject: [PATCH 06/13] Make requested changes --- src/goDoctor.ts | 146 +++++++++++++++++++++++----------------------- src/goRefactor.ts | 13 +++-- 2 files changed, 81 insertions(+), 78 deletions(-) diff --git a/src/goDoctor.ts b/src/goDoctor.ts index 149f91e23..64bcf962c 100644 --- a/src/goDoctor.ts +++ b/src/goDoctor.ts @@ -22,16 +22,27 @@ export function extractFunction() { return; } if (activeEditor.selections.length !== 1) { - vscode.window.showInformationMessage('You need to have a single selection for extracting method'); + vscode.window.showInformationMessage( + 'You need to have a single selection for extracting method' + ); return; } - let showInputBoxPromise = vscode.window.showInputBox({ placeHolder: 'Plese enter a name for the extracted function.' }); + let showInputBoxPromise = vscode.window.showInputBox({ + placeHolder: 'Please enter a name for the extracted function.' + }); showInputBoxPromise.then((functionName: string) => { - runGoDoctorExtract(functionName, activeEditor.selection, activeEditor).then(errorMessage => { - if (errorMessage) { - vscode.window.showErrorMessage(errorMessage); - } - }); + if (typeof functionName === 'string') { + runGoDoctor( + functionName, + activeEditor.selection, + activeEditor.document.fileName, + 'extract' + ).then(errorMessage => { + if (errorMessage) { + vscode.window.showErrorMessage(errorMessage); + } + }); + } }); } @@ -46,91 +57,78 @@ export function extractVariable() { return; } if (activeEditor.selections.length !== 1) { - vscode.window.showInformationMessage('You need to have a single selection for extracting variable'); + vscode.window.showInformationMessage( + 'You need to have a single selection for extracting variable' + ); return; } - let showInputBoxPromise = vscode.window.showInputBox({ placeHolder: 'Plese enter a name for the extracted variable.' }); - showInputBoxPromise.then((varName: string) => { - runGoDoctorVar(varName, activeEditor.selection, activeEditor).then(errorMessage => { - if (errorMessage) { - vscode.window.showErrorMessage(errorMessage); - } - }); + let showInputBoxPromise = vscode.window.showInputBox({ + placeHolder: 'Plese enter a name for the extracted variable.' }); -} - -/** -* @param functionName name for the extracted method -* @param selection the editor selection from which method is to be extracted -* @param activeEditor the editor that will be used to apply the changes from godoctor -* @returns errorMessage in case the method fails, null otherwise -*/ -export function runGoDoctorExtract(functionName: string, selection: vscode.Selection, activeEditor: vscode.TextEditor): Thenable { - let godoctor = getBinPath('godoctor'); - - return new Promise((resolve, reject) => { - if (typeof functionName === 'undefined') { - return resolve('Function Name is undefined'); - } - let args = [ - '-w', - '-pos', - `${selection.start.line + 1},${selection.start.character + 1}:${selection.end.line + 1},${selection.end.character + 1}`, - '-file', - activeEditor.document.fileName, - 'extract', - functionName, - ]; - let p = cp.execFile(godoctor, args, { env: getToolsEnvVars(), cwd: dirname(activeEditor.document.fileName) }, (err, stdout, stderr) => { - if (err && (err).code === 'ENOENT') { - promptForMissingTool('godoctor'); - return resolve('Could not find godoctor'); - } - if (err) { - return resolve(`Could not extract function : \n\n${stderr}`); - } - }); - if (p.pid) { - p.stdin.end(); + showInputBoxPromise.then((varName: string) => { + if (typeof varName === 'string') { + runGoDoctor( + varName, + activeEditor.selection, + activeEditor.document.fileName, + 'var' + ).then(errorMessage => { + if (errorMessage) { + vscode.window.showErrorMessage(errorMessage); + } + }); } - }); } +type typeOfExtraction = 'var' | 'extract'; + /** -* @param varName name for the extracted method -* @param selection the editor selection from which method is to be extracted -* @param activeEditor the editor that will be used to apply the changes from godoctor -* @returns errorMessage in case the method fails, null otherwise -*/ -export function runGoDoctorVar(varName: string, selection: vscode.Selection, activeEditor: vscode.TextEditor): Thenable { + * @param newName name for the extracted method + * @param selection the editor selection from which method is to be extracted + * @param activeEditor the editor that will be used to apply the changes from godoctor + * @returns errorMessage in case the method fails, null otherwise + */ +function runGoDoctor( + newName: string, + selection: vscode.Selection, + fileName: string, + type: typeOfExtraction +): Thenable { let godoctor = getBinPath('godoctor'); return new Promise((resolve, reject) => { - if (typeof varName === 'undefined') { - return resolve('Function Name is undefined'); - } + console.log(selection); let args = [ '-w', '-pos', - `${selection.start.line + 1},${selection.start.character + 1}:${selection.end.line + 1},${selection.end.character + 1}`, + `${selection.start.line + 1},${selection.start.character + + 1}:${selection.end.line + 1},${selection.end.character}`, '-file', - activeEditor.document.fileName, - 'var', - varName, + fileName, + type, + newName ]; - let p = cp.execFile(godoctor, args, { env: getToolsEnvVars(), cwd: dirname(activeEditor.document.fileName) }, (err, stdout, stderr) => { - if (err && (err).code === 'ENOENT') { - promptForMissingTool('godoctor'); - return resolve('Could not find godoctor'); + console.log(args); + let p = cp.execFile( + godoctor, + args, + { + env: getToolsEnvVars(), + cwd: dirname(fileName) + }, + (err, stdout, stderr) => { + if (err && (err).code === 'ENOENT') { + promptForMissingTool('godoctor'); + return resolve('Could not find godoctor'); + } + if (err) { + return resolve(stderr); + } } - if (err) { - return resolve(`Could not extract variable : \n\n${stderr}`); - } - }); + ); if (p.pid) { p.stdin.end(); } - }); -} \ No newline at end of file +} diff --git a/src/goRefactor.ts b/src/goRefactor.ts index 6a300a333..1745b4260 100644 --- a/src/goRefactor.ts +++ b/src/goRefactor.ts @@ -8,7 +8,12 @@ import vscode = require('vscode'); export class GoRefactorProvider implements vscode.CodeActionProvider { - public provideCodeActions(document: vscode.TextDocument, range: vscode.Range, context: vscode.CodeActionContext, token: vscode.CancellationToken): vscode.ProviderResult { + public provideCodeActions( + document: vscode.TextDocument, + range: vscode.Range, + context: vscode.CodeActionContext, + token: vscode.CancellationToken + ): vscode.ProviderResult { const extractFunction = new vscode.CodeAction( 'Extract to function in package scope', vscode.CodeActionKind.RefactorExtract @@ -19,13 +24,13 @@ export class GoRefactorProvider implements vscode.CodeActionProvider { ); extractFunction.command = { title: 'Extract to function in package scope', - command: 'go.godoctor.extract', + command: 'go.godoctor.extract' }; extractVar.command = { title: 'Extract to variable in local scope', - command: 'go.godoctor.var', + command: 'go.godoctor.var' }; return [extractFunction, extractVar]; } -} \ No newline at end of file +} From 17488d2415363442a5f01abbbd4b603a536f73e6 Mon Sep 17 00:00:00 2001 From: Aswin M Prabhu Date: Sat, 16 Feb 2019 22:52:13 +0530 Subject: [PATCH 07/13] Fix conflicts --- src/goMain.ts | 1263 ++++++++++++++++++++++++++++++++++++------------- 1 file changed, 923 insertions(+), 340 deletions(-) diff --git a/src/goMain.ts b/src/goMain.ts index 57b67935d..91791cefa 100644 --- a/src/goMain.ts +++ b/src/goMain.ts @@ -20,23 +20,58 @@ import { GoSignatureHelpProvider } from './goSignature'; import { GoWorkspaceSymbolProvider } from './goSymbol'; import { GoCodeActionProvider } from './goCodeAction'; import { check, removeTestStatus, notifyIfGeneratedFile } from './goCheck'; -import { updateGoPathGoRootFromConfig, offerToInstallTools, promptForMissingTool, installTools } from './goInstallTools'; +import { + updateGoPathGoRootFromConfig, + offerToInstallTools, + promptForMissingTool, + installTools +} from './goInstallTools'; import { GO_MODE } from './goMode'; import { showHideStatus } from './goStatus'; -import { initCoverageDecorators, toggleCoverageCurrentPackage, applyCodeCoverage, removeCodeCoverageOnFileChange, updateCodeCoverageDecorators } from './goCover'; -import { testAtCursor, testCurrentPackage, testCurrentFile, testPrevious, testWorkspace } from './goTest'; +import { + initCoverageDecorators, + toggleCoverageCurrentPackage, + applyCodeCoverage, + removeCodeCoverageOnFileChange, + updateCodeCoverageDecorators +} from './goCover'; +import { + testAtCursor, + testCurrentPackage, + testCurrentFile, + testPrevious, + testWorkspace +} from './goTest'; import { showTestOutput, cancelRunningTests } from './testUtils'; import * as goGenerateTests from './goGenerateTests'; import { addImport, addImportToWorkspace } from './goImport'; import { installAllTools, checkLanguageServer } from './goInstallTools'; import { - isGoPathSet, getBinPath, sendTelemetryEvent, getExtensionCommands, getGoVersion, getCurrentGoPath, - getToolsGopath, handleDiagnosticErrors, disposeTelemetryReporter, getToolsEnvVars, cleanupTempDir + isGoPathSet, + getBinPath, + sendTelemetryEvent, + getExtensionCommands, + getGoVersion, + getCurrentGoPath, + getToolsGopath, + handleDiagnosticErrors, + disposeTelemetryReporter, + getToolsEnvVars, + cleanupTempDir } from './util'; import { - LanguageClient, RevealOutputChannelOn, FormattingOptions, ProvideDocumentFormattingEditsSignature, - ProvideCompletionItemsSignature, ProvideRenameEditsSignature, ProvideDefinitionSignature, ProvideHoverSignature, - ProvideReferencesSignature, ProvideSignatureHelpSignature, ProvideDocumentSymbolsSignature, ProvideWorkspaceSymbolsSignature + LanguageClient, + RevealOutputChannelOn, + FormattingOptions, + ProvideDocumentFormattingEditsSignature, + ProvideCompletionItemsSignature, + ProvideRenameEditsSignature, + ProvideDefinitionSignature, + ProvideHoverSignature, + ProvideReferencesSignature, + ProvideSignatureHelpSignature, + ProvideDocumentSymbolsSignature, + ProvideWorkspaceSymbolsSignature } from 'vscode-languageclient'; import { clearCacheForTools, fixDriveCasingInWindows } from './goPath'; import { addTags, removeTags } from './goModifytags'; @@ -54,19 +89,18 @@ import { vetCode } from './goVet'; import { buildCode } from './goBuild'; import { installCurrentPackage } from './goInstall'; import { setGlobalState } from './stateUtils'; -<<<<<<< HEAD import { ProvideTypeDefinitionSignature } from 'vscode-languageclient/lib/typeDefinition'; import { ProvideImplementationSignature } from 'vscode-languageclient/lib/implementation'; -======= import { GoRefactorProvider } from './goRefactor'; ->>>>>>> Add godoctor extract function command and code action export let buildDiagnosticCollection: vscode.DiagnosticCollection; export let lintDiagnosticCollection: vscode.DiagnosticCollection; export let vetDiagnosticCollection: vscode.DiagnosticCollection; export function activate(ctx: vscode.ExtensionContext): void { - let useLangServer = vscode.workspace.getConfiguration('go')['useLanguageServer']; + let useLangServer = vscode.workspace.getConfiguration('go')[ + 'useLanguageServer' + ]; setGlobalState(ctx.globalState); updateGoPathGoRootFromConfig().then(() => { @@ -74,24 +108,36 @@ export function activate(ctx: vscode.ExtensionContext): void { const prevGoroot = ctx.globalState.get('goroot'); const currentGoroot = process.env['GOROOT']; if (prevGoroot !== currentGoroot && prevGoroot) { - vscode.window.showInformationMessage('Your goroot is different than before, a few Go tools may need recompiling', updateToolsCmdText).then(selected => { - if (selected === updateToolsCmdText) { - installAllTools(true); - } - }); + vscode.window + .showInformationMessage( + 'Your goroot is different than before, a few Go tools may need recompiling', + updateToolsCmdText + ) + .then(selected => { + if (selected === updateToolsCmdText) { + installAllTools(true); + } + }); } else { getGoVersion().then(currentVersion => { if (currentVersion) { const prevVersion = ctx.globalState.get('goVersion'); - const currVersionString = `${currentVersion.major}.${currentVersion.minor}`; + const currVersionString = `${currentVersion.major}.${ + currentVersion.minor + }`; if (prevVersion !== currVersionString) { if (prevVersion) { - vscode.window.showInformationMessage('Your Go version is different than before, few Go tools may need re-compiling', updateToolsCmdText).then(selected => { - if (selected === updateToolsCmdText) { - installAllTools(true); - } - }); + vscode.window + .showInformationMessage( + 'Your Go version is different than before, few Go tools may need re-compiling', + updateToolsCmdText + ) + .then(selected => { + if (selected === updateToolsCmdText) { + installAllTools(true); + } + }); } ctx.globalState.update('goVersion', currVersionString); } @@ -102,8 +148,14 @@ export function activate(ctx: vscode.ExtensionContext): void { offerToInstallTools(); if (checkLanguageServer()) { - const languageServerExperimentalFeatures: any = vscode.workspace.getConfiguration('go').get('languageServerExperimentalFeatures') || {}; - let langServerFlags: string[] = vscode.workspace.getConfiguration('go')['languageServerFlags'] || []; + const languageServerExperimentalFeatures: any = + vscode.workspace + .getConfiguration('go') + .get('languageServerExperimentalFeatures') || {}; + let langServerFlags: string[] = + vscode.workspace.getConfiguration('go')[ + 'languageServerFlags' + ] || []; const c = new LanguageClient( 'go-langserver', @@ -116,156 +168,415 @@ export function activate(ctx: vscode.ExtensionContext): void { }, { initializationOptions: { - funcSnippetEnabled: vscode.workspace.getConfiguration('go')['useCodeSnippetsOnFunctionSuggest'], - gocodeCompletionEnabled: languageServerExperimentalFeatures['autoComplete'] + funcSnippetEnabled: vscode.workspace.getConfiguration( + 'go' + )['useCodeSnippetsOnFunctionSuggest'], + gocodeCompletionEnabled: + languageServerExperimentalFeatures['autoComplete'] }, documentSelector: ['go'], uriConverters: { // Apply file:/// scheme to all file paths. - code2Protocol: (uri: vscode.Uri): string => (uri.scheme ? uri : uri.with({ scheme: 'file' })).toString(), - protocol2Code: (uri: string) => vscode.Uri.parse(uri), + code2Protocol: (uri: vscode.Uri): string => + (uri.scheme + ? uri + : uri.with({ scheme: 'file' }) + ).toString(), + protocol2Code: (uri: string) => vscode.Uri.parse(uri) }, revealOutputChannelOn: RevealOutputChannelOn.Never, middleware: { - provideDocumentFormattingEdits: (document: vscode.TextDocument, options: FormattingOptions, token: vscode.CancellationToken, next: ProvideDocumentFormattingEditsSignature) => { - if (languageServerExperimentalFeatures['format'] === true) { + provideDocumentFormattingEdits: ( + document: vscode.TextDocument, + options: FormattingOptions, + token: vscode.CancellationToken, + next: ProvideDocumentFormattingEditsSignature + ) => { + if ( + languageServerExperimentalFeatures['format'] === + true + ) { return next(document, options, token); } return []; }, - provideCompletionItem: (document: vscode.TextDocument, position: vscode.Position, context: vscode.CompletionContext, token: vscode.CancellationToken, next: ProvideCompletionItemsSignature) => { - if (languageServerExperimentalFeatures['autoComplete'] === true) { + provideCompletionItem: ( + document: vscode.TextDocument, + position: vscode.Position, + context: vscode.CompletionContext, + token: vscode.CancellationToken, + next: ProvideCompletionItemsSignature + ) => { + if ( + languageServerExperimentalFeatures[ + 'autoComplete' + ] === true + ) { return next(document, position, context, token); } return []; }, - provideRenameEdits: (document: vscode.TextDocument, position: vscode.Position, newName: string, token: vscode.CancellationToken, next: ProvideRenameEditsSignature) => { - if (languageServerExperimentalFeatures['rename'] === true) { + provideRenameEdits: ( + document: vscode.TextDocument, + position: vscode.Position, + newName: string, + token: vscode.CancellationToken, + next: ProvideRenameEditsSignature + ) => { + if ( + languageServerExperimentalFeatures['rename'] === + true + ) { return next(document, position, newName, token); } return null; }, - provideDefinition: (document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, next: ProvideDefinitionSignature) => { - if (languageServerExperimentalFeatures['goToDefinition'] === true) { + provideDefinition: ( + document: vscode.TextDocument, + position: vscode.Position, + token: vscode.CancellationToken, + next: ProvideDefinitionSignature + ) => { + if ( + languageServerExperimentalFeatures[ + 'goToDefinition' + ] === true + ) { return next(document, position, token); } return null; }, - provideTypeDefinition: (document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, next: ProvideTypeDefinitionSignature) => { - if (languageServerExperimentalFeatures['goToTypeDefinition'] === true) { + provideTypeDefinition: ( + document: vscode.TextDocument, + position: vscode.Position, + token: vscode.CancellationToken, + next: ProvideTypeDefinitionSignature + ) => { + if ( + languageServerExperimentalFeatures[ + 'goToTypeDefinition' + ] === true + ) { return next(document, position, token); } return null; }, - provideHover: (document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, next: ProvideHoverSignature) => { - if (languageServerExperimentalFeatures['hover'] === true) { + provideHover: ( + document: vscode.TextDocument, + position: vscode.Position, + token: vscode.CancellationToken, + next: ProvideHoverSignature + ) => { + if ( + languageServerExperimentalFeatures['hover'] === + true + ) { return next(document, position, token); } return null; }, - provideReferences: (document: vscode.TextDocument, position: vscode.Position, options: { includeDeclaration: boolean }, token: vscode.CancellationToken, next: ProvideReferencesSignature) => { - if (languageServerExperimentalFeatures['findReferences'] === true) { + provideReferences: ( + document: vscode.TextDocument, + position: vscode.Position, + options: { includeDeclaration: boolean }, + token: vscode.CancellationToken, + next: ProvideReferencesSignature + ) => { + if ( + languageServerExperimentalFeatures[ + 'findReferences' + ] === true + ) { return next(document, position, options, token); } return []; }, - provideSignatureHelp: (document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, next: ProvideSignatureHelpSignature) => { - if (languageServerExperimentalFeatures['signatureHelp'] === true) { + provideSignatureHelp: ( + document: vscode.TextDocument, + position: vscode.Position, + token: vscode.CancellationToken, + next: ProvideSignatureHelpSignature + ) => { + if ( + languageServerExperimentalFeatures[ + 'signatureHelp' + ] === true + ) { return next(document, position, token); } return null; }, - provideDocumentSymbols: (document: vscode.TextDocument, token: vscode.CancellationToken, next: ProvideDocumentSymbolsSignature) => { - if (languageServerExperimentalFeatures['documentSymbols'] === true) { + provideDocumentSymbols: ( + document: vscode.TextDocument, + token: vscode.CancellationToken, + next: ProvideDocumentSymbolsSignature + ) => { + if ( + languageServerExperimentalFeatures[ + 'documentSymbols' + ] === true + ) { return next(document, token); } return []; }, - provideWorkspaceSymbols: (query: string, token: vscode.CancellationToken, next: ProvideWorkspaceSymbolsSignature) => { - if (languageServerExperimentalFeatures['workspaceSymbols'] === true) { + provideWorkspaceSymbols: ( + query: string, + token: vscode.CancellationToken, + next: ProvideWorkspaceSymbolsSignature + ) => { + if ( + languageServerExperimentalFeatures[ + 'workspaceSymbols' + ] === true + ) { return next(query, token); } return []; }, - provideImplementation: (document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, next: ProvideImplementationSignature) => { - if (languageServerExperimentalFeatures['goToImplementation'] === true) { + provideImplementation: ( + document: vscode.TextDocument, + position: vscode.Position, + token: vscode.CancellationToken, + next: ProvideImplementationSignature + ) => { + if ( + languageServerExperimentalFeatures[ + 'goToImplementation' + ] === true + ) { return next(document, position, token); } return null; - }, + } } } ); c.onReady().then(() => { - const capabilities = c.initializeResult && c.initializeResult.capabilities; + const capabilities = + c.initializeResult && c.initializeResult.capabilities; if (!capabilities) { - return vscode.window.showErrorMessage('The language server is not able to serve any features at the moment.'); + return vscode.window.showErrorMessage( + 'The language server is not able to serve any features at the moment.' + ); } - if (languageServerExperimentalFeatures['autoComplete'] !== true || !capabilities.completionProvider) { + if ( + languageServerExperimentalFeatures['autoComplete'] !== + true || + !capabilities.completionProvider + ) { registerCompletionProvider(ctx); } - if (languageServerExperimentalFeatures['format'] !== true || !capabilities.documentFormattingProvider) { - ctx.subscriptions.push(vscode.languages.registerDocumentFormattingEditProvider(GO_MODE, new GoDocumentFormattingEditProvider())); + if ( + languageServerExperimentalFeatures['format'] !== true || + !capabilities.documentFormattingProvider + ) { + ctx.subscriptions.push( + vscode.languages.registerDocumentFormattingEditProvider( + GO_MODE, + new GoDocumentFormattingEditProvider() + ) + ); } - if (languageServerExperimentalFeatures['rename'] !== true || !capabilities.renameProvider) { - ctx.subscriptions.push(vscode.languages.registerRenameProvider(GO_MODE, new GoRenameProvider())); + if ( + languageServerExperimentalFeatures['rename'] !== true || + !capabilities.renameProvider + ) { + ctx.subscriptions.push( + vscode.languages.registerRenameProvider( + GO_MODE, + new GoRenameProvider() + ) + ); } - if (languageServerExperimentalFeatures['goToTypeDefinition'] !== true || !capabilities.typeDefinitionProvider) { - ctx.subscriptions.push(vscode.languages.registerTypeDefinitionProvider(GO_MODE, new GoTypeDefinitionProvider())); + if ( + languageServerExperimentalFeatures['goToTypeDefinition'] !== + true || + !capabilities.typeDefinitionProvider + ) { + ctx.subscriptions.push( + vscode.languages.registerTypeDefinitionProvider( + GO_MODE, + new GoTypeDefinitionProvider() + ) + ); } - if (languageServerExperimentalFeatures['hover'] !== true || !capabilities.hoverProvider) { - ctx.subscriptions.push(vscode.languages.registerHoverProvider(GO_MODE, new GoHoverProvider())); + if ( + languageServerExperimentalFeatures['hover'] !== true || + !capabilities.hoverProvider + ) { + ctx.subscriptions.push( + vscode.languages.registerHoverProvider( + GO_MODE, + new GoHoverProvider() + ) + ); } - if (languageServerExperimentalFeatures['goToDefinition'] !== true || !capabilities.definitionProvider) { - ctx.subscriptions.push(vscode.languages.registerDefinitionProvider(GO_MODE, new GoDefinitionProvider())); + if ( + languageServerExperimentalFeatures['goToDefinition'] !== + true || + !capabilities.definitionProvider + ) { + ctx.subscriptions.push( + vscode.languages.registerDefinitionProvider( + GO_MODE, + new GoDefinitionProvider() + ) + ); } - if (languageServerExperimentalFeatures['findReferences'] !== true || !capabilities.referencesProvider) { - ctx.subscriptions.push(vscode.languages.registerReferenceProvider(GO_MODE, new GoReferenceProvider())); + if ( + languageServerExperimentalFeatures['findReferences'] !== + true || + !capabilities.referencesProvider + ) { + ctx.subscriptions.push( + vscode.languages.registerReferenceProvider( + GO_MODE, + new GoReferenceProvider() + ) + ); } - if (languageServerExperimentalFeatures['documentSymbols'] !== true || !capabilities.documentSymbolProvider) { - ctx.subscriptions.push(vscode.languages.registerDocumentSymbolProvider(GO_MODE, new GoDocumentSymbolProvider())); + if ( + languageServerExperimentalFeatures['documentSymbols'] !== + true || + !capabilities.documentSymbolProvider + ) { + ctx.subscriptions.push( + vscode.languages.registerDocumentSymbolProvider( + GO_MODE, + new GoDocumentSymbolProvider() + ) + ); } - if (languageServerExperimentalFeatures['signatureHelp'] !== true || !capabilities.signatureHelpProvider) { - ctx.subscriptions.push(vscode.languages.registerSignatureHelpProvider(GO_MODE, new GoSignatureHelpProvider(), '(', ',')); + if ( + languageServerExperimentalFeatures['signatureHelp'] !== + true || + !capabilities.signatureHelpProvider + ) { + ctx.subscriptions.push( + vscode.languages.registerSignatureHelpProvider( + GO_MODE, + new GoSignatureHelpProvider(), + '(', + ',' + ) + ); } - if (languageServerExperimentalFeatures['workspaceSymbols'] !== true || !capabilities.workspaceSymbolProvider) { - ctx.subscriptions.push(vscode.languages.registerWorkspaceSymbolProvider(new GoWorkspaceSymbolProvider())); + if ( + languageServerExperimentalFeatures['workspaceSymbols'] !== + true || + !capabilities.workspaceSymbolProvider + ) { + ctx.subscriptions.push( + vscode.languages.registerWorkspaceSymbolProvider( + new GoWorkspaceSymbolProvider() + ) + ); } - if (languageServerExperimentalFeatures['goToImplementation'] !== true || !capabilities.implementationProvider) { - ctx.subscriptions.push(vscode.languages.registerImplementationProvider(GO_MODE, new GoImplementationProvider())); + if ( + languageServerExperimentalFeatures['goToImplementation'] !== + true || + !capabilities.implementationProvider + ) { + ctx.subscriptions.push( + vscode.languages.registerImplementationProvider( + GO_MODE, + new GoImplementationProvider() + ) + ); } - }); ctx.subscriptions.push(c.start()); } else { registerCompletionProvider(ctx); - ctx.subscriptions.push(vscode.languages.registerHoverProvider(GO_MODE, new GoHoverProvider())); - ctx.subscriptions.push(vscode.languages.registerDefinitionProvider(GO_MODE, new GoDefinitionProvider())); - ctx.subscriptions.push(vscode.languages.registerReferenceProvider(GO_MODE, new GoReferenceProvider())); - ctx.subscriptions.push(vscode.languages.registerDocumentSymbolProvider(GO_MODE, new GoDocumentSymbolProvider())); - ctx.subscriptions.push(vscode.languages.registerWorkspaceSymbolProvider(new GoWorkspaceSymbolProvider())); - ctx.subscriptions.push(vscode.languages.registerSignatureHelpProvider(GO_MODE, new GoSignatureHelpProvider(), '(', ',')); - ctx.subscriptions.push(vscode.languages.registerImplementationProvider(GO_MODE, new GoImplementationProvider())); - ctx.subscriptions.push(vscode.languages.registerDocumentFormattingEditProvider(GO_MODE, new GoDocumentFormattingEditProvider())); - ctx.subscriptions.push(vscode.languages.registerTypeDefinitionProvider(GO_MODE, new GoTypeDefinitionProvider())); - ctx.subscriptions.push(vscode.languages.registerRenameProvider(GO_MODE, new GoRenameProvider())); + ctx.subscriptions.push( + vscode.languages.registerHoverProvider( + GO_MODE, + new GoHoverProvider() + ) + ); + ctx.subscriptions.push( + vscode.languages.registerDefinitionProvider( + GO_MODE, + new GoDefinitionProvider() + ) + ); + ctx.subscriptions.push( + vscode.languages.registerReferenceProvider( + GO_MODE, + new GoReferenceProvider() + ) + ); + ctx.subscriptions.push( + vscode.languages.registerDocumentSymbolProvider( + GO_MODE, + new GoDocumentSymbolProvider() + ) + ); + ctx.subscriptions.push( + vscode.languages.registerWorkspaceSymbolProvider( + new GoWorkspaceSymbolProvider() + ) + ); + ctx.subscriptions.push( + vscode.languages.registerSignatureHelpProvider( + GO_MODE, + new GoSignatureHelpProvider(), + '(', + ',' + ) + ); + ctx.subscriptions.push( + vscode.languages.registerImplementationProvider( + GO_MODE, + new GoImplementationProvider() + ) + ); + ctx.subscriptions.push( + vscode.languages.registerDocumentFormattingEditProvider( + GO_MODE, + new GoDocumentFormattingEditProvider() + ) + ); + ctx.subscriptions.push( + vscode.languages.registerTypeDefinitionProvider( + GO_MODE, + new GoTypeDefinitionProvider() + ) + ); + ctx.subscriptions.push( + vscode.languages.registerRenameProvider( + GO_MODE, + new GoRenameProvider() + ) + ); } - if (vscode.window.activeTextEditor && vscode.window.activeTextEditor.document.languageId === 'go' && isGoPathSet()) { - runBuilds(vscode.window.activeTextEditor.document, vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor.document.uri)); + if ( + vscode.window.activeTextEditor && + vscode.window.activeTextEditor.document.languageId === 'go' && + isGoPathSet() + ) { + runBuilds( + vscode.window.activeTextEditor.document, + vscode.workspace.getConfiguration( + 'go', + vscode.window.activeTextEditor.document.uri + ) + ); } }); @@ -274,277 +585,512 @@ export function activate(ctx: vscode.ExtensionContext): void { let testCodeLensProvider = new GoRunTestCodeLensProvider(); let referencesCodeLensProvider = new GoReferencesCodeLensProvider(); - - ctx.subscriptions.push(vscode.languages.registerCodeActionsProvider(GO_MODE, new GoCodeActionProvider())); - ctx.subscriptions.push(vscode.languages.registerCodeActionsProvider(GO_MODE, new GoRefactorProvider())); - ctx.subscriptions.push(vscode.languages.registerCodeLensProvider(GO_MODE, testCodeLensProvider)); - ctx.subscriptions.push(vscode.languages.registerCodeLensProvider(GO_MODE, referencesCodeLensProvider)); - ctx.subscriptions.push(vscode.debug.registerDebugConfigurationProvider('go', new GoDebugConfigurationProvider())); - - buildDiagnosticCollection = vscode.languages.createDiagnosticCollection('go'); + ctx.subscriptions.push( + vscode.languages.registerCodeActionsProvider( + GO_MODE, + new GoCodeActionProvider() + ) + ); + ctx.subscriptions.push( + vscode.languages.registerCodeActionsProvider( + GO_MODE, + new GoRefactorProvider() + ) + ); + ctx.subscriptions.push( + vscode.languages.registerCodeLensProvider(GO_MODE, testCodeLensProvider) + ); + ctx.subscriptions.push( + vscode.languages.registerCodeLensProvider( + GO_MODE, + referencesCodeLensProvider + ) + ); + ctx.subscriptions.push( + vscode.debug.registerDebugConfigurationProvider( + 'go', + new GoDebugConfigurationProvider() + ) + ); + + buildDiagnosticCollection = vscode.languages.createDiagnosticCollection( + 'go' + ); ctx.subscriptions.push(buildDiagnosticCollection); - lintDiagnosticCollection = vscode.languages.createDiagnosticCollection('go-lint'); + lintDiagnosticCollection = vscode.languages.createDiagnosticCollection( + 'go-lint' + ); ctx.subscriptions.push(lintDiagnosticCollection); - vetDiagnosticCollection = vscode.languages.createDiagnosticCollection('go-vet'); + vetDiagnosticCollection = vscode.languages.createDiagnosticCollection( + 'go-vet' + ); ctx.subscriptions.push(vetDiagnosticCollection); - vscode.workspace.onDidChangeTextDocument(removeCodeCoverageOnFileChange, null, ctx.subscriptions); - vscode.workspace.onDidChangeTextDocument(removeTestStatus, null, ctx.subscriptions); - vscode.window.onDidChangeActiveTextEditor(showHideStatus, null, ctx.subscriptions); - vscode.window.onDidChangeActiveTextEditor(applyCodeCoverage, null, ctx.subscriptions); - vscode.workspace.onDidChangeTextDocument(parseLiveFile, null, ctx.subscriptions); - vscode.workspace.onDidChangeTextDocument(notifyIfGeneratedFile, ctx, ctx.subscriptions); + vscode.workspace.onDidChangeTextDocument( + removeCodeCoverageOnFileChange, + null, + ctx.subscriptions + ); + vscode.workspace.onDidChangeTextDocument( + removeTestStatus, + null, + ctx.subscriptions + ); + vscode.window.onDidChangeActiveTextEditor( + showHideStatus, + null, + ctx.subscriptions + ); + vscode.window.onDidChangeActiveTextEditor( + applyCodeCoverage, + null, + ctx.subscriptions + ); + vscode.workspace.onDidChangeTextDocument( + parseLiveFile, + null, + ctx.subscriptions + ); + vscode.workspace.onDidChangeTextDocument( + notifyIfGeneratedFile, + ctx, + ctx.subscriptions + ); startBuildOnSaveWatcher(ctx.subscriptions); - ctx.subscriptions.push(vscode.commands.registerCommand('go.gopath', () => { - let gopath = getCurrentGoPath(); - let msg = `${gopath} is the current GOPATH.`; - let wasInfered = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null)['inferGopath']; - let root = vscode.workspace.rootPath; - if (vscode.window.activeTextEditor && vscode.workspace.getWorkspaceFolder(vscode.window.activeTextEditor.document.uri)) { - root = vscode.workspace.getWorkspaceFolder(vscode.window.activeTextEditor.document.uri).uri.fsPath; - root = fixDriveCasingInWindows(root); - } - - // not only if it was configured, but if it was successful. - if (wasInfered && root && root.indexOf(gopath) === 0) { - const inferredFrom = vscode.window.activeTextEditor ? 'current folder' : 'workspace root'; - msg += ` It is inferred from ${inferredFrom}`; - } - - vscode.window.showInformationMessage(msg); - return gopath; - })); - - ctx.subscriptions.push(vscode.commands.registerCommand('go.add.tags', (args) => { - addTags(args); - })); - - ctx.subscriptions.push(vscode.commands.registerCommand('go.remove.tags', (args) => { - removeTags(args); - })); - - ctx.subscriptions.push(vscode.commands.registerCommand('go.fill.struct', () => { - runFillStruct(vscode.window.activeTextEditor); - })); - - ctx.subscriptions.push(vscode.commands.registerCommand('go.impl.cursor', () => { - implCursor(); - })); - ctx.subscriptions.push(vscode.commands.registerCommand('go.godoctor.extract', () => { - extractFunction(); - })); - ctx.subscriptions.push(vscode.commands.registerCommand('go.godoctor.var', () => { - extractVariable(); - })); - - ctx.subscriptions.push(vscode.commands.registerCommand('go.test.cursor', (args) => { - const goConfig = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null); - testAtCursor(goConfig, 'test', args); - })); - - ctx.subscriptions.push(vscode.commands.registerCommand('go.debug.cursor', (args) => { - const goConfig = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null); - testAtCursor(goConfig, 'debug', args); - })); - - ctx.subscriptions.push(vscode.commands.registerCommand('go.benchmark.cursor', (args) => { - const goConfig = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null); - testAtCursor(goConfig, 'benchmark', args); - })); - - ctx.subscriptions.push(vscode.commands.registerCommand('go.test.package', (args) => { - let goConfig = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null); - let isBenchmark = false; - testCurrentPackage(goConfig, isBenchmark, args); - })); - - ctx.subscriptions.push(vscode.commands.registerCommand('go.benchmark.package', (args) => { - let goConfig = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null); - let isBenchmark = true; - testCurrentPackage(goConfig, isBenchmark, args); - })); - - ctx.subscriptions.push(vscode.commands.registerCommand('go.test.file', (args) => { - let goConfig = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null); - let isBenchmark = false; - testCurrentFile(goConfig, isBenchmark, args); - })); - - ctx.subscriptions.push(vscode.commands.registerCommand('go.benchmark.file', (args) => { - let goConfig = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null); - let isBenchmark = true; - testCurrentFile(goConfig, isBenchmark, args); - })); - - ctx.subscriptions.push(vscode.commands.registerCommand('go.test.workspace', (args) => { - let goConfig = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null); - testWorkspace(goConfig, args); - })); - - ctx.subscriptions.push(vscode.commands.registerCommand('go.test.previous', () => { - testPrevious(); - })); - - ctx.subscriptions.push(vscode.commands.registerCommand('go.test.coverage', () => { - toggleCoverageCurrentPackage(); - })); - - ctx.subscriptions.push(vscode.commands.registerCommand('go.test.showOutput', () => { - showTestOutput(); - })); - - ctx.subscriptions.push(vscode.commands.registerCommand('go.test.cancel', () => { - cancelRunningTests(); - })); - - ctx.subscriptions.push(vscode.commands.registerCommand('go.import.add', (arg: string) => { - return addImport(typeof arg === 'string' ? arg : null); - })); - - ctx.subscriptions.push(vscode.commands.registerCommand('go.add.package.workspace', () => { - addImportToWorkspace(); - })); - - ctx.subscriptions.push(vscode.commands.registerCommand('go.tools.install', (args) => { - if (Array.isArray(args) && args.length) { - getGoVersion().then(goVersion => { - installTools(args, goVersion); - }); - return; - } - installAllTools(); - })); + ctx.subscriptions.push( + vscode.commands.registerCommand('go.gopath', () => { + let gopath = getCurrentGoPath(); + let msg = `${gopath} is the current GOPATH.`; + let wasInfered = vscode.workspace.getConfiguration( + 'go', + vscode.window.activeTextEditor + ? vscode.window.activeTextEditor.document.uri + : null + )['inferGopath']; + let root = vscode.workspace.rootPath; + if ( + vscode.window.activeTextEditor && + vscode.workspace.getWorkspaceFolder( + vscode.window.activeTextEditor.document.uri + ) + ) { + root = vscode.workspace.getWorkspaceFolder( + vscode.window.activeTextEditor.document.uri + ).uri.fsPath; + root = fixDriveCasingInWindows(root); + } - ctx.subscriptions.push(vscode.commands.registerCommand('go.browse.packages', () => { - browsePackages(); - })); + // not only if it was configured, but if it was successful. + if (wasInfered && root && root.indexOf(gopath) === 0) { + const inferredFrom = vscode.window.activeTextEditor + ? 'current folder' + : 'workspace root'; + msg += ` It is inferred from ${inferredFrom}`; + } - ctx.subscriptions.push(vscode.workspace.onDidChangeConfiguration((e: vscode.ConfigurationChangeEvent) => { - if (!e.affectsConfiguration('go')) { - return; - } - let updatedGoConfig = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null); - sendTelemetryEventForConfig(updatedGoConfig); - updateGoPathGoRootFromConfig(); - - // If there was a change in "useLanguageServer" setting, then ask the user to reload VS Code. - if (didLangServerConfigChange(e) - && (!updatedGoConfig['useLanguageServer'] || checkLanguageServer())) { - vscode.window.showInformationMessage('Reload VS Code window for the change in usage of language server to take effect', 'Reload').then(selected => { - if (selected === 'Reload') { - vscode.commands.executeCommand('workbench.action.reloadWindow'); - } - }); - } - useLangServer = updatedGoConfig['useLanguageServer']; + vscode.window.showInformationMessage(msg); + return gopath; + }) + ); - // If there was a change in "toolsGopath" setting, then clear cache for go tools - if (getToolsGopath() !== getToolsGopath(false)) { - clearCacheForTools(); - } + ctx.subscriptions.push( + vscode.commands.registerCommand('go.add.tags', args => { + addTags(args); + }) + ); - if (updatedGoConfig['enableCodeLens']) { - testCodeLensProvider.setEnabled(updatedGoConfig['enableCodeLens']['runtest']); - referencesCodeLensProvider.setEnabled(updatedGoConfig['enableCodeLens']['references']); - } + ctx.subscriptions.push( + vscode.commands.registerCommand('go.remove.tags', args => { + removeTags(args); + }) + ); - if (e.affectsConfiguration('go.formatTool')) { - checkToolExists(updatedGoConfig['formatTool']); - } - if (e.affectsConfiguration('go.lintTool')) { - checkToolExists(updatedGoConfig['lintTool']); - } - if (e.affectsConfiguration('go.docsTool')) { - checkToolExists(updatedGoConfig['docsTool']); - } - if (e.affectsConfiguration('go.coverageDecorator')) { - updateCodeCoverageDecorators(updatedGoConfig['coverageDecorator']); - } - })); + ctx.subscriptions.push( + vscode.commands.registerCommand('go.fill.struct', () => { + runFillStruct(vscode.window.activeTextEditor); + }) + ); - ctx.subscriptions.push(vscode.commands.registerCommand('go.test.generate.package', () => { - goGenerateTests.generateTestCurrentPackage(); - })); + ctx.subscriptions.push( + vscode.commands.registerCommand('go.impl.cursor', () => { + implCursor(); + }) + ); + ctx.subscriptions.push( + vscode.commands.registerCommand('go.godoctor.extract', () => { + extractFunction(); + }) + ); + ctx.subscriptions.push( + vscode.commands.registerCommand('go.godoctor.var', () => { + extractVariable(); + }) + ); + + ctx.subscriptions.push( + vscode.commands.registerCommand('go.test.cursor', args => { + const goConfig = vscode.workspace.getConfiguration( + 'go', + vscode.window.activeTextEditor + ? vscode.window.activeTextEditor.document.uri + : null + ); + testAtCursor(goConfig, 'test', args); + }) + ); + + ctx.subscriptions.push( + vscode.commands.registerCommand('go.debug.cursor', args => { + const goConfig = vscode.workspace.getConfiguration( + 'go', + vscode.window.activeTextEditor + ? vscode.window.activeTextEditor.document.uri + : null + ); + testAtCursor(goConfig, 'debug', args); + }) + ); + + ctx.subscriptions.push( + vscode.commands.registerCommand('go.benchmark.cursor', args => { + const goConfig = vscode.workspace.getConfiguration( + 'go', + vscode.window.activeTextEditor + ? vscode.window.activeTextEditor.document.uri + : null + ); + testAtCursor(goConfig, 'benchmark', args); + }) + ); + + ctx.subscriptions.push( + vscode.commands.registerCommand('go.test.package', args => { + let goConfig = vscode.workspace.getConfiguration( + 'go', + vscode.window.activeTextEditor + ? vscode.window.activeTextEditor.document.uri + : null + ); + let isBenchmark = false; + testCurrentPackage(goConfig, isBenchmark, args); + }) + ); + + ctx.subscriptions.push( + vscode.commands.registerCommand('go.benchmark.package', args => { + let goConfig = vscode.workspace.getConfiguration( + 'go', + vscode.window.activeTextEditor + ? vscode.window.activeTextEditor.document.uri + : null + ); + let isBenchmark = true; + testCurrentPackage(goConfig, isBenchmark, args); + }) + ); + + ctx.subscriptions.push( + vscode.commands.registerCommand('go.test.file', args => { + let goConfig = vscode.workspace.getConfiguration( + 'go', + vscode.window.activeTextEditor + ? vscode.window.activeTextEditor.document.uri + : null + ); + let isBenchmark = false; + testCurrentFile(goConfig, isBenchmark, args); + }) + ); + + ctx.subscriptions.push( + vscode.commands.registerCommand('go.benchmark.file', args => { + let goConfig = vscode.workspace.getConfiguration( + 'go', + vscode.window.activeTextEditor + ? vscode.window.activeTextEditor.document.uri + : null + ); + let isBenchmark = true; + testCurrentFile(goConfig, isBenchmark, args); + }) + ); + + ctx.subscriptions.push( + vscode.commands.registerCommand('go.test.workspace', args => { + let goConfig = vscode.workspace.getConfiguration( + 'go', + vscode.window.activeTextEditor + ? vscode.window.activeTextEditor.document.uri + : null + ); + testWorkspace(goConfig, args); + }) + ); - ctx.subscriptions.push(vscode.commands.registerCommand('go.test.generate.file', () => { - goGenerateTests.generateTestCurrentFile(); - })); + ctx.subscriptions.push( + vscode.commands.registerCommand('go.test.previous', () => { + testPrevious(); + }) + ); - ctx.subscriptions.push(vscode.commands.registerCommand('go.test.generate.function', () => { - goGenerateTests.generateTestCurrentFunction(); - })); + ctx.subscriptions.push( + vscode.commands.registerCommand('go.test.coverage', () => { + toggleCoverageCurrentPackage(); + }) + ); - ctx.subscriptions.push(vscode.commands.registerCommand('go.toggle.test.file', () => { - goGenerateTests.toggleTestFile(); - })); + ctx.subscriptions.push( + vscode.commands.registerCommand('go.test.showOutput', () => { + showTestOutput(); + }) + ); - ctx.subscriptions.push(vscode.commands.registerCommand('go.debug.startSession', config => { - let workspaceFolder; - if (vscode.window.activeTextEditor) { - workspaceFolder = vscode.workspace.getWorkspaceFolder(vscode.window.activeTextEditor.document.uri); - } + ctx.subscriptions.push( + vscode.commands.registerCommand('go.test.cancel', () => { + cancelRunningTests(); + }) + ); - return vscode.debug.startDebugging(workspaceFolder, config); - })); + ctx.subscriptions.push( + vscode.commands.registerCommand('go.import.add', (arg: string) => { + return addImport(typeof arg === 'string' ? arg : null); + }) + ); - ctx.subscriptions.push(vscode.commands.registerCommand('go.show.commands', () => { - let extCommands = getExtensionCommands(); - extCommands.push({ - command: 'editor.action.goToDeclaration', - title: 'Go to Definition' - }); - extCommands.push({ - command: 'editor.action.goToImplementation', - title: 'Go to Implementation' - }); - extCommands.push({ - command: 'workbench.action.gotoSymbol', - title: 'Go to Symbol in File...' - }); - extCommands.push({ - command: 'workbench.action.showAllSymbols', - title: 'Go to Symbol in Workspace...' - }); - vscode.window.showQuickPick(extCommands.map(x => x.title)).then(cmd => { - let selectedCmd = extCommands.find(x => x.title === cmd); - if (selectedCmd) { - vscode.commands.executeCommand(selectedCmd.command); + ctx.subscriptions.push( + vscode.commands.registerCommand('go.add.package.workspace', () => { + addImportToWorkspace(); + }) + ); + + ctx.subscriptions.push( + vscode.commands.registerCommand('go.tools.install', args => { + if (Array.isArray(args) && args.length) { + getGoVersion().then(goVersion => { + installTools(args, goVersion); + }); + return; } - }); - })); + installAllTools(); + }) + ); - ctx.subscriptions.push(vscode.commands.registerCommand('go.get.package', goGetPackage)); + ctx.subscriptions.push( + vscode.commands.registerCommand('go.browse.packages', () => { + browsePackages(); + }) + ); - ctx.subscriptions.push(vscode.commands.registerCommand('go.playground', playgroundCommand)); + ctx.subscriptions.push( + vscode.workspace.onDidChangeConfiguration( + (e: vscode.ConfigurationChangeEvent) => { + if (!e.affectsConfiguration('go')) { + return; + } + let updatedGoConfig = vscode.workspace.getConfiguration( + 'go', + vscode.window.activeTextEditor + ? vscode.window.activeTextEditor.document.uri + : null + ); + sendTelemetryEventForConfig(updatedGoConfig); + updateGoPathGoRootFromConfig(); + + // If there was a change in "useLanguageServer" setting, then ask the user to reload VS Code. + if ( + didLangServerConfigChange(e) && + (!updatedGoConfig['useLanguageServer'] || + checkLanguageServer()) + ) { + vscode.window + .showInformationMessage( + 'Reload VS Code window for the change in usage of language server to take effect', + 'Reload' + ) + .then(selected => { + if (selected === 'Reload') { + vscode.commands.executeCommand( + 'workbench.action.reloadWindow' + ); + } + }); + } + useLangServer = updatedGoConfig['useLanguageServer']; - ctx.subscriptions.push(vscode.commands.registerCommand('go.lint.package', () => lintCode('package'))); + // If there was a change in "toolsGopath" setting, then clear cache for go tools + if (getToolsGopath() !== getToolsGopath(false)) { + clearCacheForTools(); + } - ctx.subscriptions.push(vscode.commands.registerCommand('go.lint.workspace', () => lintCode('workspace'))); + if (updatedGoConfig['enableCodeLens']) { + testCodeLensProvider.setEnabled( + updatedGoConfig['enableCodeLens']['runtest'] + ); + referencesCodeLensProvider.setEnabled( + updatedGoConfig['enableCodeLens']['references'] + ); + } - ctx.subscriptions.push(vscode.commands.registerCommand('go.lint.file', () => lintCode('file'))); + if (e.affectsConfiguration('go.formatTool')) { + checkToolExists(updatedGoConfig['formatTool']); + } + if (e.affectsConfiguration('go.lintTool')) { + checkToolExists(updatedGoConfig['lintTool']); + } + if (e.affectsConfiguration('go.docsTool')) { + checkToolExists(updatedGoConfig['docsTool']); + } + if (e.affectsConfiguration('go.coverageDecorator')) { + updateCodeCoverageDecorators( + updatedGoConfig['coverageDecorator'] + ); + } + } + ) + ); - ctx.subscriptions.push(vscode.commands.registerCommand('go.vet.package', vetCode)); + ctx.subscriptions.push( + vscode.commands.registerCommand('go.test.generate.package', () => { + goGenerateTests.generateTestCurrentPackage(); + }) + ); - ctx.subscriptions.push(vscode.commands.registerCommand('go.vet.workspace', () => vetCode(true))); + ctx.subscriptions.push( + vscode.commands.registerCommand('go.test.generate.file', () => { + goGenerateTests.generateTestCurrentFile(); + }) + ); - ctx.subscriptions.push(vscode.commands.registerCommand('go.build.package', buildCode)); + ctx.subscriptions.push( + vscode.commands.registerCommand('go.test.generate.function', () => { + goGenerateTests.generateTestCurrentFunction(); + }) + ); - ctx.subscriptions.push(vscode.commands.registerCommand('go.build.workspace', () => buildCode(true))); + ctx.subscriptions.push( + vscode.commands.registerCommand('go.toggle.test.file', () => { + goGenerateTests.toggleTestFile(); + }) + ); + + ctx.subscriptions.push( + vscode.commands.registerCommand('go.debug.startSession', config => { + let workspaceFolder; + if (vscode.window.activeTextEditor) { + workspaceFolder = vscode.workspace.getWorkspaceFolder( + vscode.window.activeTextEditor.document.uri + ); + } - ctx.subscriptions.push(vscode.commands.registerCommand('go.install.package', installCurrentPackage)); + return vscode.debug.startDebugging(workspaceFolder, config); + }) + ); + + ctx.subscriptions.push( + vscode.commands.registerCommand('go.show.commands', () => { + let extCommands = getExtensionCommands(); + extCommands.push({ + command: 'editor.action.goToDeclaration', + title: 'Go to Definition' + }); + extCommands.push({ + command: 'editor.action.goToImplementation', + title: 'Go to Implementation' + }); + extCommands.push({ + command: 'workbench.action.gotoSymbol', + title: 'Go to Symbol in File...' + }); + extCommands.push({ + command: 'workbench.action.showAllSymbols', + title: 'Go to Symbol in Workspace...' + }); + vscode.window + .showQuickPick(extCommands.map(x => x.title)) + .then(cmd => { + let selectedCmd = extCommands.find(x => x.title === cmd); + if (selectedCmd) { + vscode.commands.executeCommand(selectedCmd.command); + } + }); + }) + ); + + ctx.subscriptions.push( + vscode.commands.registerCommand('go.get.package', goGetPackage) + ); + + ctx.subscriptions.push( + vscode.commands.registerCommand('go.playground', playgroundCommand) + ); + + ctx.subscriptions.push( + vscode.commands.registerCommand('go.lint.package', () => + lintCode('package') + ) + ); + + ctx.subscriptions.push( + vscode.commands.registerCommand('go.lint.workspace', () => + lintCode('workspace') + ) + ); + + ctx.subscriptions.push( + vscode.commands.registerCommand('go.lint.file', () => lintCode('file')) + ); + + ctx.subscriptions.push( + vscode.commands.registerCommand('go.vet.package', vetCode) + ); + + ctx.subscriptions.push( + vscode.commands.registerCommand('go.vet.workspace', () => vetCode(true)) + ); + + ctx.subscriptions.push( + vscode.commands.registerCommand('go.build.package', buildCode) + ); + + ctx.subscriptions.push( + vscode.commands.registerCommand('go.build.workspace', () => + buildCode(true) + ) + ); + + ctx.subscriptions.push( + vscode.commands.registerCommand( + 'go.install.package', + installCurrentPackage + ) + ); vscode.languages.setLanguageConfiguration(GO_MODE.language, { - wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\@\#\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g, + wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\@\#\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g }); - sendTelemetryEventForConfig(vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null)); + sendTelemetryEventForConfig( + vscode.workspace.getConfiguration( + 'go', + vscode.window.activeTextEditor + ? vscode.window.activeTextEditor.document.uri + : null + ) + ); } export function deactivate() { - return Promise.all([disposeTelemetryReporter(), cancelRunningTests(), Promise.resolve(cleanupTempDir())]); + return Promise.all([ + disposeTelemetryReporter(), + cancelRunningTests(), + Promise.resolve(cleanupTempDir()) + ]); } -function runBuilds(document: vscode.TextDocument, goConfig: vscode.WorkspaceConfiguration) { +function runBuilds( + document: vscode.TextDocument, + goConfig: vscode.WorkspaceConfiguration +) { if (document.languageId !== 'go') { return; } @@ -555,7 +1101,11 @@ function runBuilds(document: vscode.TextDocument, goConfig: vscode.WorkspaceConf check(document.uri, goConfig) .then(results => { results.forEach(result => { - handleDiagnosticErrors(document, result.errors, result.diagnosticCollection); + handleDiagnosticErrors( + document, + result.errors, + result.diagnosticCollection + ); }); }) .catch(err => { @@ -564,14 +1114,25 @@ function runBuilds(document: vscode.TextDocument, goConfig: vscode.WorkspaceConf } function startBuildOnSaveWatcher(subscriptions: vscode.Disposable[]) { - vscode.workspace.onDidSaveTextDocument(document => { - if (document.languageId !== 'go') { - return; - } - if (vscode.window.visibleTextEditors.some(e => e.document.fileName === document.fileName)) { - runBuilds(document, vscode.workspace.getConfiguration('go', document.uri)); - } - }, null, subscriptions); + vscode.workspace.onDidSaveTextDocument( + document => { + if (document.languageId !== 'go') { + return; + } + if ( + vscode.window.visibleTextEditors.some( + e => e.document.fileName === document.fileName + ) + ) { + runBuilds( + document, + vscode.workspace.getConfiguration('go', document.uri) + ); + } + }, + null, + subscriptions + ); } function sendTelemetryEventForConfig(goConfig: vscode.WorkspaceConfiguration) { @@ -639,24 +1200,39 @@ function sendTelemetryEventForConfig(goConfig: vscode.WorkspaceConfiguration) { toolsGopath: goConfig['toolsGopath'] ? 'set' : '', gocodeAutoBuild: goConfig['gocodeAutoBuild'] + '', gocodePackageLookupMode: goConfig['gocodePackageLookupMode'] + '', - useCodeSnippetsOnFunctionSuggest: goConfig['useCodeSnippetsOnFunctionSuggest'] + '', - useCodeSnippetsOnFunctionSuggestWithoutType: goConfig['useCodeSnippetsOnFunctionSuggestWithoutType'] + '', - autocompleteUnimportedPackages: goConfig['autocompleteUnimportedPackages'] + '', + useCodeSnippetsOnFunctionSuggest: + goConfig['useCodeSnippetsOnFunctionSuggest'] + '', + useCodeSnippetsOnFunctionSuggestWithoutType: + goConfig['useCodeSnippetsOnFunctionSuggestWithoutType'] + '', + autocompleteUnimportedPackages: + goConfig['autocompleteUnimportedPackages'] + '', docsTool: goConfig['docsTool'], useLanguageServer: goConfig['useLanguageServer'] + '', - languageServerExperimentalFeatures: JSON.stringify(goConfig['languageServerExperimentalFeatures']), - includeImports: goConfig['gotoSymbol'] && goConfig['gotoSymbol']['includeImports'] + '', + languageServerExperimentalFeatures: JSON.stringify( + goConfig['languageServerExperimentalFeatures'] + ), + includeImports: + goConfig['gotoSymbol'] && + goConfig['gotoSymbol']['includeImports'] + '', addTags: JSON.stringify(goConfig['addTags']), removeTags: JSON.stringify(goConfig['removeTags']), - editorContextMenuCommands: JSON.stringify(goConfig['editorContextMenuCommands']), + editorContextMenuCommands: JSON.stringify( + goConfig['editorContextMenuCommands'] + ), liveErrors: JSON.stringify(goConfig['liveErrors']), codeLens: JSON.stringify(goConfig['enableCodeLens']), alternateTools: JSON.stringify(goConfig['alternateTools']) }); } -function didLangServerConfigChange(e: vscode.ConfigurationChangeEvent): boolean { - return e.affectsConfiguration('go.useLanguageServer') || e.affectsConfiguration('go.languageServerFlags') || e.affectsConfiguration('go.languageServerExperimentalFeatures'); +function didLangServerConfigChange( + e: vscode.ConfigurationChangeEvent +): boolean { + return ( + e.affectsConfiguration('go.useLanguageServer') || + e.affectsConfiguration('go.languageServerFlags') || + e.affectsConfiguration('go.languageServerExperimentalFeatures') + ); } function checkToolExists(tool: string) { @@ -668,5 +1244,12 @@ function checkToolExists(tool: string) { function registerCompletionProvider(ctx: vscode.ExtensionContext) { let provider = new GoCompletionItemProvider(ctx.globalState); ctx.subscriptions.push(provider); - ctx.subscriptions.push(vscode.languages.registerCompletionItemProvider(GO_MODE, provider, '.', '\"')); + ctx.subscriptions.push( + vscode.languages.registerCompletionItemProvider( + GO_MODE, + provider, + '.', + '"' + ) + ); } From 803b17ab0d315f90504a2b4ac8fcea858a2d382e Mon Sep 17 00:00:00 2001 From: Ramya Achutha Rao Date: Sat, 2 Mar 2019 15:11:47 -0800 Subject: [PATCH 08/13] Revert "Fix conflicts" This reverts commit 17488d2415363442a5f01abbbd4b603a536f73e6. --- src/goMain.ts | 1263 +++++++++++++------------------------------------ 1 file changed, 340 insertions(+), 923 deletions(-) diff --git a/src/goMain.ts b/src/goMain.ts index 91791cefa..57b67935d 100644 --- a/src/goMain.ts +++ b/src/goMain.ts @@ -20,58 +20,23 @@ import { GoSignatureHelpProvider } from './goSignature'; import { GoWorkspaceSymbolProvider } from './goSymbol'; import { GoCodeActionProvider } from './goCodeAction'; import { check, removeTestStatus, notifyIfGeneratedFile } from './goCheck'; -import { - updateGoPathGoRootFromConfig, - offerToInstallTools, - promptForMissingTool, - installTools -} from './goInstallTools'; +import { updateGoPathGoRootFromConfig, offerToInstallTools, promptForMissingTool, installTools } from './goInstallTools'; import { GO_MODE } from './goMode'; import { showHideStatus } from './goStatus'; -import { - initCoverageDecorators, - toggleCoverageCurrentPackage, - applyCodeCoverage, - removeCodeCoverageOnFileChange, - updateCodeCoverageDecorators -} from './goCover'; -import { - testAtCursor, - testCurrentPackage, - testCurrentFile, - testPrevious, - testWorkspace -} from './goTest'; +import { initCoverageDecorators, toggleCoverageCurrentPackage, applyCodeCoverage, removeCodeCoverageOnFileChange, updateCodeCoverageDecorators } from './goCover'; +import { testAtCursor, testCurrentPackage, testCurrentFile, testPrevious, testWorkspace } from './goTest'; import { showTestOutput, cancelRunningTests } from './testUtils'; import * as goGenerateTests from './goGenerateTests'; import { addImport, addImportToWorkspace } from './goImport'; import { installAllTools, checkLanguageServer } from './goInstallTools'; import { - isGoPathSet, - getBinPath, - sendTelemetryEvent, - getExtensionCommands, - getGoVersion, - getCurrentGoPath, - getToolsGopath, - handleDiagnosticErrors, - disposeTelemetryReporter, - getToolsEnvVars, - cleanupTempDir + isGoPathSet, getBinPath, sendTelemetryEvent, getExtensionCommands, getGoVersion, getCurrentGoPath, + getToolsGopath, handleDiagnosticErrors, disposeTelemetryReporter, getToolsEnvVars, cleanupTempDir } from './util'; import { - LanguageClient, - RevealOutputChannelOn, - FormattingOptions, - ProvideDocumentFormattingEditsSignature, - ProvideCompletionItemsSignature, - ProvideRenameEditsSignature, - ProvideDefinitionSignature, - ProvideHoverSignature, - ProvideReferencesSignature, - ProvideSignatureHelpSignature, - ProvideDocumentSymbolsSignature, - ProvideWorkspaceSymbolsSignature + LanguageClient, RevealOutputChannelOn, FormattingOptions, ProvideDocumentFormattingEditsSignature, + ProvideCompletionItemsSignature, ProvideRenameEditsSignature, ProvideDefinitionSignature, ProvideHoverSignature, + ProvideReferencesSignature, ProvideSignatureHelpSignature, ProvideDocumentSymbolsSignature, ProvideWorkspaceSymbolsSignature } from 'vscode-languageclient'; import { clearCacheForTools, fixDriveCasingInWindows } from './goPath'; import { addTags, removeTags } from './goModifytags'; @@ -89,18 +54,19 @@ import { vetCode } from './goVet'; import { buildCode } from './goBuild'; import { installCurrentPackage } from './goInstall'; import { setGlobalState } from './stateUtils'; +<<<<<<< HEAD import { ProvideTypeDefinitionSignature } from 'vscode-languageclient/lib/typeDefinition'; import { ProvideImplementationSignature } from 'vscode-languageclient/lib/implementation'; +======= import { GoRefactorProvider } from './goRefactor'; +>>>>>>> Add godoctor extract function command and code action export let buildDiagnosticCollection: vscode.DiagnosticCollection; export let lintDiagnosticCollection: vscode.DiagnosticCollection; export let vetDiagnosticCollection: vscode.DiagnosticCollection; export function activate(ctx: vscode.ExtensionContext): void { - let useLangServer = vscode.workspace.getConfiguration('go')[ - 'useLanguageServer' - ]; + let useLangServer = vscode.workspace.getConfiguration('go')['useLanguageServer']; setGlobalState(ctx.globalState); updateGoPathGoRootFromConfig().then(() => { @@ -108,36 +74,24 @@ export function activate(ctx: vscode.ExtensionContext): void { const prevGoroot = ctx.globalState.get('goroot'); const currentGoroot = process.env['GOROOT']; if (prevGoroot !== currentGoroot && prevGoroot) { - vscode.window - .showInformationMessage( - 'Your goroot is different than before, a few Go tools may need recompiling', - updateToolsCmdText - ) - .then(selected => { - if (selected === updateToolsCmdText) { - installAllTools(true); - } - }); + vscode.window.showInformationMessage('Your goroot is different than before, a few Go tools may need recompiling', updateToolsCmdText).then(selected => { + if (selected === updateToolsCmdText) { + installAllTools(true); + } + }); } else { getGoVersion().then(currentVersion => { if (currentVersion) { const prevVersion = ctx.globalState.get('goVersion'); - const currVersionString = `${currentVersion.major}.${ - currentVersion.minor - }`; + const currVersionString = `${currentVersion.major}.${currentVersion.minor}`; if (prevVersion !== currVersionString) { if (prevVersion) { - vscode.window - .showInformationMessage( - 'Your Go version is different than before, few Go tools may need re-compiling', - updateToolsCmdText - ) - .then(selected => { - if (selected === updateToolsCmdText) { - installAllTools(true); - } - }); + vscode.window.showInformationMessage('Your Go version is different than before, few Go tools may need re-compiling', updateToolsCmdText).then(selected => { + if (selected === updateToolsCmdText) { + installAllTools(true); + } + }); } ctx.globalState.update('goVersion', currVersionString); } @@ -148,14 +102,8 @@ export function activate(ctx: vscode.ExtensionContext): void { offerToInstallTools(); if (checkLanguageServer()) { - const languageServerExperimentalFeatures: any = - vscode.workspace - .getConfiguration('go') - .get('languageServerExperimentalFeatures') || {}; - let langServerFlags: string[] = - vscode.workspace.getConfiguration('go')[ - 'languageServerFlags' - ] || []; + const languageServerExperimentalFeatures: any = vscode.workspace.getConfiguration('go').get('languageServerExperimentalFeatures') || {}; + let langServerFlags: string[] = vscode.workspace.getConfiguration('go')['languageServerFlags'] || []; const c = new LanguageClient( 'go-langserver', @@ -168,415 +116,156 @@ export function activate(ctx: vscode.ExtensionContext): void { }, { initializationOptions: { - funcSnippetEnabled: vscode.workspace.getConfiguration( - 'go' - )['useCodeSnippetsOnFunctionSuggest'], - gocodeCompletionEnabled: - languageServerExperimentalFeatures['autoComplete'] + funcSnippetEnabled: vscode.workspace.getConfiguration('go')['useCodeSnippetsOnFunctionSuggest'], + gocodeCompletionEnabled: languageServerExperimentalFeatures['autoComplete'] }, documentSelector: ['go'], uriConverters: { // Apply file:/// scheme to all file paths. - code2Protocol: (uri: vscode.Uri): string => - (uri.scheme - ? uri - : uri.with({ scheme: 'file' }) - ).toString(), - protocol2Code: (uri: string) => vscode.Uri.parse(uri) + code2Protocol: (uri: vscode.Uri): string => (uri.scheme ? uri : uri.with({ scheme: 'file' })).toString(), + protocol2Code: (uri: string) => vscode.Uri.parse(uri), }, revealOutputChannelOn: RevealOutputChannelOn.Never, middleware: { - provideDocumentFormattingEdits: ( - document: vscode.TextDocument, - options: FormattingOptions, - token: vscode.CancellationToken, - next: ProvideDocumentFormattingEditsSignature - ) => { - if ( - languageServerExperimentalFeatures['format'] === - true - ) { + provideDocumentFormattingEdits: (document: vscode.TextDocument, options: FormattingOptions, token: vscode.CancellationToken, next: ProvideDocumentFormattingEditsSignature) => { + if (languageServerExperimentalFeatures['format'] === true) { return next(document, options, token); } return []; }, - provideCompletionItem: ( - document: vscode.TextDocument, - position: vscode.Position, - context: vscode.CompletionContext, - token: vscode.CancellationToken, - next: ProvideCompletionItemsSignature - ) => { - if ( - languageServerExperimentalFeatures[ - 'autoComplete' - ] === true - ) { + provideCompletionItem: (document: vscode.TextDocument, position: vscode.Position, context: vscode.CompletionContext, token: vscode.CancellationToken, next: ProvideCompletionItemsSignature) => { + if (languageServerExperimentalFeatures['autoComplete'] === true) { return next(document, position, context, token); } return []; }, - provideRenameEdits: ( - document: vscode.TextDocument, - position: vscode.Position, - newName: string, - token: vscode.CancellationToken, - next: ProvideRenameEditsSignature - ) => { - if ( - languageServerExperimentalFeatures['rename'] === - true - ) { + provideRenameEdits: (document: vscode.TextDocument, position: vscode.Position, newName: string, token: vscode.CancellationToken, next: ProvideRenameEditsSignature) => { + if (languageServerExperimentalFeatures['rename'] === true) { return next(document, position, newName, token); } return null; }, - provideDefinition: ( - document: vscode.TextDocument, - position: vscode.Position, - token: vscode.CancellationToken, - next: ProvideDefinitionSignature - ) => { - if ( - languageServerExperimentalFeatures[ - 'goToDefinition' - ] === true - ) { + provideDefinition: (document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, next: ProvideDefinitionSignature) => { + if (languageServerExperimentalFeatures['goToDefinition'] === true) { return next(document, position, token); } return null; }, - provideTypeDefinition: ( - document: vscode.TextDocument, - position: vscode.Position, - token: vscode.CancellationToken, - next: ProvideTypeDefinitionSignature - ) => { - if ( - languageServerExperimentalFeatures[ - 'goToTypeDefinition' - ] === true - ) { + provideTypeDefinition: (document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, next: ProvideTypeDefinitionSignature) => { + if (languageServerExperimentalFeatures['goToTypeDefinition'] === true) { return next(document, position, token); } return null; }, - provideHover: ( - document: vscode.TextDocument, - position: vscode.Position, - token: vscode.CancellationToken, - next: ProvideHoverSignature - ) => { - if ( - languageServerExperimentalFeatures['hover'] === - true - ) { + provideHover: (document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, next: ProvideHoverSignature) => { + if (languageServerExperimentalFeatures['hover'] === true) { return next(document, position, token); } return null; }, - provideReferences: ( - document: vscode.TextDocument, - position: vscode.Position, - options: { includeDeclaration: boolean }, - token: vscode.CancellationToken, - next: ProvideReferencesSignature - ) => { - if ( - languageServerExperimentalFeatures[ - 'findReferences' - ] === true - ) { + provideReferences: (document: vscode.TextDocument, position: vscode.Position, options: { includeDeclaration: boolean }, token: vscode.CancellationToken, next: ProvideReferencesSignature) => { + if (languageServerExperimentalFeatures['findReferences'] === true) { return next(document, position, options, token); } return []; }, - provideSignatureHelp: ( - document: vscode.TextDocument, - position: vscode.Position, - token: vscode.CancellationToken, - next: ProvideSignatureHelpSignature - ) => { - if ( - languageServerExperimentalFeatures[ - 'signatureHelp' - ] === true - ) { + provideSignatureHelp: (document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, next: ProvideSignatureHelpSignature) => { + if (languageServerExperimentalFeatures['signatureHelp'] === true) { return next(document, position, token); } return null; }, - provideDocumentSymbols: ( - document: vscode.TextDocument, - token: vscode.CancellationToken, - next: ProvideDocumentSymbolsSignature - ) => { - if ( - languageServerExperimentalFeatures[ - 'documentSymbols' - ] === true - ) { + provideDocumentSymbols: (document: vscode.TextDocument, token: vscode.CancellationToken, next: ProvideDocumentSymbolsSignature) => { + if (languageServerExperimentalFeatures['documentSymbols'] === true) { return next(document, token); } return []; }, - provideWorkspaceSymbols: ( - query: string, - token: vscode.CancellationToken, - next: ProvideWorkspaceSymbolsSignature - ) => { - if ( - languageServerExperimentalFeatures[ - 'workspaceSymbols' - ] === true - ) { + provideWorkspaceSymbols: (query: string, token: vscode.CancellationToken, next: ProvideWorkspaceSymbolsSignature) => { + if (languageServerExperimentalFeatures['workspaceSymbols'] === true) { return next(query, token); } return []; }, - provideImplementation: ( - document: vscode.TextDocument, - position: vscode.Position, - token: vscode.CancellationToken, - next: ProvideImplementationSignature - ) => { - if ( - languageServerExperimentalFeatures[ - 'goToImplementation' - ] === true - ) { + provideImplementation: (document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, next: ProvideImplementationSignature) => { + if (languageServerExperimentalFeatures['goToImplementation'] === true) { return next(document, position, token); } return null; - } + }, } } ); c.onReady().then(() => { - const capabilities = - c.initializeResult && c.initializeResult.capabilities; + const capabilities = c.initializeResult && c.initializeResult.capabilities; if (!capabilities) { - return vscode.window.showErrorMessage( - 'The language server is not able to serve any features at the moment.' - ); + return vscode.window.showErrorMessage('The language server is not able to serve any features at the moment.'); } - if ( - languageServerExperimentalFeatures['autoComplete'] !== - true || - !capabilities.completionProvider - ) { + if (languageServerExperimentalFeatures['autoComplete'] !== true || !capabilities.completionProvider) { registerCompletionProvider(ctx); } - if ( - languageServerExperimentalFeatures['format'] !== true || - !capabilities.documentFormattingProvider - ) { - ctx.subscriptions.push( - vscode.languages.registerDocumentFormattingEditProvider( - GO_MODE, - new GoDocumentFormattingEditProvider() - ) - ); + if (languageServerExperimentalFeatures['format'] !== true || !capabilities.documentFormattingProvider) { + ctx.subscriptions.push(vscode.languages.registerDocumentFormattingEditProvider(GO_MODE, new GoDocumentFormattingEditProvider())); } - if ( - languageServerExperimentalFeatures['rename'] !== true || - !capabilities.renameProvider - ) { - ctx.subscriptions.push( - vscode.languages.registerRenameProvider( - GO_MODE, - new GoRenameProvider() - ) - ); + if (languageServerExperimentalFeatures['rename'] !== true || !capabilities.renameProvider) { + ctx.subscriptions.push(vscode.languages.registerRenameProvider(GO_MODE, new GoRenameProvider())); } - if ( - languageServerExperimentalFeatures['goToTypeDefinition'] !== - true || - !capabilities.typeDefinitionProvider - ) { - ctx.subscriptions.push( - vscode.languages.registerTypeDefinitionProvider( - GO_MODE, - new GoTypeDefinitionProvider() - ) - ); + if (languageServerExperimentalFeatures['goToTypeDefinition'] !== true || !capabilities.typeDefinitionProvider) { + ctx.subscriptions.push(vscode.languages.registerTypeDefinitionProvider(GO_MODE, new GoTypeDefinitionProvider())); } - if ( - languageServerExperimentalFeatures['hover'] !== true || - !capabilities.hoverProvider - ) { - ctx.subscriptions.push( - vscode.languages.registerHoverProvider( - GO_MODE, - new GoHoverProvider() - ) - ); + if (languageServerExperimentalFeatures['hover'] !== true || !capabilities.hoverProvider) { + ctx.subscriptions.push(vscode.languages.registerHoverProvider(GO_MODE, new GoHoverProvider())); } - if ( - languageServerExperimentalFeatures['goToDefinition'] !== - true || - !capabilities.definitionProvider - ) { - ctx.subscriptions.push( - vscode.languages.registerDefinitionProvider( - GO_MODE, - new GoDefinitionProvider() - ) - ); + if (languageServerExperimentalFeatures['goToDefinition'] !== true || !capabilities.definitionProvider) { + ctx.subscriptions.push(vscode.languages.registerDefinitionProvider(GO_MODE, new GoDefinitionProvider())); } - if ( - languageServerExperimentalFeatures['findReferences'] !== - true || - !capabilities.referencesProvider - ) { - ctx.subscriptions.push( - vscode.languages.registerReferenceProvider( - GO_MODE, - new GoReferenceProvider() - ) - ); + if (languageServerExperimentalFeatures['findReferences'] !== true || !capabilities.referencesProvider) { + ctx.subscriptions.push(vscode.languages.registerReferenceProvider(GO_MODE, new GoReferenceProvider())); } - if ( - languageServerExperimentalFeatures['documentSymbols'] !== - true || - !capabilities.documentSymbolProvider - ) { - ctx.subscriptions.push( - vscode.languages.registerDocumentSymbolProvider( - GO_MODE, - new GoDocumentSymbolProvider() - ) - ); + if (languageServerExperimentalFeatures['documentSymbols'] !== true || !capabilities.documentSymbolProvider) { + ctx.subscriptions.push(vscode.languages.registerDocumentSymbolProvider(GO_MODE, new GoDocumentSymbolProvider())); } - if ( - languageServerExperimentalFeatures['signatureHelp'] !== - true || - !capabilities.signatureHelpProvider - ) { - ctx.subscriptions.push( - vscode.languages.registerSignatureHelpProvider( - GO_MODE, - new GoSignatureHelpProvider(), - '(', - ',' - ) - ); + if (languageServerExperimentalFeatures['signatureHelp'] !== true || !capabilities.signatureHelpProvider) { + ctx.subscriptions.push(vscode.languages.registerSignatureHelpProvider(GO_MODE, new GoSignatureHelpProvider(), '(', ',')); } - if ( - languageServerExperimentalFeatures['workspaceSymbols'] !== - true || - !capabilities.workspaceSymbolProvider - ) { - ctx.subscriptions.push( - vscode.languages.registerWorkspaceSymbolProvider( - new GoWorkspaceSymbolProvider() - ) - ); + if (languageServerExperimentalFeatures['workspaceSymbols'] !== true || !capabilities.workspaceSymbolProvider) { + ctx.subscriptions.push(vscode.languages.registerWorkspaceSymbolProvider(new GoWorkspaceSymbolProvider())); } - if ( - languageServerExperimentalFeatures['goToImplementation'] !== - true || - !capabilities.implementationProvider - ) { - ctx.subscriptions.push( - vscode.languages.registerImplementationProvider( - GO_MODE, - new GoImplementationProvider() - ) - ); + if (languageServerExperimentalFeatures['goToImplementation'] !== true || !capabilities.implementationProvider) { + ctx.subscriptions.push(vscode.languages.registerImplementationProvider(GO_MODE, new GoImplementationProvider())); } + }); ctx.subscriptions.push(c.start()); } else { registerCompletionProvider(ctx); - ctx.subscriptions.push( - vscode.languages.registerHoverProvider( - GO_MODE, - new GoHoverProvider() - ) - ); - ctx.subscriptions.push( - vscode.languages.registerDefinitionProvider( - GO_MODE, - new GoDefinitionProvider() - ) - ); - ctx.subscriptions.push( - vscode.languages.registerReferenceProvider( - GO_MODE, - new GoReferenceProvider() - ) - ); - ctx.subscriptions.push( - vscode.languages.registerDocumentSymbolProvider( - GO_MODE, - new GoDocumentSymbolProvider() - ) - ); - ctx.subscriptions.push( - vscode.languages.registerWorkspaceSymbolProvider( - new GoWorkspaceSymbolProvider() - ) - ); - ctx.subscriptions.push( - vscode.languages.registerSignatureHelpProvider( - GO_MODE, - new GoSignatureHelpProvider(), - '(', - ',' - ) - ); - ctx.subscriptions.push( - vscode.languages.registerImplementationProvider( - GO_MODE, - new GoImplementationProvider() - ) - ); - ctx.subscriptions.push( - vscode.languages.registerDocumentFormattingEditProvider( - GO_MODE, - new GoDocumentFormattingEditProvider() - ) - ); - ctx.subscriptions.push( - vscode.languages.registerTypeDefinitionProvider( - GO_MODE, - new GoTypeDefinitionProvider() - ) - ); - ctx.subscriptions.push( - vscode.languages.registerRenameProvider( - GO_MODE, - new GoRenameProvider() - ) - ); + ctx.subscriptions.push(vscode.languages.registerHoverProvider(GO_MODE, new GoHoverProvider())); + ctx.subscriptions.push(vscode.languages.registerDefinitionProvider(GO_MODE, new GoDefinitionProvider())); + ctx.subscriptions.push(vscode.languages.registerReferenceProvider(GO_MODE, new GoReferenceProvider())); + ctx.subscriptions.push(vscode.languages.registerDocumentSymbolProvider(GO_MODE, new GoDocumentSymbolProvider())); + ctx.subscriptions.push(vscode.languages.registerWorkspaceSymbolProvider(new GoWorkspaceSymbolProvider())); + ctx.subscriptions.push(vscode.languages.registerSignatureHelpProvider(GO_MODE, new GoSignatureHelpProvider(), '(', ',')); + ctx.subscriptions.push(vscode.languages.registerImplementationProvider(GO_MODE, new GoImplementationProvider())); + ctx.subscriptions.push(vscode.languages.registerDocumentFormattingEditProvider(GO_MODE, new GoDocumentFormattingEditProvider())); + ctx.subscriptions.push(vscode.languages.registerTypeDefinitionProvider(GO_MODE, new GoTypeDefinitionProvider())); + ctx.subscriptions.push(vscode.languages.registerRenameProvider(GO_MODE, new GoRenameProvider())); } - if ( - vscode.window.activeTextEditor && - vscode.window.activeTextEditor.document.languageId === 'go' && - isGoPathSet() - ) { - runBuilds( - vscode.window.activeTextEditor.document, - vscode.workspace.getConfiguration( - 'go', - vscode.window.activeTextEditor.document.uri - ) - ); + if (vscode.window.activeTextEditor && vscode.window.activeTextEditor.document.languageId === 'go' && isGoPathSet()) { + runBuilds(vscode.window.activeTextEditor.document, vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor.document.uri)); } }); @@ -585,512 +274,277 @@ export function activate(ctx: vscode.ExtensionContext): void { let testCodeLensProvider = new GoRunTestCodeLensProvider(); let referencesCodeLensProvider = new GoReferencesCodeLensProvider(); - ctx.subscriptions.push( - vscode.languages.registerCodeActionsProvider( - GO_MODE, - new GoCodeActionProvider() - ) - ); - ctx.subscriptions.push( - vscode.languages.registerCodeActionsProvider( - GO_MODE, - new GoRefactorProvider() - ) - ); - ctx.subscriptions.push( - vscode.languages.registerCodeLensProvider(GO_MODE, testCodeLensProvider) - ); - ctx.subscriptions.push( - vscode.languages.registerCodeLensProvider( - GO_MODE, - referencesCodeLensProvider - ) - ); - ctx.subscriptions.push( - vscode.debug.registerDebugConfigurationProvider( - 'go', - new GoDebugConfigurationProvider() - ) - ); - - buildDiagnosticCollection = vscode.languages.createDiagnosticCollection( - 'go' - ); + + ctx.subscriptions.push(vscode.languages.registerCodeActionsProvider(GO_MODE, new GoCodeActionProvider())); + ctx.subscriptions.push(vscode.languages.registerCodeActionsProvider(GO_MODE, new GoRefactorProvider())); + ctx.subscriptions.push(vscode.languages.registerCodeLensProvider(GO_MODE, testCodeLensProvider)); + ctx.subscriptions.push(vscode.languages.registerCodeLensProvider(GO_MODE, referencesCodeLensProvider)); + ctx.subscriptions.push(vscode.debug.registerDebugConfigurationProvider('go', new GoDebugConfigurationProvider())); + + buildDiagnosticCollection = vscode.languages.createDiagnosticCollection('go'); ctx.subscriptions.push(buildDiagnosticCollection); - lintDiagnosticCollection = vscode.languages.createDiagnosticCollection( - 'go-lint' - ); + lintDiagnosticCollection = vscode.languages.createDiagnosticCollection('go-lint'); ctx.subscriptions.push(lintDiagnosticCollection); - vetDiagnosticCollection = vscode.languages.createDiagnosticCollection( - 'go-vet' - ); + vetDiagnosticCollection = vscode.languages.createDiagnosticCollection('go-vet'); ctx.subscriptions.push(vetDiagnosticCollection); - vscode.workspace.onDidChangeTextDocument( - removeCodeCoverageOnFileChange, - null, - ctx.subscriptions - ); - vscode.workspace.onDidChangeTextDocument( - removeTestStatus, - null, - ctx.subscriptions - ); - vscode.window.onDidChangeActiveTextEditor( - showHideStatus, - null, - ctx.subscriptions - ); - vscode.window.onDidChangeActiveTextEditor( - applyCodeCoverage, - null, - ctx.subscriptions - ); - vscode.workspace.onDidChangeTextDocument( - parseLiveFile, - null, - ctx.subscriptions - ); - vscode.workspace.onDidChangeTextDocument( - notifyIfGeneratedFile, - ctx, - ctx.subscriptions - ); + vscode.workspace.onDidChangeTextDocument(removeCodeCoverageOnFileChange, null, ctx.subscriptions); + vscode.workspace.onDidChangeTextDocument(removeTestStatus, null, ctx.subscriptions); + vscode.window.onDidChangeActiveTextEditor(showHideStatus, null, ctx.subscriptions); + vscode.window.onDidChangeActiveTextEditor(applyCodeCoverage, null, ctx.subscriptions); + vscode.workspace.onDidChangeTextDocument(parseLiveFile, null, ctx.subscriptions); + vscode.workspace.onDidChangeTextDocument(notifyIfGeneratedFile, ctx, ctx.subscriptions); startBuildOnSaveWatcher(ctx.subscriptions); - ctx.subscriptions.push( - vscode.commands.registerCommand('go.gopath', () => { - let gopath = getCurrentGoPath(); - let msg = `${gopath} is the current GOPATH.`; - let wasInfered = vscode.workspace.getConfiguration( - 'go', - vscode.window.activeTextEditor - ? vscode.window.activeTextEditor.document.uri - : null - )['inferGopath']; - let root = vscode.workspace.rootPath; - if ( - vscode.window.activeTextEditor && - vscode.workspace.getWorkspaceFolder( - vscode.window.activeTextEditor.document.uri - ) - ) { - root = vscode.workspace.getWorkspaceFolder( - vscode.window.activeTextEditor.document.uri - ).uri.fsPath; - root = fixDriveCasingInWindows(root); - } + ctx.subscriptions.push(vscode.commands.registerCommand('go.gopath', () => { + let gopath = getCurrentGoPath(); + let msg = `${gopath} is the current GOPATH.`; + let wasInfered = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null)['inferGopath']; + let root = vscode.workspace.rootPath; + if (vscode.window.activeTextEditor && vscode.workspace.getWorkspaceFolder(vscode.window.activeTextEditor.document.uri)) { + root = vscode.workspace.getWorkspaceFolder(vscode.window.activeTextEditor.document.uri).uri.fsPath; + root = fixDriveCasingInWindows(root); + } - // not only if it was configured, but if it was successful. - if (wasInfered && root && root.indexOf(gopath) === 0) { - const inferredFrom = vscode.window.activeTextEditor - ? 'current folder' - : 'workspace root'; - msg += ` It is inferred from ${inferredFrom}`; - } + // not only if it was configured, but if it was successful. + if (wasInfered && root && root.indexOf(gopath) === 0) { + const inferredFrom = vscode.window.activeTextEditor ? 'current folder' : 'workspace root'; + msg += ` It is inferred from ${inferredFrom}`; + } - vscode.window.showInformationMessage(msg); - return gopath; - }) - ); + vscode.window.showInformationMessage(msg); + return gopath; + })); + + ctx.subscriptions.push(vscode.commands.registerCommand('go.add.tags', (args) => { + addTags(args); + })); + + ctx.subscriptions.push(vscode.commands.registerCommand('go.remove.tags', (args) => { + removeTags(args); + })); + + ctx.subscriptions.push(vscode.commands.registerCommand('go.fill.struct', () => { + runFillStruct(vscode.window.activeTextEditor); + })); + + ctx.subscriptions.push(vscode.commands.registerCommand('go.impl.cursor', () => { + implCursor(); + })); + ctx.subscriptions.push(vscode.commands.registerCommand('go.godoctor.extract', () => { + extractFunction(); + })); + ctx.subscriptions.push(vscode.commands.registerCommand('go.godoctor.var', () => { + extractVariable(); + })); + + ctx.subscriptions.push(vscode.commands.registerCommand('go.test.cursor', (args) => { + const goConfig = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null); + testAtCursor(goConfig, 'test', args); + })); + + ctx.subscriptions.push(vscode.commands.registerCommand('go.debug.cursor', (args) => { + const goConfig = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null); + testAtCursor(goConfig, 'debug', args); + })); + + ctx.subscriptions.push(vscode.commands.registerCommand('go.benchmark.cursor', (args) => { + const goConfig = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null); + testAtCursor(goConfig, 'benchmark', args); + })); + + ctx.subscriptions.push(vscode.commands.registerCommand('go.test.package', (args) => { + let goConfig = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null); + let isBenchmark = false; + testCurrentPackage(goConfig, isBenchmark, args); + })); + + ctx.subscriptions.push(vscode.commands.registerCommand('go.benchmark.package', (args) => { + let goConfig = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null); + let isBenchmark = true; + testCurrentPackage(goConfig, isBenchmark, args); + })); + + ctx.subscriptions.push(vscode.commands.registerCommand('go.test.file', (args) => { + let goConfig = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null); + let isBenchmark = false; + testCurrentFile(goConfig, isBenchmark, args); + })); + + ctx.subscriptions.push(vscode.commands.registerCommand('go.benchmark.file', (args) => { + let goConfig = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null); + let isBenchmark = true; + testCurrentFile(goConfig, isBenchmark, args); + })); + + ctx.subscriptions.push(vscode.commands.registerCommand('go.test.workspace', (args) => { + let goConfig = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null); + testWorkspace(goConfig, args); + })); + + ctx.subscriptions.push(vscode.commands.registerCommand('go.test.previous', () => { + testPrevious(); + })); + + ctx.subscriptions.push(vscode.commands.registerCommand('go.test.coverage', () => { + toggleCoverageCurrentPackage(); + })); + + ctx.subscriptions.push(vscode.commands.registerCommand('go.test.showOutput', () => { + showTestOutput(); + })); + + ctx.subscriptions.push(vscode.commands.registerCommand('go.test.cancel', () => { + cancelRunningTests(); + })); + + ctx.subscriptions.push(vscode.commands.registerCommand('go.import.add', (arg: string) => { + return addImport(typeof arg === 'string' ? arg : null); + })); + + ctx.subscriptions.push(vscode.commands.registerCommand('go.add.package.workspace', () => { + addImportToWorkspace(); + })); + + ctx.subscriptions.push(vscode.commands.registerCommand('go.tools.install', (args) => { + if (Array.isArray(args) && args.length) { + getGoVersion().then(goVersion => { + installTools(args, goVersion); + }); + return; + } + installAllTools(); + })); - ctx.subscriptions.push( - vscode.commands.registerCommand('go.add.tags', args => { - addTags(args); - }) - ); + ctx.subscriptions.push(vscode.commands.registerCommand('go.browse.packages', () => { + browsePackages(); + })); - ctx.subscriptions.push( - vscode.commands.registerCommand('go.remove.tags', args => { - removeTags(args); - }) - ); + ctx.subscriptions.push(vscode.workspace.onDidChangeConfiguration((e: vscode.ConfigurationChangeEvent) => { + if (!e.affectsConfiguration('go')) { + return; + } + let updatedGoConfig = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null); + sendTelemetryEventForConfig(updatedGoConfig); + updateGoPathGoRootFromConfig(); + + // If there was a change in "useLanguageServer" setting, then ask the user to reload VS Code. + if (didLangServerConfigChange(e) + && (!updatedGoConfig['useLanguageServer'] || checkLanguageServer())) { + vscode.window.showInformationMessage('Reload VS Code window for the change in usage of language server to take effect', 'Reload').then(selected => { + if (selected === 'Reload') { + vscode.commands.executeCommand('workbench.action.reloadWindow'); + } + }); + } + useLangServer = updatedGoConfig['useLanguageServer']; - ctx.subscriptions.push( - vscode.commands.registerCommand('go.fill.struct', () => { - runFillStruct(vscode.window.activeTextEditor); - }) - ); + // If there was a change in "toolsGopath" setting, then clear cache for go tools + if (getToolsGopath() !== getToolsGopath(false)) { + clearCacheForTools(); + } - ctx.subscriptions.push( - vscode.commands.registerCommand('go.impl.cursor', () => { - implCursor(); - }) - ); - ctx.subscriptions.push( - vscode.commands.registerCommand('go.godoctor.extract', () => { - extractFunction(); - }) - ); - ctx.subscriptions.push( - vscode.commands.registerCommand('go.godoctor.var', () => { - extractVariable(); - }) - ); - - ctx.subscriptions.push( - vscode.commands.registerCommand('go.test.cursor', args => { - const goConfig = vscode.workspace.getConfiguration( - 'go', - vscode.window.activeTextEditor - ? vscode.window.activeTextEditor.document.uri - : null - ); - testAtCursor(goConfig, 'test', args); - }) - ); - - ctx.subscriptions.push( - vscode.commands.registerCommand('go.debug.cursor', args => { - const goConfig = vscode.workspace.getConfiguration( - 'go', - vscode.window.activeTextEditor - ? vscode.window.activeTextEditor.document.uri - : null - ); - testAtCursor(goConfig, 'debug', args); - }) - ); - - ctx.subscriptions.push( - vscode.commands.registerCommand('go.benchmark.cursor', args => { - const goConfig = vscode.workspace.getConfiguration( - 'go', - vscode.window.activeTextEditor - ? vscode.window.activeTextEditor.document.uri - : null - ); - testAtCursor(goConfig, 'benchmark', args); - }) - ); - - ctx.subscriptions.push( - vscode.commands.registerCommand('go.test.package', args => { - let goConfig = vscode.workspace.getConfiguration( - 'go', - vscode.window.activeTextEditor - ? vscode.window.activeTextEditor.document.uri - : null - ); - let isBenchmark = false; - testCurrentPackage(goConfig, isBenchmark, args); - }) - ); - - ctx.subscriptions.push( - vscode.commands.registerCommand('go.benchmark.package', args => { - let goConfig = vscode.workspace.getConfiguration( - 'go', - vscode.window.activeTextEditor - ? vscode.window.activeTextEditor.document.uri - : null - ); - let isBenchmark = true; - testCurrentPackage(goConfig, isBenchmark, args); - }) - ); - - ctx.subscriptions.push( - vscode.commands.registerCommand('go.test.file', args => { - let goConfig = vscode.workspace.getConfiguration( - 'go', - vscode.window.activeTextEditor - ? vscode.window.activeTextEditor.document.uri - : null - ); - let isBenchmark = false; - testCurrentFile(goConfig, isBenchmark, args); - }) - ); - - ctx.subscriptions.push( - vscode.commands.registerCommand('go.benchmark.file', args => { - let goConfig = vscode.workspace.getConfiguration( - 'go', - vscode.window.activeTextEditor - ? vscode.window.activeTextEditor.document.uri - : null - ); - let isBenchmark = true; - testCurrentFile(goConfig, isBenchmark, args); - }) - ); - - ctx.subscriptions.push( - vscode.commands.registerCommand('go.test.workspace', args => { - let goConfig = vscode.workspace.getConfiguration( - 'go', - vscode.window.activeTextEditor - ? vscode.window.activeTextEditor.document.uri - : null - ); - testWorkspace(goConfig, args); - }) - ); + if (updatedGoConfig['enableCodeLens']) { + testCodeLensProvider.setEnabled(updatedGoConfig['enableCodeLens']['runtest']); + referencesCodeLensProvider.setEnabled(updatedGoConfig['enableCodeLens']['references']); + } - ctx.subscriptions.push( - vscode.commands.registerCommand('go.test.previous', () => { - testPrevious(); - }) - ); + if (e.affectsConfiguration('go.formatTool')) { + checkToolExists(updatedGoConfig['formatTool']); + } + if (e.affectsConfiguration('go.lintTool')) { + checkToolExists(updatedGoConfig['lintTool']); + } + if (e.affectsConfiguration('go.docsTool')) { + checkToolExists(updatedGoConfig['docsTool']); + } + if (e.affectsConfiguration('go.coverageDecorator')) { + updateCodeCoverageDecorators(updatedGoConfig['coverageDecorator']); + } + })); - ctx.subscriptions.push( - vscode.commands.registerCommand('go.test.coverage', () => { - toggleCoverageCurrentPackage(); - }) - ); + ctx.subscriptions.push(vscode.commands.registerCommand('go.test.generate.package', () => { + goGenerateTests.generateTestCurrentPackage(); + })); - ctx.subscriptions.push( - vscode.commands.registerCommand('go.test.showOutput', () => { - showTestOutput(); - }) - ); + ctx.subscriptions.push(vscode.commands.registerCommand('go.test.generate.file', () => { + goGenerateTests.generateTestCurrentFile(); + })); - ctx.subscriptions.push( - vscode.commands.registerCommand('go.test.cancel', () => { - cancelRunningTests(); - }) - ); + ctx.subscriptions.push(vscode.commands.registerCommand('go.test.generate.function', () => { + goGenerateTests.generateTestCurrentFunction(); + })); - ctx.subscriptions.push( - vscode.commands.registerCommand('go.import.add', (arg: string) => { - return addImport(typeof arg === 'string' ? arg : null); - }) - ); + ctx.subscriptions.push(vscode.commands.registerCommand('go.toggle.test.file', () => { + goGenerateTests.toggleTestFile(); + })); - ctx.subscriptions.push( - vscode.commands.registerCommand('go.add.package.workspace', () => { - addImportToWorkspace(); - }) - ); - - ctx.subscriptions.push( - vscode.commands.registerCommand('go.tools.install', args => { - if (Array.isArray(args) && args.length) { - getGoVersion().then(goVersion => { - installTools(args, goVersion); - }); - return; + ctx.subscriptions.push(vscode.commands.registerCommand('go.debug.startSession', config => { + let workspaceFolder; + if (vscode.window.activeTextEditor) { + workspaceFolder = vscode.workspace.getWorkspaceFolder(vscode.window.activeTextEditor.document.uri); + } + + return vscode.debug.startDebugging(workspaceFolder, config); + })); + + ctx.subscriptions.push(vscode.commands.registerCommand('go.show.commands', () => { + let extCommands = getExtensionCommands(); + extCommands.push({ + command: 'editor.action.goToDeclaration', + title: 'Go to Definition' + }); + extCommands.push({ + command: 'editor.action.goToImplementation', + title: 'Go to Implementation' + }); + extCommands.push({ + command: 'workbench.action.gotoSymbol', + title: 'Go to Symbol in File...' + }); + extCommands.push({ + command: 'workbench.action.showAllSymbols', + title: 'Go to Symbol in Workspace...' + }); + vscode.window.showQuickPick(extCommands.map(x => x.title)).then(cmd => { + let selectedCmd = extCommands.find(x => x.title === cmd); + if (selectedCmd) { + vscode.commands.executeCommand(selectedCmd.command); } - installAllTools(); - }) - ); + }); + })); - ctx.subscriptions.push( - vscode.commands.registerCommand('go.browse.packages', () => { - browsePackages(); - }) - ); + ctx.subscriptions.push(vscode.commands.registerCommand('go.get.package', goGetPackage)); - ctx.subscriptions.push( - vscode.workspace.onDidChangeConfiguration( - (e: vscode.ConfigurationChangeEvent) => { - if (!e.affectsConfiguration('go')) { - return; - } - let updatedGoConfig = vscode.workspace.getConfiguration( - 'go', - vscode.window.activeTextEditor - ? vscode.window.activeTextEditor.document.uri - : null - ); - sendTelemetryEventForConfig(updatedGoConfig); - updateGoPathGoRootFromConfig(); - - // If there was a change in "useLanguageServer" setting, then ask the user to reload VS Code. - if ( - didLangServerConfigChange(e) && - (!updatedGoConfig['useLanguageServer'] || - checkLanguageServer()) - ) { - vscode.window - .showInformationMessage( - 'Reload VS Code window for the change in usage of language server to take effect', - 'Reload' - ) - .then(selected => { - if (selected === 'Reload') { - vscode.commands.executeCommand( - 'workbench.action.reloadWindow' - ); - } - }); - } - useLangServer = updatedGoConfig['useLanguageServer']; + ctx.subscriptions.push(vscode.commands.registerCommand('go.playground', playgroundCommand)); - // If there was a change in "toolsGopath" setting, then clear cache for go tools - if (getToolsGopath() !== getToolsGopath(false)) { - clearCacheForTools(); - } + ctx.subscriptions.push(vscode.commands.registerCommand('go.lint.package', () => lintCode('package'))); - if (updatedGoConfig['enableCodeLens']) { - testCodeLensProvider.setEnabled( - updatedGoConfig['enableCodeLens']['runtest'] - ); - referencesCodeLensProvider.setEnabled( - updatedGoConfig['enableCodeLens']['references'] - ); - } + ctx.subscriptions.push(vscode.commands.registerCommand('go.lint.workspace', () => lintCode('workspace'))); - if (e.affectsConfiguration('go.formatTool')) { - checkToolExists(updatedGoConfig['formatTool']); - } - if (e.affectsConfiguration('go.lintTool')) { - checkToolExists(updatedGoConfig['lintTool']); - } - if (e.affectsConfiguration('go.docsTool')) { - checkToolExists(updatedGoConfig['docsTool']); - } - if (e.affectsConfiguration('go.coverageDecorator')) { - updateCodeCoverageDecorators( - updatedGoConfig['coverageDecorator'] - ); - } - } - ) - ); + ctx.subscriptions.push(vscode.commands.registerCommand('go.lint.file', () => lintCode('file'))); - ctx.subscriptions.push( - vscode.commands.registerCommand('go.test.generate.package', () => { - goGenerateTests.generateTestCurrentPackage(); - }) - ); + ctx.subscriptions.push(vscode.commands.registerCommand('go.vet.package', vetCode)); - ctx.subscriptions.push( - vscode.commands.registerCommand('go.test.generate.file', () => { - goGenerateTests.generateTestCurrentFile(); - }) - ); + ctx.subscriptions.push(vscode.commands.registerCommand('go.vet.workspace', () => vetCode(true))); - ctx.subscriptions.push( - vscode.commands.registerCommand('go.test.generate.function', () => { - goGenerateTests.generateTestCurrentFunction(); - }) - ); + ctx.subscriptions.push(vscode.commands.registerCommand('go.build.package', buildCode)); - ctx.subscriptions.push( - vscode.commands.registerCommand('go.toggle.test.file', () => { - goGenerateTests.toggleTestFile(); - }) - ); - - ctx.subscriptions.push( - vscode.commands.registerCommand('go.debug.startSession', config => { - let workspaceFolder; - if (vscode.window.activeTextEditor) { - workspaceFolder = vscode.workspace.getWorkspaceFolder( - vscode.window.activeTextEditor.document.uri - ); - } + ctx.subscriptions.push(vscode.commands.registerCommand('go.build.workspace', () => buildCode(true))); - return vscode.debug.startDebugging(workspaceFolder, config); - }) - ); - - ctx.subscriptions.push( - vscode.commands.registerCommand('go.show.commands', () => { - let extCommands = getExtensionCommands(); - extCommands.push({ - command: 'editor.action.goToDeclaration', - title: 'Go to Definition' - }); - extCommands.push({ - command: 'editor.action.goToImplementation', - title: 'Go to Implementation' - }); - extCommands.push({ - command: 'workbench.action.gotoSymbol', - title: 'Go to Symbol in File...' - }); - extCommands.push({ - command: 'workbench.action.showAllSymbols', - title: 'Go to Symbol in Workspace...' - }); - vscode.window - .showQuickPick(extCommands.map(x => x.title)) - .then(cmd => { - let selectedCmd = extCommands.find(x => x.title === cmd); - if (selectedCmd) { - vscode.commands.executeCommand(selectedCmd.command); - } - }); - }) - ); - - ctx.subscriptions.push( - vscode.commands.registerCommand('go.get.package', goGetPackage) - ); - - ctx.subscriptions.push( - vscode.commands.registerCommand('go.playground', playgroundCommand) - ); - - ctx.subscriptions.push( - vscode.commands.registerCommand('go.lint.package', () => - lintCode('package') - ) - ); - - ctx.subscriptions.push( - vscode.commands.registerCommand('go.lint.workspace', () => - lintCode('workspace') - ) - ); - - ctx.subscriptions.push( - vscode.commands.registerCommand('go.lint.file', () => lintCode('file')) - ); - - ctx.subscriptions.push( - vscode.commands.registerCommand('go.vet.package', vetCode) - ); - - ctx.subscriptions.push( - vscode.commands.registerCommand('go.vet.workspace', () => vetCode(true)) - ); - - ctx.subscriptions.push( - vscode.commands.registerCommand('go.build.package', buildCode) - ); - - ctx.subscriptions.push( - vscode.commands.registerCommand('go.build.workspace', () => - buildCode(true) - ) - ); - - ctx.subscriptions.push( - vscode.commands.registerCommand( - 'go.install.package', - installCurrentPackage - ) - ); + ctx.subscriptions.push(vscode.commands.registerCommand('go.install.package', installCurrentPackage)); vscode.languages.setLanguageConfiguration(GO_MODE.language, { - wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\@\#\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g + wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\@\#\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g, }); - sendTelemetryEventForConfig( - vscode.workspace.getConfiguration( - 'go', - vscode.window.activeTextEditor - ? vscode.window.activeTextEditor.document.uri - : null - ) - ); + sendTelemetryEventForConfig(vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null)); } export function deactivate() { - return Promise.all([ - disposeTelemetryReporter(), - cancelRunningTests(), - Promise.resolve(cleanupTempDir()) - ]); + return Promise.all([disposeTelemetryReporter(), cancelRunningTests(), Promise.resolve(cleanupTempDir())]); } -function runBuilds( - document: vscode.TextDocument, - goConfig: vscode.WorkspaceConfiguration -) { +function runBuilds(document: vscode.TextDocument, goConfig: vscode.WorkspaceConfiguration) { if (document.languageId !== 'go') { return; } @@ -1101,11 +555,7 @@ function runBuilds( check(document.uri, goConfig) .then(results => { results.forEach(result => { - handleDiagnosticErrors( - document, - result.errors, - result.diagnosticCollection - ); + handleDiagnosticErrors(document, result.errors, result.diagnosticCollection); }); }) .catch(err => { @@ -1114,25 +564,14 @@ function runBuilds( } function startBuildOnSaveWatcher(subscriptions: vscode.Disposable[]) { - vscode.workspace.onDidSaveTextDocument( - document => { - if (document.languageId !== 'go') { - return; - } - if ( - vscode.window.visibleTextEditors.some( - e => e.document.fileName === document.fileName - ) - ) { - runBuilds( - document, - vscode.workspace.getConfiguration('go', document.uri) - ); - } - }, - null, - subscriptions - ); + vscode.workspace.onDidSaveTextDocument(document => { + if (document.languageId !== 'go') { + return; + } + if (vscode.window.visibleTextEditors.some(e => e.document.fileName === document.fileName)) { + runBuilds(document, vscode.workspace.getConfiguration('go', document.uri)); + } + }, null, subscriptions); } function sendTelemetryEventForConfig(goConfig: vscode.WorkspaceConfiguration) { @@ -1200,39 +639,24 @@ function sendTelemetryEventForConfig(goConfig: vscode.WorkspaceConfiguration) { toolsGopath: goConfig['toolsGopath'] ? 'set' : '', gocodeAutoBuild: goConfig['gocodeAutoBuild'] + '', gocodePackageLookupMode: goConfig['gocodePackageLookupMode'] + '', - useCodeSnippetsOnFunctionSuggest: - goConfig['useCodeSnippetsOnFunctionSuggest'] + '', - useCodeSnippetsOnFunctionSuggestWithoutType: - goConfig['useCodeSnippetsOnFunctionSuggestWithoutType'] + '', - autocompleteUnimportedPackages: - goConfig['autocompleteUnimportedPackages'] + '', + useCodeSnippetsOnFunctionSuggest: goConfig['useCodeSnippetsOnFunctionSuggest'] + '', + useCodeSnippetsOnFunctionSuggestWithoutType: goConfig['useCodeSnippetsOnFunctionSuggestWithoutType'] + '', + autocompleteUnimportedPackages: goConfig['autocompleteUnimportedPackages'] + '', docsTool: goConfig['docsTool'], useLanguageServer: goConfig['useLanguageServer'] + '', - languageServerExperimentalFeatures: JSON.stringify( - goConfig['languageServerExperimentalFeatures'] - ), - includeImports: - goConfig['gotoSymbol'] && - goConfig['gotoSymbol']['includeImports'] + '', + languageServerExperimentalFeatures: JSON.stringify(goConfig['languageServerExperimentalFeatures']), + includeImports: goConfig['gotoSymbol'] && goConfig['gotoSymbol']['includeImports'] + '', addTags: JSON.stringify(goConfig['addTags']), removeTags: JSON.stringify(goConfig['removeTags']), - editorContextMenuCommands: JSON.stringify( - goConfig['editorContextMenuCommands'] - ), + editorContextMenuCommands: JSON.stringify(goConfig['editorContextMenuCommands']), liveErrors: JSON.stringify(goConfig['liveErrors']), codeLens: JSON.stringify(goConfig['enableCodeLens']), alternateTools: JSON.stringify(goConfig['alternateTools']) }); } -function didLangServerConfigChange( - e: vscode.ConfigurationChangeEvent -): boolean { - return ( - e.affectsConfiguration('go.useLanguageServer') || - e.affectsConfiguration('go.languageServerFlags') || - e.affectsConfiguration('go.languageServerExperimentalFeatures') - ); +function didLangServerConfigChange(e: vscode.ConfigurationChangeEvent): boolean { + return e.affectsConfiguration('go.useLanguageServer') || e.affectsConfiguration('go.languageServerFlags') || e.affectsConfiguration('go.languageServerExperimentalFeatures'); } function checkToolExists(tool: string) { @@ -1244,12 +668,5 @@ function checkToolExists(tool: string) { function registerCompletionProvider(ctx: vscode.ExtensionContext) { let provider = new GoCompletionItemProvider(ctx.globalState); ctx.subscriptions.push(provider); - ctx.subscriptions.push( - vscode.languages.registerCompletionItemProvider( - GO_MODE, - provider, - '.', - '"' - ) - ); + ctx.subscriptions.push(vscode.languages.registerCompletionItemProvider(GO_MODE, provider, '.', '\"')); } From 9b3ad1b162496462dcf66c70ccb60114b7e64fd5 Mon Sep 17 00:00:00 2001 From: Ramya Achutha Rao Date: Sat, 2 Mar 2019 15:13:03 -0800 Subject: [PATCH 09/13] Fix merge conflicts with minimal changes --- src/goMain.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/goMain.ts b/src/goMain.ts index 57b67935d..9ce976319 100644 --- a/src/goMain.ts +++ b/src/goMain.ts @@ -54,12 +54,9 @@ import { vetCode } from './goVet'; import { buildCode } from './goBuild'; import { installCurrentPackage } from './goInstall'; import { setGlobalState } from './stateUtils'; -<<<<<<< HEAD import { ProvideTypeDefinitionSignature } from 'vscode-languageclient/lib/typeDefinition'; import { ProvideImplementationSignature } from 'vscode-languageclient/lib/implementation'; -======= import { GoRefactorProvider } from './goRefactor'; ->>>>>>> Add godoctor extract function command and code action export let buildDiagnosticCollection: vscode.DiagnosticCollection; export let lintDiagnosticCollection: vscode.DiagnosticCollection; From bbb70479ff748ad10c57afadbe8b447369826547 Mon Sep 17 00:00:00 2001 From: Ramya Achutha Rao Date: Sat, 2 Mar 2019 15:41:27 -0800 Subject: [PATCH 10/13] promptForMissingTool doesnt work --- src/goInstallTools.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/goInstallTools.ts b/src/goInstallTools.ts index acde7ddd5..5c405e3b0 100644 --- a/src/goInstallTools.ts +++ b/src/goInstallTools.ts @@ -152,7 +152,8 @@ function getTools(goVersion: SemVersion): string[] { 'gomodifytags', 'impl', 'fillstruct', - 'goplay' + 'goplay', + 'godoctor' ); return tools; From 2b987d3be967c03e93d4b72afb9f04d5306034ef Mon Sep 17 00:00:00 2001 From: Ramya Achutha Rao Date: Sat, 2 Mar 2019 15:41:33 -0800 Subject: [PATCH 11/13] Refactoring --- src/goDoctor.ts | 115 ++++++++++++++++++------------------------------ 1 file changed, 42 insertions(+), 73 deletions(-) diff --git a/src/goDoctor.ts b/src/goDoctor.ts index 64bcf962c..a38556330 100644 --- a/src/goDoctor.ts +++ b/src/goDoctor.ts @@ -9,41 +9,13 @@ import vscode = require('vscode'); import cp = require('child_process'); import { getBinPath, getToolsEnvVars } from './util'; import { promptForMissingTool } from './goInstallTools'; -import { dirname } from 'path'; -import { resolve } from 'dns'; +import { dirname, isAbsolute } from 'path'; /** * Extracts function out of current selection and replaces the current selection with a call to the extracted function. */ export function extractFunction() { - let activeEditor = vscode.window.activeTextEditor; - if (!activeEditor) { - vscode.window.showInformationMessage('No editor is active.'); - return; - } - if (activeEditor.selections.length !== 1) { - vscode.window.showInformationMessage( - 'You need to have a single selection for extracting method' - ); - return; - } - let showInputBoxPromise = vscode.window.showInputBox({ - placeHolder: 'Please enter a name for the extracted function.' - }); - showInputBoxPromise.then((functionName: string) => { - if (typeof functionName === 'string') { - runGoDoctor( - functionName, - activeEditor.selection, - activeEditor.document.fileName, - 'extract' - ).then(errorMessage => { - if (errorMessage) { - vscode.window.showErrorMessage(errorMessage); - } - }); - } - }); + extract('extract'); } /** @@ -51,6 +23,12 @@ export function extractFunction() { * replaces the current selection with the new var. */ export function extractVariable() { + extract('var'); +} + +type typeOfExtraction = 'var' | 'extract'; + +async function extract(type: typeOfExtraction): Promise { let activeEditor = vscode.window.activeTextEditor; if (!activeEditor) { vscode.window.showInformationMessage('No editor is active.'); @@ -58,30 +36,26 @@ export function extractVariable() { } if (activeEditor.selections.length !== 1) { vscode.window.showInformationMessage( - 'You need to have a single selection for extracting variable' + `You need to have a single selection for extracting ${type === 'var' ? 'variable' : 'method'}` ); return; } - let showInputBoxPromise = vscode.window.showInputBox({ - placeHolder: 'Plese enter a name for the extracted variable.' - }); - showInputBoxPromise.then((varName: string) => { - if (typeof varName === 'string') { - runGoDoctor( - varName, - activeEditor.selection, - activeEditor.document.fileName, - 'var' - ).then(errorMessage => { - if (errorMessage) { - vscode.window.showErrorMessage(errorMessage); - } - }); - } + + const newName = await vscode.window.showInputBox({ + placeHolder: 'Please enter a name for the extracted variable.' }); -} -type typeOfExtraction = 'var' | 'extract'; + if (!newName) { + return; + } + + runGoDoctor( + newName, + activeEditor.selection, + activeEditor.document.fileName, + type + ); +} /** * @param newName name for the extracted method @@ -94,41 +68,36 @@ function runGoDoctor( selection: vscode.Selection, fileName: string, type: typeOfExtraction -): Thenable { - let godoctor = getBinPath('godoctor'); +): Thenable { + const godoctor = getBinPath('godoctor'); return new Promise((resolve, reject) => { - console.log(selection); - let args = [ - '-w', - '-pos', - `${selection.start.line + 1},${selection.start.character + - 1}:${selection.end.line + 1},${selection.end.character}`, - '-file', - fileName, - type, - newName - ]; - console.log(args); - let p = cp.execFile( + if (!isAbsolute(godoctor)) { + promptForMissingTool('godoctor'); + return resolve(); + } + + cp.execFile( godoctor, - args, + [ + '-w', + '-pos', + `${selection.start.line + 1},${selection.start.character + + 1}:${selection.end.line + 1},${selection.end.character}`, + '-file', + fileName, + type, + newName + ], { env: getToolsEnvVars(), cwd: dirname(fileName) }, (err, stdout, stderr) => { - if (err && (err).code === 'ENOENT') { - promptForMissingTool('godoctor'); - return resolve('Could not find godoctor'); - } if (err) { - return resolve(stderr); + vscode.window.showErrorMessage(stderr || err.message); } } ); - if (p.pid) { - p.stdin.end(); - } }); } From 7edc8bf6d8e8fd142c9aa159774310e8d365d067 Mon Sep 17 00:00:00 2001 From: Ramya Achutha Rao Date: Sat, 2 Mar 2019 16:00:50 -0800 Subject: [PATCH 12/13] Use diffs --- src/goDoctor.ts | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/goDoctor.ts b/src/goDoctor.ts index a38556330..306814c25 100644 --- a/src/goDoctor.ts +++ b/src/goDoctor.ts @@ -10,6 +10,7 @@ import cp = require('child_process'); import { getBinPath, getToolsEnvVars } from './util'; import { promptForMissingTool } from './goInstallTools'; import { dirname, isAbsolute } from 'path'; +import { getEditsFromUnifiedDiffStr, Edit } from './diffUtils'; /** * Extracts function out of current selection and replaces the current selection with a call to the extracted function. @@ -54,21 +55,32 @@ async function extract(type: typeOfExtraction): Promise { activeEditor.selection, activeEditor.document.fileName, type - ); + ).then(diffs => { + const filePatches = getEditsFromUnifiedDiffStr(diffs); + if (filePatches.length !== 1) { + return; + } + const patchForCurrentEditor = filePatches[0]; + activeEditor.edit(editBuilder => { + patchForCurrentEditor.edits.forEach((edit: Edit) => { + edit.applyUsingTextEditorEdit(editBuilder); + }); + }); + }); } /** * @param newName name for the extracted method * @param selection the editor selection from which method is to be extracted * @param activeEditor the editor that will be used to apply the changes from godoctor - * @returns errorMessage in case the method fails, null otherwise + * @returns Diff string in unified format. http://www.gnu.org/software/diffutils/manual/diffutils.html#Unified-Format */ function runGoDoctor( newName: string, selection: vscode.Selection, fileName: string, type: typeOfExtraction -): Thenable { +): Thenable { const godoctor = getBinPath('godoctor'); return new Promise((resolve, reject) => { @@ -96,7 +108,9 @@ function runGoDoctor( (err, stdout, stderr) => { if (err) { vscode.window.showErrorMessage(stderr || err.message); + return reject(); } + resolve(stdout); } ); }); From 9334542a20cc84c77bdf2907397afd4bdab89a36 Mon Sep 17 00:00:00 2001 From: Ramya Achutha Rao Date: Sat, 2 Mar 2019 19:55:46 -0800 Subject: [PATCH 13/13] Revert "Use diffs" This reverts commit 7edc8bf6d8e8fd142c9aa159774310e8d365d067. --- src/goDoctor.ts | 20 +++----------------- 1 file changed, 3 insertions(+), 17 deletions(-) diff --git a/src/goDoctor.ts b/src/goDoctor.ts index 306814c25..a38556330 100644 --- a/src/goDoctor.ts +++ b/src/goDoctor.ts @@ -10,7 +10,6 @@ import cp = require('child_process'); import { getBinPath, getToolsEnvVars } from './util'; import { promptForMissingTool } from './goInstallTools'; import { dirname, isAbsolute } from 'path'; -import { getEditsFromUnifiedDiffStr, Edit } from './diffUtils'; /** * Extracts function out of current selection and replaces the current selection with a call to the extracted function. @@ -55,32 +54,21 @@ async function extract(type: typeOfExtraction): Promise { activeEditor.selection, activeEditor.document.fileName, type - ).then(diffs => { - const filePatches = getEditsFromUnifiedDiffStr(diffs); - if (filePatches.length !== 1) { - return; - } - const patchForCurrentEditor = filePatches[0]; - activeEditor.edit(editBuilder => { - patchForCurrentEditor.edits.forEach((edit: Edit) => { - edit.applyUsingTextEditorEdit(editBuilder); - }); - }); - }); + ); } /** * @param newName name for the extracted method * @param selection the editor selection from which method is to be extracted * @param activeEditor the editor that will be used to apply the changes from godoctor - * @returns Diff string in unified format. http://www.gnu.org/software/diffutils/manual/diffutils.html#Unified-Format + * @returns errorMessage in case the method fails, null otherwise */ function runGoDoctor( newName: string, selection: vscode.Selection, fileName: string, type: typeOfExtraction -): Thenable { +): Thenable { const godoctor = getBinPath('godoctor'); return new Promise((resolve, reject) => { @@ -108,9 +96,7 @@ function runGoDoctor( (err, stdout, stderr) => { if (err) { vscode.window.showErrorMessage(stderr || err.message); - return reject(); } - resolve(stdout); } ); });