diff --git a/.prettierrc.json b/.prettierrc.json index 410bca4897..18704c7718 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -2,5 +2,6 @@ "printWidth": 120, "singleQuote": true, "arrowParens": "always", - "quoteProps": "consistent" + "quoteProps": "consistent", + "trailingComma": "none" } \ No newline at end of file diff --git a/src/debugAdapter/goDebug.ts b/src/debugAdapter/goDebug.ts index cd90b290fe..d143d3c6fb 100644 --- a/src/debugAdapter/goDebug.ts +++ b/src/debugAdapter/goDebug.ts @@ -24,7 +24,7 @@ import { StackFrame, StoppedEvent, TerminatedEvent, - Thread, + Thread } from 'vscode-debugadapter'; import { DebugProtocol } from 'vscode-debugprotocol'; import { @@ -1399,16 +1399,9 @@ class GoDebugSession extends LoggingDebugSession { } if (i) { - localPath = - llist - .reverse() - .slice(0, -i) - .join(this.localPathSeparator) + this.localPathSeparator; + localPath = llist.reverse().slice(0, -i).join(this.localPathSeparator) + this.localPathSeparator; args.remotePath = - rlist - .reverse() - .slice(0, -i) - .join(this.remotePathSeparator) + this.remotePathSeparator; + rlist.reverse().slice(0, -i).join(this.remotePathSeparator) + this.remotePathSeparator; } else if ( args.remotePath.length > 1 && (args.remotePath.endsWith('\\') || args.remotePath.endsWith('/')) @@ -1720,7 +1713,7 @@ class GoDebugSession extends LoggingDebugSession { // TODO(polina): validate the assumption in this code that the first goroutine // is the current one. So far it appears to me that this is always the main goroutine // with id 1. - this.delve.call('ListGoroutines', [{count: 1}], (err, out) => { + this.delve.call('ListGoroutines', [{ count: 1 }], (err, out) => { if (err) { this.logDelveError(err, 'Failed to get threads'); } diff --git a/src/goBaseCodelens.ts b/src/goBaseCodelens.ts index 6f4f442b4f..1282fd6632 100644 --- a/src/goBaseCodelens.ts +++ b/src/goBaseCodelens.ts @@ -1,29 +1,29 @@ -/*--------------------------------------------------------- - * Copyright (C) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------*/ - -import vscode = require('vscode'); - -export abstract class GoBaseCodeLensProvider implements vscode.CodeLensProvider { - protected enabled: boolean = true; - private onDidChangeCodeLensesEmitter = new vscode.EventEmitter(); - - public get onDidChangeCodeLenses(): vscode.Event { - return this.onDidChangeCodeLensesEmitter.event; - } - - public setEnabled(enabled: false): void { - if (this.enabled !== enabled) { - this.enabled = enabled; - this.onDidChangeCodeLensesEmitter.fire(); - } - } - - public provideCodeLenses( - document: vscode.TextDocument, - token: vscode.CancellationToken - ): vscode.ProviderResult { - return []; - } -} +/*--------------------------------------------------------- + * Copyright (C) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------*/ + +import vscode = require('vscode'); + +export abstract class GoBaseCodeLensProvider implements vscode.CodeLensProvider { + protected enabled: boolean = true; + private onDidChangeCodeLensesEmitter = new vscode.EventEmitter(); + + public get onDidChangeCodeLenses(): vscode.Event { + return this.onDidChangeCodeLensesEmitter.event; + } + + public setEnabled(enabled: false): void { + if (this.enabled !== enabled) { + this.enabled = enabled; + this.onDidChangeCodeLensesEmitter.fire(); + } + } + + public provideCodeLenses( + document: vscode.TextDocument, + token: vscode.CancellationToken + ): vscode.ProviderResult { + return []; + } +} diff --git a/src/goBuild.ts b/src/goBuild.ts index db5c3874f0..836d53b0cf 100644 --- a/src/goBuild.ts +++ b/src/goBuild.ts @@ -1,177 +1,177 @@ -/*--------------------------------------------------------- - * Copyright (C) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------*/ - -import path = require('path'); -import vscode = require('vscode'); -import { buildDiagnosticCollection } from './goMain'; -import { isModSupported } from './goModules'; -import { getNonVendorPackages } from './goPackages'; -import { getCurrentGoWorkspaceFromGOPATH } from './goPath'; -import { diagnosticsStatusBarItem, outputChannel } from './goStatus'; -import { getTestFlags } from './testUtils'; -import { - getCurrentGoPath, - getGoConfig, - getModuleCache, - getTempFilePath, - getToolsEnvVars, - getWorkspaceFolderPath, - handleDiagnosticErrors, - ICheckResult, - runTool -} from './util'; -/** - * Builds current package or workspace. - */ -export function buildCode(buildWorkspace?: boolean) { - const editor = vscode.window.activeTextEditor; - if (!buildWorkspace) { - if (!editor) { - vscode.window.showInformationMessage('No editor is active, cannot find current package to build'); - return; - } - if (editor.document.languageId !== 'go') { - vscode.window.showInformationMessage( - 'File in the active editor is not a Go file, cannot find current package to build' - ); - return; - } - } - - const documentUri = editor ? editor.document.uri : null; - const goConfig = getGoConfig(documentUri); - - outputChannel.clear(); // Ensures stale output from build on save is cleared - diagnosticsStatusBarItem.show(); - diagnosticsStatusBarItem.text = 'Building...'; - - isModSupported(documentUri).then((isMod) => { - goBuild(documentUri, isMod, goConfig, buildWorkspace) - .then((errors) => { - handleDiagnosticErrors(editor ? editor.document : null, errors, buildDiagnosticCollection); - diagnosticsStatusBarItem.hide(); - }) - .catch((err) => { - vscode.window.showInformationMessage('Error: ' + err); - diagnosticsStatusBarItem.text = 'Build Failed'; - }); - }); -} - -/** - * Runs go build -i or go test -i and presents the output in the 'Go' channel and in the diagnostic collections. - * - * @param fileUri Document uri. - * @param isMod Boolean denoting if modules are being used. - * @param goConfig Configuration for the Go extension. - * @param buildWorkspace If true builds code in all workspace. - */ -export async function goBuild( - fileUri: vscode.Uri, - isMod: boolean, - goConfig: vscode.WorkspaceConfiguration, - buildWorkspace?: boolean -): Promise { - epoch++; - const closureEpoch = epoch; - if (tokenSource) { - if (running) { - tokenSource.cancel(); - } - tokenSource.dispose(); - } - tokenSource = new vscode.CancellationTokenSource(); - const updateRunning = () => { - if (closureEpoch === epoch) { - running = false; - } - }; - - const currentWorkspace = getWorkspaceFolderPath(fileUri); - const cwd = buildWorkspace && currentWorkspace ? currentWorkspace : path.dirname(fileUri.fsPath); - if (!path.isAbsolute(cwd)) { - return Promise.resolve([]); - } - - // Skip building if cwd is in the module cache - if (isMod && cwd.startsWith(getModuleCache())) { - return []; - } - - const buildEnv = Object.assign({}, getToolsEnvVars()); - const tmpPath = getTempFilePath('go-code-check'); - const isTestFile = fileUri && fileUri.fsPath.endsWith('_test.go'); - const buildFlags: string[] = isTestFile - ? getTestFlags(goConfig) - : Array.isArray(goConfig['buildFlags']) - ? [...goConfig['buildFlags']] - : []; - const buildArgs: string[] = isTestFile ? ['test', '-c'] : ['build']; - - if (goConfig['installDependenciesWhenBuilding'] === true && !isMod) { - buildArgs.push('-i'); - // Remove the -i flag from user as we add it anyway - if (buildFlags.indexOf('-i') > -1) { - buildFlags.splice(buildFlags.indexOf('-i'), 1); - } - } - buildArgs.push(...buildFlags); - if (goConfig['buildTags'] && buildFlags.indexOf('-tags') === -1) { - buildArgs.push('-tags'); - buildArgs.push(goConfig['buildTags']); - } - - if (buildWorkspace && currentWorkspace && !isTestFile) { - outputChannel.appendLine(`Starting building the current workspace at ${currentWorkspace}`); - return getNonVendorPackages(currentWorkspace).then((pkgs) => { - running = true; - return runTool( - buildArgs.concat(Array.from(pkgs.keys())), - currentWorkspace, - 'error', - true, - null, - buildEnv, - true, - tokenSource.token - ).then((v) => { - updateRunning(); - return v; - }); - }); - } - - outputChannel.appendLine(`Starting building the current package at ${cwd}`); - - // Find the right importPath instead of directly using `.`. Fixes https://github.com/Microsoft/vscode-go/issues/846 - const currentGoWorkspace = getCurrentGoWorkspaceFromGOPATH(getCurrentGoPath(), cwd); - let importPath = '.'; - if (currentGoWorkspace && !isMod) { - importPath = cwd.substr(currentGoWorkspace.length + 1); - } else { - outputChannel.appendLine( - `Not able to determine import path of current package by using cwd: ${cwd} and Go workspace: ${currentGoWorkspace}` - ); - } - - running = true; - return runTool( - buildArgs.concat('-o', tmpPath, importPath), - cwd, - 'error', - true, - null, - buildEnv, - true, - tokenSource.token - ).then((v) => { - updateRunning(); - return v; - }); -} - -let epoch = 0; -let tokenSource: vscode.CancellationTokenSource; -let running = false; +/*--------------------------------------------------------- + * Copyright (C) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------*/ + +import path = require('path'); +import vscode = require('vscode'); +import { buildDiagnosticCollection } from './goMain'; +import { isModSupported } from './goModules'; +import { getNonVendorPackages } from './goPackages'; +import { getCurrentGoWorkspaceFromGOPATH } from './goPath'; +import { diagnosticsStatusBarItem, outputChannel } from './goStatus'; +import { getTestFlags } from './testUtils'; +import { + getCurrentGoPath, + getGoConfig, + getModuleCache, + getTempFilePath, + getToolsEnvVars, + getWorkspaceFolderPath, + handleDiagnosticErrors, + ICheckResult, + runTool +} from './util'; +/** + * Builds current package or workspace. + */ +export function buildCode(buildWorkspace?: boolean) { + const editor = vscode.window.activeTextEditor; + if (!buildWorkspace) { + if (!editor) { + vscode.window.showInformationMessage('No editor is active, cannot find current package to build'); + return; + } + if (editor.document.languageId !== 'go') { + vscode.window.showInformationMessage( + 'File in the active editor is not a Go file, cannot find current package to build' + ); + return; + } + } + + const documentUri = editor ? editor.document.uri : null; + const goConfig = getGoConfig(documentUri); + + outputChannel.clear(); // Ensures stale output from build on save is cleared + diagnosticsStatusBarItem.show(); + diagnosticsStatusBarItem.text = 'Building...'; + + isModSupported(documentUri).then((isMod) => { + goBuild(documentUri, isMod, goConfig, buildWorkspace) + .then((errors) => { + handleDiagnosticErrors(editor ? editor.document : null, errors, buildDiagnosticCollection); + diagnosticsStatusBarItem.hide(); + }) + .catch((err) => { + vscode.window.showInformationMessage('Error: ' + err); + diagnosticsStatusBarItem.text = 'Build Failed'; + }); + }); +} + +/** + * Runs go build -i or go test -i and presents the output in the 'Go' channel and in the diagnostic collections. + * + * @param fileUri Document uri. + * @param isMod Boolean denoting if modules are being used. + * @param goConfig Configuration for the Go extension. + * @param buildWorkspace If true builds code in all workspace. + */ +export async function goBuild( + fileUri: vscode.Uri, + isMod: boolean, + goConfig: vscode.WorkspaceConfiguration, + buildWorkspace?: boolean +): Promise { + epoch++; + const closureEpoch = epoch; + if (tokenSource) { + if (running) { + tokenSource.cancel(); + } + tokenSource.dispose(); + } + tokenSource = new vscode.CancellationTokenSource(); + const updateRunning = () => { + if (closureEpoch === epoch) { + running = false; + } + }; + + const currentWorkspace = getWorkspaceFolderPath(fileUri); + const cwd = buildWorkspace && currentWorkspace ? currentWorkspace : path.dirname(fileUri.fsPath); + if (!path.isAbsolute(cwd)) { + return Promise.resolve([]); + } + + // Skip building if cwd is in the module cache + if (isMod && cwd.startsWith(getModuleCache())) { + return []; + } + + const buildEnv = Object.assign({}, getToolsEnvVars()); + const tmpPath = getTempFilePath('go-code-check'); + const isTestFile = fileUri && fileUri.fsPath.endsWith('_test.go'); + const buildFlags: string[] = isTestFile + ? getTestFlags(goConfig) + : Array.isArray(goConfig['buildFlags']) + ? [...goConfig['buildFlags']] + : []; + const buildArgs: string[] = isTestFile ? ['test', '-c'] : ['build']; + + if (goConfig['installDependenciesWhenBuilding'] === true && !isMod) { + buildArgs.push('-i'); + // Remove the -i flag from user as we add it anyway + if (buildFlags.indexOf('-i') > -1) { + buildFlags.splice(buildFlags.indexOf('-i'), 1); + } + } + buildArgs.push(...buildFlags); + if (goConfig['buildTags'] && buildFlags.indexOf('-tags') === -1) { + buildArgs.push('-tags'); + buildArgs.push(goConfig['buildTags']); + } + + if (buildWorkspace && currentWorkspace && !isTestFile) { + outputChannel.appendLine(`Starting building the current workspace at ${currentWorkspace}`); + return getNonVendorPackages(currentWorkspace).then((pkgs) => { + running = true; + return runTool( + buildArgs.concat(Array.from(pkgs.keys())), + currentWorkspace, + 'error', + true, + null, + buildEnv, + true, + tokenSource.token + ).then((v) => { + updateRunning(); + return v; + }); + }); + } + + outputChannel.appendLine(`Starting building the current package at ${cwd}`); + + // Find the right importPath instead of directly using `.`. Fixes https://github.com/Microsoft/vscode-go/issues/846 + const currentGoWorkspace = getCurrentGoWorkspaceFromGOPATH(getCurrentGoPath(), cwd); + let importPath = '.'; + if (currentGoWorkspace && !isMod) { + importPath = cwd.substr(currentGoWorkspace.length + 1); + } else { + outputChannel.appendLine( + `Not able to determine import path of current package by using cwd: ${cwd} and Go workspace: ${currentGoWorkspace}` + ); + } + + running = true; + return runTool( + buildArgs.concat('-o', tmpPath, importPath), + cwd, + 'error', + true, + null, + buildEnv, + true, + tokenSource.token + ).then((v) => { + updateRunning(); + return v; + }); +} + +let epoch = 0; +let tokenSource: vscode.CancellationTokenSource; +let running = false; diff --git a/src/goDebugConfiguration.ts b/src/goDebugConfiguration.ts index 7e145e45ea..db1c20f4bc 100644 --- a/src/goDebugConfiguration.ts +++ b/src/goDebugConfiguration.ts @@ -1,146 +1,146 @@ -/*--------------------------------------------------------- - * 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 path = require('path'); -import vscode = require('vscode'); -import { promptForMissingTool } from './goInstallTools'; -import { packagePathToGoModPathMap } from './goModules'; -import { getFromGlobalState, updateGlobalState } from './stateUtils'; -import { sendTelemetryEventForDebugConfiguration } from './telemetry'; -import { getBinPath, getCurrentGoPath, getGoConfig, getToolsEnvVars } from './util'; - -export class GoDebugConfigurationProvider implements vscode.DebugConfigurationProvider { - public provideDebugConfigurations( - folder: vscode.WorkspaceFolder | undefined, - token?: vscode.CancellationToken - ): vscode.DebugConfiguration[] { - return [ - { - name: 'Launch', - type: 'go', - request: 'launch', - mode: 'auto', - program: '${fileDirname}', - env: {}, - args: [] - } - ]; - } - - public resolveDebugConfiguration?( - folder: vscode.WorkspaceFolder | undefined, - debugConfiguration: vscode.DebugConfiguration, - token?: vscode.CancellationToken - ): vscode.DebugConfiguration { - if (debugConfiguration) { - sendTelemetryEventForDebugConfiguration(debugConfiguration); - } - - const activeEditor = vscode.window.activeTextEditor; - if (!debugConfiguration || !debugConfiguration.request) { - // if 'request' is missing interpret this as a missing launch.json - if (!activeEditor || activeEditor.document.languageId !== 'go') { - return; - } - - debugConfiguration = Object.assign(debugConfiguration || {}, { - name: 'Launch', - type: 'go', - request: 'launch', - mode: 'auto', - program: path.dirname(activeEditor.document.fileName) // matches ${fileDirname} - }); - } - - debugConfiguration['packagePathToGoModPathMap'] = packagePathToGoModPathMap; - - const gopath = getCurrentGoPath(folder ? folder.uri : undefined); - if (!debugConfiguration['env']) { - debugConfiguration['env'] = { GOPATH: gopath }; - } else if (!debugConfiguration['env']['GOPATH']) { - debugConfiguration['env']['GOPATH'] = gopath; - } - - const goConfig = getGoConfig(folder && folder.uri); - const goToolsEnvVars = getToolsEnvVars(); - Object.keys(goToolsEnvVars).forEach((key) => { - if (!debugConfiguration['env'].hasOwnProperty(key)) { - debugConfiguration['env'][key] = goToolsEnvVars[key]; - } - }); - - const dlvConfig = goConfig.get('delveConfig'); - let useApiV1 = false; - if (debugConfiguration.hasOwnProperty('useApiV1')) { - useApiV1 = debugConfiguration['useApiV1'] === true; - } else if (dlvConfig.hasOwnProperty('useApiV1')) { - useApiV1 = dlvConfig['useApiV1'] === true; - } - if (useApiV1) { - debugConfiguration['apiVersion'] = 1; - } - if (!debugConfiguration.hasOwnProperty('apiVersion') && dlvConfig.hasOwnProperty('apiVersion')) { - debugConfiguration['apiVersion'] = dlvConfig['apiVersion']; - } - if (!debugConfiguration.hasOwnProperty('dlvLoadConfig') && dlvConfig.hasOwnProperty('dlvLoadConfig')) { - debugConfiguration['dlvLoadConfig'] = dlvConfig['dlvLoadConfig']; - } - if ( - !debugConfiguration.hasOwnProperty('showGlobalVariables') && - dlvConfig.hasOwnProperty('showGlobalVariables') - ) { - debugConfiguration['showGlobalVariables'] = dlvConfig['showGlobalVariables']; - } - if (debugConfiguration.request === 'attach' && !debugConfiguration['cwd']) { - debugConfiguration['cwd'] = '${workspaceFolder}'; - } - - debugConfiguration['dlvToolPath'] = getBinPath('dlv'); - if (!path.isAbsolute(debugConfiguration['dlvToolPath'])) { - promptForMissingTool('dlv'); - return; - } - - if (debugConfiguration['mode'] === 'auto') { - debugConfiguration['mode'] = - activeEditor && activeEditor.document.fileName.endsWith('_test.go') ? 'test' : 'debug'; - } - - if (debugConfiguration.request === 'launch' && debugConfiguration['mode'] === 'remote') { - this.showWarning( - 'ignoreDebugLaunchRemoteWarning', - `Request type of 'launch' with mode 'remote' is deprecated, please use request type 'attach' with mode 'remote' instead.` - ); - } - - if ( - debugConfiguration.request === 'attach' && - debugConfiguration['mode'] === 'remote' && - debugConfiguration['program'] - ) { - this.showWarning( - 'ignoreUsingRemotePathAndProgramWarning', - `Request type of 'attach' with mode 'remote' does not work with 'program' attribute, please use 'cwd' attribute instead.` - ); - } - return debugConfiguration; - } - - private showWarning(ignoreWarningKey: string, warningMessage: string) { - const ignoreWarning = getFromGlobalState(ignoreWarningKey); - if (ignoreWarning) { - return; - } - - const neverAgain = { title: `Don't Show Again` }; - vscode.window.showWarningMessage(warningMessage, neverAgain).then((result) => { - if (result === neverAgain) { - updateGlobalState(ignoreWarningKey, true); - } - }); - } -} +/*--------------------------------------------------------- + * 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 path = require('path'); +import vscode = require('vscode'); +import { promptForMissingTool } from './goInstallTools'; +import { packagePathToGoModPathMap } from './goModules'; +import { getFromGlobalState, updateGlobalState } from './stateUtils'; +import { sendTelemetryEventForDebugConfiguration } from './telemetry'; +import { getBinPath, getCurrentGoPath, getGoConfig, getToolsEnvVars } from './util'; + +export class GoDebugConfigurationProvider implements vscode.DebugConfigurationProvider { + public provideDebugConfigurations( + folder: vscode.WorkspaceFolder | undefined, + token?: vscode.CancellationToken + ): vscode.DebugConfiguration[] { + return [ + { + name: 'Launch', + type: 'go', + request: 'launch', + mode: 'auto', + program: '${fileDirname}', + env: {}, + args: [] + } + ]; + } + + public resolveDebugConfiguration?( + folder: vscode.WorkspaceFolder | undefined, + debugConfiguration: vscode.DebugConfiguration, + token?: vscode.CancellationToken + ): vscode.DebugConfiguration { + if (debugConfiguration) { + sendTelemetryEventForDebugConfiguration(debugConfiguration); + } + + const activeEditor = vscode.window.activeTextEditor; + if (!debugConfiguration || !debugConfiguration.request) { + // if 'request' is missing interpret this as a missing launch.json + if (!activeEditor || activeEditor.document.languageId !== 'go') { + return; + } + + debugConfiguration = Object.assign(debugConfiguration || {}, { + name: 'Launch', + type: 'go', + request: 'launch', + mode: 'auto', + program: path.dirname(activeEditor.document.fileName) // matches ${fileDirname} + }); + } + + debugConfiguration['packagePathToGoModPathMap'] = packagePathToGoModPathMap; + + const gopath = getCurrentGoPath(folder ? folder.uri : undefined); + if (!debugConfiguration['env']) { + debugConfiguration['env'] = { GOPATH: gopath }; + } else if (!debugConfiguration['env']['GOPATH']) { + debugConfiguration['env']['GOPATH'] = gopath; + } + + const goConfig = getGoConfig(folder && folder.uri); + const goToolsEnvVars = getToolsEnvVars(); + Object.keys(goToolsEnvVars).forEach((key) => { + if (!debugConfiguration['env'].hasOwnProperty(key)) { + debugConfiguration['env'][key] = goToolsEnvVars[key]; + } + }); + + const dlvConfig = goConfig.get('delveConfig'); + let useApiV1 = false; + if (debugConfiguration.hasOwnProperty('useApiV1')) { + useApiV1 = debugConfiguration['useApiV1'] === true; + } else if (dlvConfig.hasOwnProperty('useApiV1')) { + useApiV1 = dlvConfig['useApiV1'] === true; + } + if (useApiV1) { + debugConfiguration['apiVersion'] = 1; + } + if (!debugConfiguration.hasOwnProperty('apiVersion') && dlvConfig.hasOwnProperty('apiVersion')) { + debugConfiguration['apiVersion'] = dlvConfig['apiVersion']; + } + if (!debugConfiguration.hasOwnProperty('dlvLoadConfig') && dlvConfig.hasOwnProperty('dlvLoadConfig')) { + debugConfiguration['dlvLoadConfig'] = dlvConfig['dlvLoadConfig']; + } + if ( + !debugConfiguration.hasOwnProperty('showGlobalVariables') && + dlvConfig.hasOwnProperty('showGlobalVariables') + ) { + debugConfiguration['showGlobalVariables'] = dlvConfig['showGlobalVariables']; + } + if (debugConfiguration.request === 'attach' && !debugConfiguration['cwd']) { + debugConfiguration['cwd'] = '${workspaceFolder}'; + } + + debugConfiguration['dlvToolPath'] = getBinPath('dlv'); + if (!path.isAbsolute(debugConfiguration['dlvToolPath'])) { + promptForMissingTool('dlv'); + return; + } + + if (debugConfiguration['mode'] === 'auto') { + debugConfiguration['mode'] = + activeEditor && activeEditor.document.fileName.endsWith('_test.go') ? 'test' : 'debug'; + } + + if (debugConfiguration.request === 'launch' && debugConfiguration['mode'] === 'remote') { + this.showWarning( + 'ignoreDebugLaunchRemoteWarning', + `Request type of 'launch' with mode 'remote' is deprecated, please use request type 'attach' with mode 'remote' instead.` + ); + } + + if ( + debugConfiguration.request === 'attach' && + debugConfiguration['mode'] === 'remote' && + debugConfiguration['program'] + ) { + this.showWarning( + 'ignoreUsingRemotePathAndProgramWarning', + `Request type of 'attach' with mode 'remote' does not work with 'program' attribute, please use 'cwd' attribute instead.` + ); + } + return debugConfiguration; + } + + private showWarning(ignoreWarningKey: string, warningMessage: string) { + const ignoreWarning = getFromGlobalState(ignoreWarningKey); + if (ignoreWarning) { + return; + } + + const neverAgain = { title: `Don't Show Again` }; + vscode.window.showWarningMessage(warningMessage, neverAgain).then((result) => { + if (result === neverAgain) { + updateGlobalState(ignoreWarningKey, true); + } + }); + } +} diff --git a/src/goInstall.ts b/src/goInstall.ts index b4b0101e22..be7ff9f917 100644 --- a/src/goInstall.ts +++ b/src/goInstall.ts @@ -1,64 +1,64 @@ -/*--------------------------------------------------------- - * Copyright (C) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------*/ - -import cp = require('child_process'); -import path = require('path'); -import vscode = require('vscode'); -import { isModSupported } from './goModules'; -import { envPath, getCurrentGoWorkspaceFromGOPATH } from './goPath'; -import { outputChannel } from './goStatus'; -import { getBinPath, getCurrentGoPath, getGoConfig, getModuleCache, getToolsEnvVars } from './util'; - -export async function installCurrentPackage(): Promise { - const editor = vscode.window.activeTextEditor; - if (!editor) { - vscode.window.showInformationMessage('No editor is active, cannot find current package to install'); - return; - } - if (editor.document.languageId !== 'go') { - vscode.window.showInformationMessage( - 'File in the active editor is not a Go file, cannot find current package to install' - ); - return; - } - - const goRuntimePath = getBinPath('go'); - if (!goRuntimePath) { - vscode.window.showErrorMessage( - `Failed to run "go install" to install the package as the "go" binary cannot be found in either GOROOT(${process.env['GOROOT']}) or PATH(${envPath})` - ); - return; - } - - const env = Object.assign({}, getToolsEnvVars()); - const cwd = path.dirname(editor.document.uri.fsPath); - const isMod = await isModSupported(editor.document.uri); - - // Skip installing if cwd is in the module cache - if (isMod && cwd.startsWith(getModuleCache())) { - return; - } - - const goConfig = getGoConfig(); - const buildFlags = goConfig['buildFlags'] || []; - const args = ['install', ...buildFlags]; - - if (goConfig['buildTags'] && buildFlags.indexOf('-tags') === -1) { - args.push('-tags', goConfig['buildTags']); - } - - // Find the right importPath instead of directly using `.`. Fixes https://github.com/Microsoft/vscode-go/issues/846 - const currentGoWorkspace = getCurrentGoWorkspaceFromGOPATH(getCurrentGoPath(), cwd); - const importPath = currentGoWorkspace && !isMod ? cwd.substr(currentGoWorkspace.length + 1) : '.'; - args.push(importPath); - - outputChannel.clear(); - outputChannel.show(); - outputChannel.appendLine(`Installing ${importPath === '.' ? 'current package' : importPath}`); - - cp.execFile(goRuntimePath, args, { env, cwd }, (err, stdout, stderr) => { - outputChannel.appendLine(err ? `Installation failed: ${stderr}` : `Installation successful`); - }); -} +/*--------------------------------------------------------- + * Copyright (C) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------*/ + +import cp = require('child_process'); +import path = require('path'); +import vscode = require('vscode'); +import { isModSupported } from './goModules'; +import { envPath, getCurrentGoWorkspaceFromGOPATH } from './goPath'; +import { outputChannel } from './goStatus'; +import { getBinPath, getCurrentGoPath, getGoConfig, getModuleCache, getToolsEnvVars } from './util'; + +export async function installCurrentPackage(): Promise { + const editor = vscode.window.activeTextEditor; + if (!editor) { + vscode.window.showInformationMessage('No editor is active, cannot find current package to install'); + return; + } + if (editor.document.languageId !== 'go') { + vscode.window.showInformationMessage( + 'File in the active editor is not a Go file, cannot find current package to install' + ); + return; + } + + const goRuntimePath = getBinPath('go'); + if (!goRuntimePath) { + vscode.window.showErrorMessage( + `Failed to run "go install" to install the package as the "go" binary cannot be found in either GOROOT(${process.env['GOROOT']}) or PATH(${envPath})` + ); + return; + } + + const env = Object.assign({}, getToolsEnvVars()); + const cwd = path.dirname(editor.document.uri.fsPath); + const isMod = await isModSupported(editor.document.uri); + + // Skip installing if cwd is in the module cache + if (isMod && cwd.startsWith(getModuleCache())) { + return; + } + + const goConfig = getGoConfig(); + const buildFlags = goConfig['buildFlags'] || []; + const args = ['install', ...buildFlags]; + + if (goConfig['buildTags'] && buildFlags.indexOf('-tags') === -1) { + args.push('-tags', goConfig['buildTags']); + } + + // Find the right importPath instead of directly using `.`. Fixes https://github.com/Microsoft/vscode-go/issues/846 + const currentGoWorkspace = getCurrentGoWorkspaceFromGOPATH(getCurrentGoPath(), cwd); + const importPath = currentGoWorkspace && !isMod ? cwd.substr(currentGoWorkspace.length + 1) : '.'; + args.push(importPath); + + outputChannel.clear(); + outputChannel.show(); + outputChannel.appendLine(`Installing ${importPath === '.' ? 'current package' : importPath}`); + + cp.execFile(goRuntimePath, args, { env, cwd }, (err, stdout, stderr) => { + outputChannel.appendLine(err ? `Installation failed: ${stderr}` : `Installation successful`); + }); +} diff --git a/src/goInstallTools.ts b/src/goInstallTools.ts index 3f991f98a7..bcec6e5392 100644 --- a/src/goInstallTools.ts +++ b/src/goInstallTools.ts @@ -376,7 +376,7 @@ export async function promptForMissingTool(toolName: string) { export async function promptForUpdatingTool(toolName: string, newVersion?: SemVer) { const tool = getTool(toolName); - const toolVersion = {...tool, version: newVersion}; // ToolWithVersion + const toolVersion = { ...tool, version: newVersion }; // ToolWithVersion // If user has declined to update, then don't prompt. if (containsTool(declinedUpdates, tool)) { diff --git a/src/goLanguageServer.ts b/src/goLanguageServer.ts index 7c77fc65c5..37764a69b0 100644 --- a/src/goLanguageServer.ts +++ b/src/goLanguageServer.ts @@ -250,7 +250,7 @@ export function parseLanguageServerConfig(): LanguageServerConfig { // TODO: We should have configs that match these names. // Ultimately, we should have a centralized language server config rather than separate fields. diagnostics: goConfig['languageServerExperimentalFeatures']['diagnostics'], - documentLink: goConfig['languageServerExperimentalFeatures']['documentLink'], + documentLink: goConfig['languageServerExperimentalFeatures']['documentLink'] }, checkForUpdates: goConfig['useGoProxyToCheckForToolUpdates'] }; @@ -462,7 +462,7 @@ async function latestGopls(tool: Tool): Promise { versions.sort(semver.rcompare); if (acceptGoplsPrerelease) { - return versions[0]; // The first one (newest one). + return versions[0]; // The first one (newest one). } // The first version in the sorted list without a prerelease tag. return versions.find((version) => !version.prerelease || !version.prerelease.length); diff --git a/src/goPackages.ts b/src/goPackages.ts index c840d502c7..1db33586f0 100644 --- a/src/goPackages.ts +++ b/src/goPackages.ts @@ -279,10 +279,7 @@ export function getNonVendorPackages(currentFolderPath: string): Promise { - const lines = chunks - .join('') - .toString() - .split('\n'); + const lines = chunks.join('').toString().split('\n'); const result = new Map(); const version = await getGoVersion(); diff --git a/src/goVet.ts b/src/goVet.ts index cd96c3ed83..72e3de3180 100644 --- a/src/goVet.ts +++ b/src/goVet.ts @@ -1,125 +1,125 @@ -/*--------------------------------------------------------- - * Copyright (C) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------*/ - -import path = require('path'); -import vscode = require('vscode'); -import { vetDiagnosticCollection } from './goMain'; -import { diagnosticsStatusBarItem, outputChannel } from './goStatus'; -import { - getGoConfig, - getGoVersion, - getToolsEnvVars, - getWorkspaceFolderPath, - handleDiagnosticErrors, - ICheckResult, - resolvePath, - runTool -} from './util'; - -/** - * Runs go vet in the current package or workspace. - */ -export function vetCode(vetWorkspace?: boolean) { - const editor = vscode.window.activeTextEditor; - if (!editor && !vetWorkspace) { - vscode.window.showInformationMessage('No editor is active, cannot find current package to vet'); - return; - } - if (editor.document.languageId !== 'go' && !vetWorkspace) { - vscode.window.showInformationMessage( - 'File in the active editor is not a Go file, cannot find current package to vet' - ); - return; - } - - const documentUri = editor ? editor.document.uri : null; - const goConfig = getGoConfig(documentUri); - - outputChannel.clear(); // Ensures stale output from vet on save is cleared - diagnosticsStatusBarItem.show(); - diagnosticsStatusBarItem.text = 'Vetting...'; - - goVet(documentUri, goConfig, vetWorkspace) - .then((warnings) => { - handleDiagnosticErrors(editor ? editor.document : null, warnings, vetDiagnosticCollection); - diagnosticsStatusBarItem.hide(); - }) - .catch((err) => { - vscode.window.showInformationMessage('Error: ' + err); - diagnosticsStatusBarItem.text = 'Vetting Failed'; - }); -} - -/** - * Runs go vet or go tool vet and presents the output in the 'Go' channel and in the diagnostic collections. - * - * @param fileUri Document uri. - * @param goConfig Configuration for the Go extension. - * @param vetWorkspace If true vets code in all workspace. - */ -export async function goVet( - fileUri: vscode.Uri, - goConfig: vscode.WorkspaceConfiguration, - vetWorkspace?: boolean -): Promise { - epoch++; - const closureEpoch = epoch; - if (tokenSource) { - if (running) { - tokenSource.cancel(); - } - tokenSource.dispose(); - } - tokenSource = new vscode.CancellationTokenSource(); - - const currentWorkspace = getWorkspaceFolderPath(fileUri); - const cwd = vetWorkspace && currentWorkspace ? currentWorkspace : path.dirname(fileUri.fsPath); - if (!path.isAbsolute(cwd)) { - return Promise.resolve([]); - } - - const vetFlags: string[] = goConfig['vetFlags'] || []; - const vetEnv = Object.assign({}, getToolsEnvVars()); - const args: string[] = []; - - vetFlags.forEach((flag) => { - if (flag.startsWith('--vettool=') || flag.startsWith('-vettool=')) { - let vetToolPath = flag.substr(flag.indexOf('=') + 1).trim(); - if (!vetToolPath) { - return; - } - vetToolPath = resolvePath(vetToolPath); - args.push(`${flag.substr(0, flag.indexOf('=') + 1)}${vetToolPath}`); - return; - } - args.push(flag); - }); - - const goVersion = await getGoVersion(); - const tagsArg = []; - if (goConfig['buildTags'] && vetFlags.indexOf('-tags') === -1) { - tagsArg.push('-tags'); - tagsArg.push(goConfig['buildTags']); - } - - let vetArgs = ['vet', ...args, ...tagsArg, vetWorkspace ? './...' : '.']; - if (goVersion.lt('1.10') && args.length) { - vetArgs = ['tool', 'vet', ...args, ...tagsArg, '.']; - } - - outputChannel.appendLine(`Starting "go vet" under the folder ${cwd}`); - - running = true; - return runTool(vetArgs, cwd, 'warning', true, null, vetEnv, false, tokenSource.token).then((result) => { - if (closureEpoch === epoch) { - running = false; - } - return result; - }); -} - -let epoch = 0; -let tokenSource: vscode.CancellationTokenSource; -let running = false; +/*--------------------------------------------------------- + * Copyright (C) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------*/ + +import path = require('path'); +import vscode = require('vscode'); +import { vetDiagnosticCollection } from './goMain'; +import { diagnosticsStatusBarItem, outputChannel } from './goStatus'; +import { + getGoConfig, + getGoVersion, + getToolsEnvVars, + getWorkspaceFolderPath, + handleDiagnosticErrors, + ICheckResult, + resolvePath, + runTool +} from './util'; + +/** + * Runs go vet in the current package or workspace. + */ +export function vetCode(vetWorkspace?: boolean) { + const editor = vscode.window.activeTextEditor; + if (!editor && !vetWorkspace) { + vscode.window.showInformationMessage('No editor is active, cannot find current package to vet'); + return; + } + if (editor.document.languageId !== 'go' && !vetWorkspace) { + vscode.window.showInformationMessage( + 'File in the active editor is not a Go file, cannot find current package to vet' + ); + return; + } + + const documentUri = editor ? editor.document.uri : null; + const goConfig = getGoConfig(documentUri); + + outputChannel.clear(); // Ensures stale output from vet on save is cleared + diagnosticsStatusBarItem.show(); + diagnosticsStatusBarItem.text = 'Vetting...'; + + goVet(documentUri, goConfig, vetWorkspace) + .then((warnings) => { + handleDiagnosticErrors(editor ? editor.document : null, warnings, vetDiagnosticCollection); + diagnosticsStatusBarItem.hide(); + }) + .catch((err) => { + vscode.window.showInformationMessage('Error: ' + err); + diagnosticsStatusBarItem.text = 'Vetting Failed'; + }); +} + +/** + * Runs go vet or go tool vet and presents the output in the 'Go' channel and in the diagnostic collections. + * + * @param fileUri Document uri. + * @param goConfig Configuration for the Go extension. + * @param vetWorkspace If true vets code in all workspace. + */ +export async function goVet( + fileUri: vscode.Uri, + goConfig: vscode.WorkspaceConfiguration, + vetWorkspace?: boolean +): Promise { + epoch++; + const closureEpoch = epoch; + if (tokenSource) { + if (running) { + tokenSource.cancel(); + } + tokenSource.dispose(); + } + tokenSource = new vscode.CancellationTokenSource(); + + const currentWorkspace = getWorkspaceFolderPath(fileUri); + const cwd = vetWorkspace && currentWorkspace ? currentWorkspace : path.dirname(fileUri.fsPath); + if (!path.isAbsolute(cwd)) { + return Promise.resolve([]); + } + + const vetFlags: string[] = goConfig['vetFlags'] || []; + const vetEnv = Object.assign({}, getToolsEnvVars()); + const args: string[] = []; + + vetFlags.forEach((flag) => { + if (flag.startsWith('--vettool=') || flag.startsWith('-vettool=')) { + let vetToolPath = flag.substr(flag.indexOf('=') + 1).trim(); + if (!vetToolPath) { + return; + } + vetToolPath = resolvePath(vetToolPath); + args.push(`${flag.substr(0, flag.indexOf('=') + 1)}${vetToolPath}`); + return; + } + args.push(flag); + }); + + const goVersion = await getGoVersion(); + const tagsArg = []; + if (goConfig['buildTags'] && vetFlags.indexOf('-tags') === -1) { + tagsArg.push('-tags'); + tagsArg.push(goConfig['buildTags']); + } + + let vetArgs = ['vet', ...args, ...tagsArg, vetWorkspace ? './...' : '.']; + if (goVersion.lt('1.10') && args.length) { + vetArgs = ['tool', 'vet', ...args, ...tagsArg, '.']; + } + + outputChannel.appendLine(`Starting "go vet" under the folder ${cwd}`); + + running = true; + return runTool(vetArgs, cwd, 'warning', true, null, vetEnv, false, tokenSource.token).then((result) => { + if (closureEpoch === epoch) { + running = false; + } + return result; + }); +} + +let epoch = 0; +let tokenSource: vscode.CancellationTokenSource; +let running = false; diff --git a/test/integration/extension.test.ts b/test/integration/extension.test.ts index 17372c59b7..a8af8d13f3 100644 --- a/test/integration/extension.test.ts +++ b/test/integration/extension.test.ts @@ -39,7 +39,7 @@ import { isVendorSupported } from '../../src/util'; -suite('Go Extension Tests', function() { +suite('Go Extension Tests', function () { this.timeout(10000); const dummyCancellationSource = new vscode.CancellationTokenSource(); @@ -1305,9 +1305,9 @@ encountered. assert.equal( expected.length, labels.length, - `expected number of completions: ${expected.length} Actual: ${ - labels.length - } at position(${position.line + 1},${position.character + 1}) ${labels}` + `expected number of completions: ${expected.length} Actual: ${labels.length} at position(${ + position.line + 1 + },${position.character + 1}) ${labels}` ); expected.forEach((entry, index) => { assert.equal( diff --git a/tslint.json b/tslint.json index e5e73bded9..41739c7d97 100644 --- a/tslint.json +++ b/tslint.json @@ -119,7 +119,7 @@ "semicolon": true, "space-before-function-paren": { "options": { - "anonymous": "never", + "anonymous": "always", "asyncArrow": "always", "constructor": "never", "method": "never",