[tslint] apply allow-parens rule
diff --git a/src/debugAdapter/goDebug.ts b/src/debugAdapter/goDebug.ts
index 65bb63d..e465ec7 100644
--- a/src/debugAdapter/goDebug.ts
+++ b/src/debugAdapter/goDebug.ts
@@ -268,7 +268,7 @@
});
function logArgsToString(args: any[]): string {
- return args.map(arg => {
+ return args.map((arg) => {
return typeof arg === 'string' ?
arg :
JSON.stringify(arg);
@@ -405,11 +405,11 @@
runArgs.push(...launchArgs.args);
}
this.debugProcess = spawn(getBinPathWithPreferredGopath('go', []), runArgs, { env });
- this.debugProcess.stderr.on('data', chunk => {
+ this.debugProcess.stderr.on('data', (chunk) => {
const str = chunk.toString();
if (this.onstderr) { this.onstderr(str); }
});
- this.debugProcess.stdout.on('data', chunk => {
+ this.debugProcess.stdout.on('data', (chunk) => {
const str = chunk.toString();
if (this.onstdout) { this.onstdout(str); }
});
@@ -520,11 +520,11 @@
}, 200);
}
- this.debugProcess.stderr.on('data', chunk => {
+ this.debugProcess.stderr.on('data', (chunk) => {
const str = chunk.toString();
if (this.onstderr) { this.onstderr(str); }
});
- this.debugProcess.stdout.on('data', chunk => {
+ this.debugProcess.stdout.on('data', (chunk) => {
const str = chunk.toString();
if (this.onstdout) { this.onstdout(str); }
if (!serverRunning) {
@@ -544,20 +544,20 @@
}
public call<T>(command: string, args: any[], callback: (err: Error, results: T) => void) {
- this.connection.then(conn => {
+ this.connection.then((conn) => {
conn.call('RPCServer.' + command, args, callback);
- }, err => {
+ }, (err) => {
callback(err, null);
});
}
public callPromise<T>(command: string, args: any[]): Thenable<T> {
return new Promise<T>((resolve, reject) => {
- this.connection.then(conn => {
+ this.connection.then((conn) => {
conn.call<T>(`RPCServer.${command}`, args, (err, res) => {
return err ? reject(err) : resolve(res);
});
- }, err => {
+ }, (err) => {
reject(err);
});
});
@@ -601,7 +601,7 @@
killTree(this.debugProcess.pid);
await removeFile(this.localDebugeePath);
};
- return new Promise(async resolve => {
+ return new Promise(async (resolve) => {
// For remote debugging, closing the connection would terminate the
// program as well so we just want to disconnect.
// See https://www.github.com/go-delve/delve/issues/1587
@@ -792,7 +792,7 @@
log('InitializeEvent');
}
this.sendResponse(response);
- }, err => {
+ }, (err) => {
this.sendErrorResponse(response, 3000, 'Failed to continue: "{e}"', { e: err.toString() });
log('ContinueResponse');
});
@@ -877,7 +877,7 @@
private updateGoroutinesList(goroutines: DebugGoroutine[]): void {
// Assume we need to stop all the threads we saw before...
const needsToBeStopped = new Set<number>();
- this.goroutines.forEach(id => needsToBeStopped.add(id));
+ this.goroutines.forEach((id) => needsToBeStopped.add(id));
for (const goroutine of goroutines) {
// ...but delete from list of threads to stop if we still see it
needsToBeStopped.delete(goroutine.id);
@@ -888,7 +888,7 @@
this.goroutines.add(goroutine.id);
}
// Send existed event if it's no longer there
- needsToBeStopped.forEach(id => {
+ needsToBeStopped.forEach((id) => {
this.sendEvent(new ThreadEvent('exited', id));
this.goroutines.delete(id);
});
@@ -901,13 +901,13 @@
}
const remoteFile = this.toDebuggerPath(file);
- return Promise.all(this.breakpoints.get(file).map(existingBP => {
+ return Promise.all(this.breakpoints.get(file).map((existingBP) => {
log('Clearing: ' + existingBP.id);
return this.delve.callPromise('ClearBreakpoint', [this.delve.isApiV1 ? existingBP.id : { Id: existingBP.id }]);
})).then(() => {
log('All cleared');
let existingBreakpoints: DebugBreakpoint[] | undefined;
- return Promise.all(args.breakpoints.map(breakpoint => {
+ return Promise.all(args.breakpoints.map((breakpoint) => {
if (this.delve.remotePath.length === 0) {
log('Creating on: ' + file + ':' + breakpoint.line);
} else {
@@ -938,7 +938,7 @@
return null;
}
}
- const matchedBreakpoint = existingBreakpoints.find(breakpoint =>
+ const matchedBreakpoint = existingBreakpoints.find((breakpoint) =>
breakpoint.line === breakpointIn.line && breakpoint.file === breakpointIn.file);
if (!matchedBreakpoint) {
log(`Cannot match breakpoint ${breakpointIn} with existing breakpoints.`);
@@ -950,7 +950,7 @@
return null;
});
}));
- }).then(newBreakpoints => {
+ }).then((newBreakpoints) => {
let convertedBreakpoints: DebugBreakpoint[];
if (!this.delve.isApiV1) {
// Unwrap breakpoints from v2 apicall
@@ -969,13 +969,13 @@
return { verified: false, line: args.lines[i] };
}
});
- this.breakpoints.set(file, convertedBreakpoints.filter(x => !!x));
+ this.breakpoints.set(file, convertedBreakpoints.filter((x) => !!x));
return breakpoints;
- }).then(breakpoints => {
+ }).then((breakpoints) => {
response.body = { breakpoints };
this.sendResponse(response);
log('SetBreakPointsResponse');
- }, err => {
+ }, (err) => {
this.sendErrorResponse(response, 2002, 'Failed to set breakpoint: "{e}"', { e: err.toString() });
logError(err);
});
@@ -998,11 +998,11 @@
this.skipStopEventOnce = this.continueRequestRunning;
this.delve.callPromise('Command', [{ name: 'halt' }]).then(() => {
return this.setBreakPoints(response, args).then(() => {
- return this.continue(true).then(null, err => {
+ return this.continue(true).then(null, (err) => {
logError(`Failed to continue delve after halting it to set breakpoints: "${err.toString()}"`);
});
});
- }, err => {
+ }, (err) => {
this.skipStopEventOnce = false;
logError(err);
return this.sendErrorResponse(response, 2008, 'Failed to halt delve before attempting to set breakpoint: "{e}"', { e: err.toString() });
@@ -1032,7 +1032,7 @@
const goroutines = this.delve.isApiV1 ? <DebugGoroutine[]>out : (<ListGoroutinesOut>out).Goroutines;
log('goroutines', goroutines);
this.updateGoroutinesList(goroutines);
- const threads = goroutines.map(goroutine =>
+ const threads = goroutines.map((goroutine) =>
new Thread(
goroutine.id,
goroutine.userCurrentLoc.function ? goroutine.userCurrentLoc.function.name : (goroutine.userCurrentLoc.file + '@' + goroutine.userCurrentLoc.line)
@@ -1166,7 +1166,7 @@
return;
}
- this.getPackageInfo(this.debugState).then(packageName => {
+ this.getPackageInfo(this.debugState).then((packageName) => {
if (!packageName) {
this.sendResponse(response);
log('ScopesResponse');
@@ -1225,7 +1225,7 @@
if (this.packageInfo.has(dir)) {
return Promise.resolve(this.packageInfo.get(dir));
}
- return new Promise(resolve => {
+ return new Promise((resolve) => {
execFile(getBinPathWithPreferredGopath('go', []), ['list', '-f', '{{.Name}} {{.ImportPath}}'], { cwd: dir, env: this.delve.dlvEnv }, (err, stdout, stderr) => {
if (err || stderr || !stdout) {
logError(`go list failed on ${dir}: ${stderr || err}`);
@@ -1264,7 +1264,7 @@
if (v.children[0].children.length > 0) {
// Generate correct fullyQualified names for variable expressions
v.children[0].fullyQualifiedName = v.fullyQualifiedName;
- v.children[0].children.forEach(child => {
+ v.children[0].children.forEach((child) => {
child.fullyQualifiedName = v.fullyQualifiedName + '.' + child.name;
});
}
@@ -1314,7 +1314,7 @@
// Default case - structs
if (v.children.length > 0) {
// Generate correct fullyQualified names for variable expressions
- v.children.forEach(child => {
+ v.children.forEach((child) => {
child.fullyQualifiedName = v.fullyQualifiedName + '.' + child.name;
});
}
@@ -1333,10 +1333,10 @@
// from https://github.com/go-delve/delve/blob/master/Documentation/api/ClientHowto.md#looking-into-variables
if ((v.kind === GoReflectKind.Struct && v.len > v.children.length) ||
(v.kind === GoReflectKind.Interface && v.children.length > 0 && v.children[0].onlyAddr === true)) {
- await this.evaluateRequestImpl({ expression: exp }).then(result => {
+ await this.evaluateRequestImpl({ expression: exp }).then((result) => {
const variable = this.delve.isApiV1 ? <DebugVariable>result : (<EvalOut>result).Variable;
v.children = variable.children;
- }, err => logError('Failed to evaluate expression - ' + err.toString()));
+ }, (err) => logError('Failed to evaluate expression - ' + err.toString()));
}
};
// expressions passed to loadChildren defined per https://github.com/go-delve/delve/blob/master/Documentation/api/ClientHowto.md#loading-more-of-a-variable
@@ -1525,14 +1525,14 @@
protected evaluateRequest(response: DebugProtocol.EvaluateResponse, args: DebugProtocol.EvaluateArguments): void {
log('EvaluateRequest');
- this.evaluateRequestImpl(args).then(out => {
+ this.evaluateRequestImpl(args).then((out) => {
const variable = this.delve.isApiV1 ? <DebugVariable>out : (<EvalOut>out).Variable;
// #2326: Set the fully qualified name for variable mapping
variable.fullyQualifiedName = variable.name;
response.body = this.convertDebugVariableToProtocolVariable(variable);
this.sendResponse(response);
log('EvaluateResponse');
- }, err => {
+ }, (err) => {
this.sendErrorResponse(response, 2009, 'Unable to eval expression: "{e}"', { e: err.toString() });
});
}
@@ -1557,8 +1557,8 @@
Scope: scope,
Cfg: this.delve.loadConfig
};
- const returnValue = this.delve.callPromise<EvalOut | DebugVariable>(this.delve.isApiV1 ? 'EvalSymbol' : 'Eval', [evalSymbolArgs]).then(val => val,
- err => {
+ const returnValue = this.delve.callPromise<EvalOut | DebugVariable>(this.delve.isApiV1 ? 'EvalSymbol' : 'Eval', [evalSymbolArgs]).then((val) => val,
+ (err) => {
logError('Failed to eval expression: ', JSON.stringify(evalSymbolArgs, null, ' '), '\n\rEval error:', err.toString());
return Promise.reject(err);
});
@@ -1588,9 +1588,9 @@
}
private addFullyQualifiedName(variables: DebugVariable[]) {
- variables.forEach(local => {
+ variables.forEach((local) => {
local.fullyQualifiedName = local.name;
- local.children.forEach(child => {
+ local.children.forEach((child) => {
child.fullyQualifiedName = local.name;
});
});
diff --git a/src/goBrowsePackage.ts b/src/goBrowsePackage.ts
index c0c89e7..aa8020d 100644
--- a/src/goBrowsePackage.ts
+++ b/src/goBrowsePackage.ts
@@ -73,14 +73,14 @@
const xtestfiles = matches[4] ? matches[4].split(' ') : [];
files = files.concat(testfiles);
files = files.concat(xtestfiles);
- vscode.window.showQuickPick(files, { placeHolder: `Below are Go files from ${pkg}` }).then(file => {
+ vscode.window.showQuickPick(files, { placeHolder: `Below are Go files from ${pkg}` }).then((file) => {
// if user abandoned list, file will be null and path.join will error out.
// therefore return.
if (!file) {
return;
}
- vscode.workspace.openTextDocument(path.join(dir, file)).then(document => {
+ vscode.workspace.openTextDocument(path.join(dir, file)).then((document) => {
vscode.window.showTextDocument(document);
});
});
@@ -89,7 +89,7 @@
}
function showPackageList(workDir: string) {
- return getAllPackages(workDir).then(pkgMap => {
+ return getAllPackages(workDir).then((pkgMap) => {
const pkgs: string[] = Array.from(pkgMap.keys());
if (pkgs.length === 0) {
return vscode.window.showErrorMessage('Could not find packages. Ensure `gopkgs -format {{.Name}};{{.ImportPath}}` runs successfully.');
@@ -98,7 +98,7 @@
vscode
.window
.showQuickPick(pkgs.sort(), { placeHolder: 'Select a package to browse' })
- .then(pkgFromDropdown => {
+ .then((pkgFromDropdown) => {
if (!pkgFromDropdown) {
return;
}
diff --git a/src/goBuild.ts b/src/goBuild.ts
index 2fc9c93..b503d36 100644
--- a/src/goBuild.ts
+++ b/src/goBuild.ts
@@ -35,13 +35,13 @@
diagnosticsStatusBarItem.show();
diagnosticsStatusBarItem.text = 'Building...';
- isModSupported(documentUri).then(isMod => {
+ isModSupported(documentUri).then((isMod) => {
goBuild(documentUri, isMod, goConfig, buildWorkspace)
- .then(errors => {
+ .then((errors) => {
handleDiagnosticErrors(editor ? editor.document : null, errors, buildDiagnosticCollection);
diagnosticsStatusBarItem.hide();
})
- .catch(err => {
+ .catch((err) => {
vscode.window.showInformationMessage('Error: ' + err);
diagnosticsStatusBarItem.text = 'Build Failed';
});
@@ -104,7 +104,7 @@
if (buildWorkspace && currentWorkspace && !isTestFile) {
outputChannel.appendLine(`Starting building the current workspace at ${currentWorkspace}`);
- return getNonVendorPackages(currentWorkspace).then(pkgs => {
+ return getNonVendorPackages(currentWorkspace).then((pkgs) => {
running = true;
return runTool(
buildArgs.concat(Array.from(pkgs.keys())),
@@ -115,7 +115,7 @@
buildEnv,
true,
tokenSource.token
- ).then(v => {
+ ).then((v) => {
updateRunning();
return v;
});
@@ -143,7 +143,7 @@
buildEnv,
true,
tokenSource.token
- ).then(v => {
+ ).then((v) => {
updateRunning();
return v;
});
diff --git a/src/goCheck.ts b/src/goCheck.ts
index ccd920a..dcd0e93 100644
--- a/src/goCheck.ts
+++ b/src/goCheck.ts
@@ -35,7 +35,7 @@
return;
}
if ((ctx.globalState.get('ignoreGeneratedCodeWarning') !== true) && e.document.lineAt(0).text.match(/^\/\/ Code generated .* DO NOT EDIT\.$/)) {
- vscode.window.showWarningMessage('This file seems to be generated. DO NOT EDIT.', neverAgain).then(result => {
+ vscode.window.showWarningMessage('This file seems to be generated. DO NOT EDIT.', neverAgain).then((result) => {
if (result === neverAgain) {
ctx.globalState.update('ignoreGeneratedCodeWarning', true);
}
@@ -73,7 +73,7 @@
return testPromise;
}
- testPromise = isModSupported(fileUri).then(isMod => {
+ testPromise = isModSupported(fileUri).then((isMod) => {
testConfig.isMod = isMod;
return goTest(testConfig);
});
@@ -82,14 +82,14 @@
if (!disableBuildAndVet && !!goConfig['buildOnSave'] && goConfig['buildOnSave'] !== 'off') {
runningToolsPromises.push(isModSupported(fileUri)
- .then(isMod => goBuild(fileUri, isMod, goConfig, goConfig['buildOnSave'] === 'workspace'))
- .then(errors => ({ diagnosticCollection: buildDiagnosticCollection, errors })));
+ .then((isMod) => goBuild(fileUri, isMod, goConfig, goConfig['buildOnSave'] === 'workspace'))
+ .then((errors) => ({ diagnosticCollection: buildDiagnosticCollection, errors })));
}
if (!!goConfig['testOnSave']) {
statusBarItem.show();
statusBarItem.text = 'Tests Running';
- runTest().then(success => {
+ runTest().then((success) => {
if (statusBarItem.text === '') {
return;
}
@@ -103,16 +103,16 @@
if (!!goConfig['lintOnSave'] && goConfig['lintOnSave'] !== 'off') {
runningToolsPromises.push(goLint(fileUri, goConfig, goConfig['lintOnSave'])
- .then(errors => ({ diagnosticCollection: lintDiagnosticCollection, errors })));
+ .then((errors) => ({ diagnosticCollection: lintDiagnosticCollection, errors })));
}
if (!disableBuildAndVet && !!goConfig['vetOnSave'] && goConfig['vetOnSave'] !== 'off') {
runningToolsPromises.push(goVet(fileUri, goConfig, goConfig['vetOnSave'] === 'workspace')
- .then(errors => ({ diagnosticCollection: vetDiagnosticCollection, errors })));
+ .then((errors) => ({ diagnosticCollection: vetDiagnosticCollection, errors })));
}
if (!!goConfig['coverOnSave']) {
- runTest().then(success => {
+ runTest().then((success) => {
if (!success) {
return [];
}
diff --git a/src/goCodeAction.ts b/src/goCodeAction.ts
index a44d577..c87471c 100644
--- a/src/goCodeAction.ts
+++ b/src/goCodeAction.ts
@@ -11,14 +11,14 @@
export class GoCodeActionProvider implements vscode.CodeActionProvider {
public provideCodeActions(document: vscode.TextDocument, range: vscode.Range, context: vscode.CodeActionContext, token: vscode.CancellationToken): Thenable<vscode.Command[]> {
- const promises = context.diagnostics.map(diag => {
+ const promises = context.diagnostics.map((diag) => {
// When a name is not found but could refer to a package, offer to add import
if (diag.message.indexOf('undefined: ') === 0) {
const [_, name] = /^undefined: (\S*)/.exec(diag.message);
- return listPackages().then(packages => {
+ return listPackages().then((packages) => {
const commands = packages
- .filter(pkg => pkg === name || pkg.endsWith('/' + name))
- .map(pkg => {
+ .filter((pkg) => pkg === name || pkg.endsWith('/' + name))
+ .map((pkg) => {
return {
title: 'import "' + pkg + '"',
command: 'go.import.add',
@@ -31,7 +31,7 @@
return [];
});
- return Promise.all(promises).then(arrs => {
+ return Promise.all(promises).then((arrs) => {
const results: { [key: string]: any } = {};
for (const segment of arrs) {
for (const item of segment) {
diff --git a/src/goCover.ts b/src/goCover.ts
index b8c1e94..9fa91b9 100644
--- a/src/goCover.ts
+++ b/src/goCover.ts
@@ -265,7 +265,7 @@
return;
}
- if (vscode.window.visibleTextEditors.every(editor => editor.document !== e.document)) {
+ if (vscode.window.visibleTextEditors.every((editor) => editor.document !== e.document)) {
return;
}
@@ -306,7 +306,7 @@
applyCodeCoverage: true
};
- return goTest(testConfig).then(success => {
+ return goTest(testConfig).then((success) => {
if (!success) {
showTestOutput();
}
@@ -314,7 +314,7 @@
}
export function isPartOfComment(e: vscode.TextDocumentChangeEvent): boolean {
- return e.contentChanges.every(change => {
+ return e.contentChanges.every((change) => {
// We cannot be sure with using just regex on individual lines whether a multi line change is part of a comment or not
// So play it safe and treat it as not a comment
if (!change.range.isSingleLine || change.text.includes('\n')) {
diff --git a/src/goDebugConfiguration.ts b/src/goDebugConfiguration.ts
index c1fcb21..0b7769f 100644
--- a/src/goDebugConfiguration.ts
+++ b/src/goDebugConfiguration.ts
@@ -60,7 +60,7 @@
const goConfig = getGoConfig(folder && folder.uri);
const goToolsEnvVars = getToolsEnvVars();
- Object.keys(goToolsEnvVars).forEach(key => {
+ Object.keys(goToolsEnvVars).forEach((key) => {
if (!debugConfiguration['env'].hasOwnProperty(key)) {
debugConfiguration['env'][key] = goToolsEnvVars[key];
}
@@ -104,7 +104,7 @@
const ignoreWarningKey = 'ignoreDebugLaunchRemoteWarning';
const ignoreWarning = getFromGlobalState(ignoreWarningKey);
if (ignoreWarning !== true && debugConfiguration.request === 'launch' && debugConfiguration['mode'] === 'remote') {
- vscode.window.showWarningMessage('Request type of \'launch\' with mode \'remote\' is deprecated, please use request type \'attach\' with mode \'remote\' instead.', neverAgain).then(result => {
+ vscode.window.showWarningMessage('Request type of \'launch\' with mode \'remote\' is deprecated, please use request type \'attach\' with mode \'remote\' instead.', neverAgain).then((result) => {
if (result === neverAgain) {
updateGlobalState(ignoreWarningKey, true);
}
diff --git a/src/goDeclaration.ts b/src/goDeclaration.ts
index 00ba352..eaea26c 100644
--- a/src/goDeclaration.ts
+++ b/src/goDeclaration.ts
@@ -58,7 +58,7 @@
goConfig = getGoConfig(document.uri);
}
const toolForDocs = goConfig['docsTool'] || 'godoc';
- return getModFolderPath(document.uri).then(modFolderPath => {
+ return getModFolderPath(document.uri).then((modFolderPath) => {
const input: GoDefinitionInput = {
document,
position,
@@ -155,12 +155,12 @@
return resolve(definitionInformation);
}
match = /^\w+ \(\*?(\w+)\)/.exec(lines[1]);
- runGodoc(input.cwd, pkgPath, match ? match[1] : '', input.word, token).then(doc => {
+ runGodoc(input.cwd, pkgPath, match ? match[1] : '', input.word, token).then((doc) => {
if (doc) {
definitionInformation.doc = doc;
}
resolve(definitionInformation);
- }).catch(err => {
+ }).catch((err) => {
console.log(err);
resolve(definitionInformation);
});
@@ -308,14 +308,14 @@
}
public provideDefinition(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Thenable<vscode.Location> {
- return definitionLocation(document, position, this.goConfig, false, token).then(definitionInfo => {
+ return definitionLocation(document, position, this.goConfig, false, token).then((definitionInfo) => {
if (definitionInfo == null || definitionInfo.file == null) {
return null;
}
const definitionResource = vscode.Uri.file(definitionInfo.file);
const pos = new vscode.Position(definitionInfo.line, definitionInfo.column);
return new vscode.Location(definitionResource, pos);
- }, err => {
+ }, (err) => {
const miss = parseMissingError(err);
if (miss[0]) {
promptForMissingTool(miss[1]);
diff --git a/src/goExtraInfo.ts b/src/goExtraInfo.ts
index 462b228..090a9ec 100644
--- a/src/goExtraInfo.ts
+++ b/src/goExtraInfo.ts
@@ -27,13 +27,13 @@
if (goConfig['docsTool'] === 'guru') {
goConfig = Object.assign({}, goConfig, { docsTool: 'godoc' });
}
- return definitionLocation(document, position, goConfig, true, token).then(definitionInfo => {
+ return definitionLocation(document, position, goConfig, true, token).then((definitionInfo) => {
if (definitionInfo == null) {
return null;
}
const lines = definitionInfo.declarationlines
- .filter(line => line !== '')
- .map(line => line.replace(/\t/g, ' '));
+ .filter((line) => line !== '')
+ .map((line) => line.replace(/\t/g, ' '));
let text;
text = lines.join('\n').replace(/\n+$/, '');
const hoverTexts = new vscode.MarkdownString();
diff --git a/src/goFillStruct.ts b/src/goFillStruct.ts
index 84d3b97..c3f725f 100644
--- a/src/goFillStruct.ts
+++ b/src/goFillStruct.ts
@@ -79,7 +79,7 @@
const indent = '\t'.repeat(tabsCount);
- editor.edit(editBuilder => {
+ editor.edit((editBuilder) => {
output.forEach((structToFill) => {
const out = structToFill.code.replace(/\n/g, '\n' + indent);
const rangeToReplace = new vscode.Range(editor.document.positionAt(structToFill.start),
diff --git a/src/goFormat.ts b/src/goFormat.ts
index b6b7a38..c13e895 100644
--- a/src/goFormat.ts
+++ b/src/goFormat.ts
@@ -15,7 +15,7 @@
export class GoDocumentFormattingEditProvider implements vscode.DocumentFormattingEditProvider {
public provideDocumentFormattingEdits(document: vscode.TextDocument, options: vscode.FormattingOptions, token: vscode.CancellationToken): vscode.ProviderResult<vscode.TextEdit[]> {
- if (vscode.window.visibleTextEditors.every(e => e.document.fileName !== document.fileName)) {
+ if (vscode.window.visibleTextEditors.every((e) => e.document.fileName !== document.fileName)) {
return [];
}
@@ -39,7 +39,7 @@
formatFlags.push('-style=indent=' + options.tabSize);
}
- return this.runFormatter(formatTool, formatFlags, document, token).then(edits => edits, err => {
+ return this.runFormatter(formatTool, formatFlags, document, token).then((edits) => edits, (err) => {
if (typeof err === 'string' && err.startsWith('flag provided but not defined: -srcdir')) {
promptForUpdatingTool(formatTool);
return Promise.resolve([]);
@@ -70,15 +70,15 @@
const p = cp.spawn(formatCommandBinPath, formatFlags, { env, cwd });
token.onCancellationRequested(() => !p.killed && killTree(p.pid));
p.stdout.setEncoding('utf8');
- p.stdout.on('data', data => stdout += data);
- p.stderr.on('data', data => stderr += data);
- p.on('error', err => {
+ p.stdout.on('data', (data) => stdout += data);
+ p.stderr.on('data', (data) => stderr += data);
+ p.on('error', (err) => {
if (err && (<any>err).code === 'ENOENT') {
promptForMissingTool(formatTool);
return reject();
}
});
- p.on('close', code => {
+ p.on('close', (code) => {
if (code !== 0) {
return reject(stderr);
}
diff --git a/src/goGenerateTests.ts b/src/goGenerateTests.ts
index f51641a..8039da5 100644
--- a/src/goGenerateTests.ts
+++ b/src/goGenerateTests.ts
@@ -91,7 +91,7 @@
const functions = await getFunctions(editor.document);
const selection = editor.selection;
- const currentFunction: vscode.DocumentSymbol = functions.find(func => selection && func.range.contains(selection.start));
+ const currentFunction: vscode.DocumentSymbol = functions.find((func) => selection && func.range.contains(selection.start));
if (!currentFunction) {
vscode.window.showInformationMessage('No function found at cursor.');
@@ -161,7 +161,7 @@
// Expected stdout is of the format "Generated TestMain\nGenerated Testhello\n"
if (stdout.startsWith(generatedWord)) {
- const lines = stdout.split('\n').filter(element => {
+ const lines = stdout.split('\n').filter((element) => {
return element.startsWith(generatedWord);
}).map((element) => {
return element.substr(generatedWord.length);
@@ -189,5 +189,5 @@
async function getFunctions(doc: vscode.TextDocument): Promise<vscode.DocumentSymbol[]> {
const documentSymbolProvider = new GoDocumentSymbolProvider();
const symbols = await documentSymbolProvider.provideDocumentSymbols(doc, null);
- return symbols[0].children.filter(sym => sym.kind === vscode.SymbolKind.Function);
+ return symbols[0].children.filter((sym) => sym.kind === vscode.SymbolKind.Function);
}
diff --git a/src/goImpl.ts b/src/goImpl.ts
index 87e1023..dcb0fcf 100644
--- a/src/goImpl.ts
+++ b/src/goImpl.ts
@@ -19,7 +19,7 @@
return vscode.window.showInputBox({
placeHolder: 'f *File io.Closer',
prompt: 'Enter receiver and interface to implement.'
- }).then(implInput => {
+ }).then((implInput) => {
if (typeof implInput === 'undefined') {
return;
}
@@ -50,7 +50,7 @@
return;
}
- vscode.window.activeTextEditor.edit(editBuilder => {
+ vscode.window.activeTextEditor.edit((editBuilder) => {
editBuilder.insert(insertPos, stdout);
});
});
diff --git a/src/goImport.ts b/src/goImport.ts
index 7f35efa..bd19d65 100644
--- a/src/goImport.ts
+++ b/src/goImport.ts
@@ -24,7 +24,7 @@
const stdLibs: string[] = [];
const nonStdLibs: string[] = [];
pkgMap.forEach((value, key) => {
- if (importedPkgs.some(imported => imported === key)) {
+ if (importedPkgs.some((imported) => imported === key)) {
return;
}
if (value.isStd) {
@@ -73,11 +73,11 @@
}
const { imports, pkg } = parseFilePrelude(vscode.window.activeTextEditor.document.getText());
- if (imports.some(block => block.pkgs.some(pkgpath => pkgpath === arg))) {
+ if (imports.some((block) => block.pkgs.some((pkgpath) => pkgpath === arg))) {
return [];
}
- const multis = imports.filter(x => x.kind === 'multi');
+ const multis = imports.filter((x) => x.kind === 'multi');
if (multis.length > 0) {
// There is a multiple import declaration, add to the last one
const lastImportSection = multis[multis.length - 1];
@@ -92,7 +92,7 @@
const edits = [];
edits.push(vscode.TextEdit.insert(new vscode.Position(imports[0].start, 0), 'import (\n\t"' + arg + '"\n'));
- imports.forEach(element => {
+ imports.forEach((element) => {
const currentLine = vscode.window.activeTextEditor.document.lineAt(element.start).text;
const updatedLine = currentLine.replace(/^\s*import\s*/, '\t');
edits.push(vscode.TextEdit.replace(new vscode.Range(element.start, 0, element.start, currentLine.length), updatedLine));
@@ -112,7 +112,7 @@
export function addImport(arg: { importPath: string, from: string }) {
const p = (arg && arg.importPath) ? Promise.resolve(arg.importPath) : askUserForImport();
- p.then(imp => {
+ p.then((imp) => {
sendTelemetryEventForAddImportCmd(arg);
const edits = getTextEditForAddImport(imp);
if (edits && edits.length > 0) {
diff --git a/src/goInstallTools.ts b/src/goInstallTools.ts
index 114f95f..b51ab91 100644
--- a/src/goInstallTools.ts
+++ b/src/goInstallTools.ts
@@ -27,7 +27,7 @@
// Update existing tools by finding all tools the user has already installed.
if (updateExistingToolsOnly) {
- installTools(allTools.filter(tool => {
+ installTools(allTools.filter((tool) => {
const toolPath = getBinPath(tool.name);
return toolPath && path.isAbsolute(toolPath);
}), goVersion);
@@ -35,7 +35,7 @@
}
// Otherwise, allow the user to select which tools to install or update.
- vscode.window.showQuickPick(allTools.map(x => {
+ vscode.window.showQuickPick(allTools.map((x) => {
const item: vscode.QuickPickItem = {
label: x.name,
description: x.description
@@ -44,11 +44,11 @@
}), {
canPickMany: true,
placeHolder: 'Select the tools to install/update.'
- }).then(selectedTools => {
+ }).then((selectedTools) => {
if (!selectedTools) {
return;
}
- installTools(selectedTools.map(x => getTool(x.label)), goVersion);
+ installTools(selectedTools.map((x) => getTool(x.label)), goVersion);
});
}
@@ -99,7 +99,7 @@
envForTools['GOPATH'] = toolsGopath;
} else {
const msg = 'Cannot install Go tools. Set either go.gopath or go.toolsGopath in settings.';
- vscode.window.showInformationMessage(msg, 'Open User Settings', 'Open Workspace Settings').then(selected => {
+ vscode.window.showInformationMessage(msg, 'Open User Settings', 'Open Workspace Settings').then((selected) => {
switch (selected) {
case 'Open User Settings':
vscode.commands.executeCommand('workbench.action.openGlobalSettings');
@@ -135,7 +135,7 @@
const toolsTmpDir = fs.mkdtempSync(getTempFilePath('go-tools-'));
return missing.reduce((res: Promise<string[]>, tool: Tool) => {
- return res.then(sofar => new Promise<string[]>((resolve, reject) => {
+ return res.then((sofar) => new Promise<string[]>((resolve, reject) => {
// Disable modules for tools which are installed with the "..." wildcard.
// TODO: ... will be supported in Go 1.13, so enable these tools to use modules then.
const modulesOffForTool = modulesOff || disableModulesForWildcard(tool, goVersion);
@@ -212,9 +212,9 @@
});
});
}));
- }, Promise.resolve([])).then(res => {
+ }, Promise.resolve([])).then((res) => {
outputChannel.appendLine(''); // Blank line for spacing
- const failures = res.filter(x => x != null);
+ const failures = res.filter((x) => x != null);
if (failures.length === 0) {
if (containsString(missing, 'go-langserver') || containsString(missing, 'gopls')) {
outputChannel.appendLine('Reload VS Code window to use the Go language server');
@@ -263,13 +263,13 @@
if (!containsTool(missing, tool)) {
return;
}
- missing = missing.filter(x => x === tool || tool.isImportant);
+ missing = missing.filter((x) => x === tool || tool.isImportant);
if (missing.length > 1) {
// Offer the option to install all tools.
installOptions.push('Install All');
}
const msg = `The "${tool.name}" command is not available. Run "go get -v ${getImportPath(tool, goVersion)}" to install.`;
- vscode.window.showInformationMessage(msg, ...installOptions).then(selected => {
+ vscode.window.showInformationMessage(msg, ...installOptions).then((selected) => {
switch (selected) {
case 'Install':
installTools([tool], goVersion);
@@ -295,7 +295,7 @@
}
const goVersion = await getGoVersion();
const updateMsg = `Your version of ${tool.name} appears to be out of date. Please update for an improved experience.`;
- vscode.window.showInformationMessage(updateMsg, 'Update').then(selected => {
+ vscode.window.showInformationMessage(updateMsg, 'Update').then((selected) => {
switch (selected) {
case 'Update':
installTools([tool], goVersion);
@@ -370,7 +370,7 @@
const goVersion = await getGoVersion();
let missing = await getMissingTools(goVersion);
- missing = missing.filter(x => x.isImportant);
+ missing = missing.filter((x) => x.isImportant);
if (missing.length > 0) {
showGoStatus('Analysis Tools Missing', 'go.promptforinstall', 'Not all Go tools are available on the GOPATH');
vscode.commands.registerCommand('go.promptforinstall', () => {
@@ -384,7 +384,7 @@
const disableLabel = 'Disable language server';
const installLabel = 'Install';
vscode.window.showInformationMessage(promptMsg, installLabel, disableLabel)
- .then(selected => {
+ .then((selected) => {
if (selected === installLabel) {
installTools([getTool('gopls')], goVersion)
.then(() => {
@@ -415,10 +415,10 @@
command() {
outputChannel.clear();
outputChannel.appendLine('Below tools are needed for the basic features of the Go extension.');
- missing.forEach(x => outputChannel.appendLine(x.name));
+ missing.forEach((x) => outputChannel.appendLine(x.name));
}
};
- vscode.window.showInformationMessage('Failed to find some of the Go analysis tools. Would you like to install them?', installItem, showItem).then(selection => {
+ vscode.window.showInformationMessage('Failed to find some of the Go analysis tools. Would you like to install them?', installItem, showItem).then((selection) => {
if (selection) {
selection.command();
} else {
@@ -430,12 +430,12 @@
function getMissingTools(goVersion: GoVersion): Promise<Tool[]> {
const keys = getConfiguredTools(goVersion);
- return Promise.all<Tool>(keys.map(tool => new Promise<Tool>((resolve, reject) => {
+ return Promise.all<Tool>(keys.map((tool) => new Promise<Tool>((resolve, reject) => {
const toolPath = getBinPath(tool.name);
- fs.exists(toolPath, exists => {
+ fs.exists(toolPath, (exists) => {
resolve(exists ? null : tool);
});
- }))).then(res => {
- return res.filter(x => x != null);
+ }))).then((res) => {
+ return res.filter((x) => x != null);
});
}
diff --git a/src/goLanguageServer.ts b/src/goLanguageServer.ts
index a4b1dd3..0c0b3f0 100644
--- a/src/goLanguageServer.ts
+++ b/src/goLanguageServer.ts
@@ -48,7 +48,7 @@
// It looks to either the language server or the standard providers for these features.
export async function registerLanguageFeatures(ctx: vscode.ExtensionContext) {
// Subscribe to notifications for changes to the configuration of the language server.
- ctx.subscriptions.push(vscode.workspace.onDidChangeConfiguration(e => watchLanguageServerConfiguration(e)));
+ ctx.subscriptions.push(vscode.workspace.onDidChangeConfiguration((e) => watchLanguageServerConfiguration(e)));
const config = parseLanguageServerConfig();
@@ -208,7 +208,7 @@
// If there was a change in the configuration of the language server,
// then ask the user to reload VS Code.
if (reloadMessage) {
- vscode.window.showInformationMessage(reloadMessage, 'Reload').then(selected => {
+ vscode.window.showInformationMessage(reloadMessage, 'Reload').then((selected) => {
if (selected === 'Reload') {
vscode.commands.executeCommand('workbench.action.reloadWindow');
}
@@ -293,7 +293,7 @@
return true;
}
const tempGopath = getCurrentGoPath(vscode.workspace.workspaceFolders[0].uri);
- return vscode.workspace.workspaceFolders.find(x => tempGopath !== getCurrentGoPath(x.uri)) ? false : true;
+ return vscode.workspace.workspaceFolders.find((x) => tempGopath !== getCurrentGoPath(x.uri)) ? false : true;
}
// registerUsualProviders registers the language feature providers if the language server is not enabled.
@@ -434,7 +434,7 @@
versions.sort(semver.rcompare);
// The first version in the sorted list without a prerelease tag.
- return versions.find(version => !version.prerelease || !version.prerelease.length);
+ return versions.find((version) => !version.prerelease || !version.prerelease.length);
}
async function goplsVersion(goplsPath: string): Promise<string> {
diff --git a/src/goLint.ts b/src/goLint.ts
index 3605443..ca17cdb 100644
--- a/src/goLint.ts
+++ b/src/goLint.ts
@@ -30,11 +30,11 @@
diagnosticsStatusBarItem.text = 'Linting...';
goLint(documentUri, goConfig, scope)
- .then(warnings => {
+ .then((warnings) => {
handleDiagnosticErrors(editor ? editor.document : null, warnings, lintDiagnosticCollection);
diagnosticsStatusBarItem.hide();
})
- .catch(err => {
+ .catch((err) => {
vscode.window.showInformationMessage('Error: ' + err);
diagnosticsStatusBarItem.text = 'Linting Failed';
});
@@ -71,7 +71,7 @@
const lintEnv = Object.assign({}, getToolsEnvVars());
const args: string[] = [];
- lintFlags.forEach(flag => {
+ lintFlags.forEach((flag) => {
// --json is not a valid flag for golint and in gometalinter, it is used to print output in json which we dont want
if (flag === '--json') {
return;
diff --git a/src/goLiveErrors.ts b/src/goLiveErrors.ts
index a6d2cac..c1401e1 100644
--- a/src/goLiveErrors.ts
+++ b/src/goLiveErrors.ts
@@ -87,7 +87,7 @@
// returns a non-zero exit status if the checks fail
const diagnosticMap: Map<string, vscode.Diagnostic[]> = new Map();
- stderr.split('\n').forEach(error => {
+ stderr.split('\n').forEach((error) => {
if (error === null || error.length === 0) {
return;
}
diff --git a/src/goMain.ts b/src/goMain.ts
index 0712741..cfadb93 100644
--- a/src/goMain.ts
+++ b/src/goMain.ts
@@ -58,7 +58,7 @@
const prevGoroot = toolsGoInfo[toolsGopath].goroot;
const currentGoroot: string = process.env['GOROOT'] && process.env['GOROOT'].toLowerCase();
if (prevGoroot && prevGoroot.toLowerCase() !== currentGoroot) {
- vscode.window.showInformationMessage(`Your current goroot (${currentGoroot}) is different than before (${prevGoroot}), a few Go tools may need recompiling`, updateToolsCmdText).then(selected => {
+ vscode.window.showInformationMessage(`Your current goroot (${currentGoroot}) is different than before (${prevGoroot}), a few Go tools may need recompiling`, updateToolsCmdText).then((selected) => {
if (selected === updateToolsCmdText) {
installAllTools(true);
}
@@ -71,7 +71,7 @@
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 => {
+ 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);
}
@@ -303,7 +303,7 @@
goGenerateTests.toggleTestFile();
}));
- ctx.subscriptions.push(vscode.commands.registerCommand('go.debug.startSession', config => {
+ 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);
@@ -330,8 +330,8 @@
command: 'workbench.action.showAllSymbols',
title: 'Go to Symbol in Workspace...'
});
- vscode.window.showQuickPick(extCommands.map(x => x.title)).then(cmd => {
- const selectedCmd = extCommands.find(x => x.title === cmd);
+ vscode.window.showQuickPick(extCommands.map((x) => x.title)).then((cmd) => {
+ const selectedCmd = extCommands.find((x) => x.title === cmd);
if (selectedCmd) {
vscode.commands.executeCommand(selectedCmd.command);
}
@@ -378,18 +378,18 @@
lintDiagnosticCollection.clear();
vetDiagnosticCollection.clear();
check(document.uri, goConfig)
- .then(results => {
- results.forEach(result => {
+ .then((results) => {
+ results.forEach((result) => {
handleDiagnosticErrors(document, result.errors, result.diagnosticCollection);
});
})
- .catch(err => {
+ .catch((err) => {
vscode.window.showInformationMessage('Error: ' + err);
});
}
function addOnSaveTextDocumentListeners(ctx: vscode.ExtensionContext) {
- vscode.workspace.onDidSaveTextDocument(document => {
+ vscode.workspace.onDidSaveTextDocument((document) => {
if (document.languageId !== 'go') {
return;
}
@@ -398,14 +398,14 @@
const ignoreActiveDebugWarningKey = 'ignoreActiveDebugWarningKey';
const ignoreActiveDebugWarning = getFromGlobalState(ignoreActiveDebugWarningKey);
if (!ignoreActiveDebugWarning) {
- vscode.window.showWarningMessage('A debug session is currently active. Changes to your Go files may result in unexpected behaviour.', neverAgain).then(result => {
+ vscode.window.showWarningMessage('A debug session is currently active. Changes to your Go files may result in unexpected behaviour.', neverAgain).then((result) => {
if (result === neverAgain) {
updateGlobalState(ignoreActiveDebugWarningKey, true);
}
});
}
}
- if (vscode.window.visibleTextEditors.some(e => e.document.fileName === document.fileName)) {
+ if (vscode.window.visibleTextEditors.some((e) => e.document.fileName === document.fileName)) {
runBuilds(document, getGoConfig(document.uri));
}
diff --git a/src/goModifytags.ts b/src/goModifytags.ts
index 371de7e..73e910e 100644
--- a/src/goModifytags.ts
+++ b/src/goModifytags.ts
@@ -113,11 +113,11 @@
return vscode.window.showInputBox({
value: tags,
prompt: 'Enter comma separated tag names'
- }).then(inputTags => {
+ }).then((inputTags) => {
return vscode.window.showInputBox({
value: options,
prompt: 'Enter comma separated options'
- }).then(inputOptions => {
+ }).then((inputOptions) => {
return [inputTags, inputOptions, transformValue];
});
});
@@ -137,7 +137,7 @@
return;
}
const output = <GomodifytagsOutput>JSON.parse(stdout);
- vscode.window.activeTextEditor.edit(editBuilder => {
+ vscode.window.activeTextEditor.edit((editBuilder) => {
editBuilder.replace(new vscode.Range(output.start - 1, 0, output.end, 0), output.lines.join('\n') + '\n');
});
});
diff --git a/src/goModules.ts b/src/goModules.ts
index 76fa93f..8723c2a 100644
--- a/src/goModules.ts
+++ b/src/goModules.ts
@@ -23,7 +23,7 @@
}
const env = getToolsEnvVars();
GO111MODULE = env['GO111MODULE'];
- return new Promise(resolve => {
+ return new Promise((resolve) => {
cp.execFile(goExecutable, ['env', 'GOMOD'], { cwd: folderPath, env: getToolsEnvVars() }, (err, stdout) => {
if (err) {
console.warn(`Error when running go env GOMOD: ${err}`);
@@ -36,7 +36,7 @@
}
export function isModSupported(fileuri: vscode.Uri): Promise<boolean> {
- return getModFolderPath(fileuri).then(modPath => !!modPath);
+ return getModFolderPath(fileuri).then((modPath) => !!modPath);
}
export const packagePathToGoModPathMap: {[key: string]: string} = {};
@@ -177,7 +177,7 @@
console.warn(`Failed to run "go list" to find current package as the "go" binary cannot be found in either GOROOT(${process.env['GOROOT']}) or PATH(${envPath})`);
return;
}
- return new Promise<string>(resolve => {
+ return new Promise<string>((resolve) => {
const childProcess = cp.spawn(goRuntimePath, ['list'], { cwd, env: getToolsEnvVars() });
const chunks: any[] = [];
childProcess.stdout.on('data', (stdout) => {
@@ -186,7 +186,7 @@
childProcess.on('close', () => {
// Ignore lines that are empty or those that have logs about updating the module cache
- const pkgs = chunks.join('').toString().split('\n').filter(line => line && line.indexOf(' ') === -1);
+ const pkgs = chunks.join('').toString().split('\n').filter((line) => line && line.indexOf(' ') === -1);
if (pkgs.length !== 1) {
resolve();
return;
diff --git a/src/goOutline.ts b/src/goOutline.ts
index e5c7e37..3bcd46a 100644
--- a/src/goOutline.ts
+++ b/src/goOutline.ts
@@ -92,7 +92,7 @@
options.document = null;
}
p = null;
- return runGoOutline(options, token).then(results => {
+ return runGoOutline(options, token).then((results) => {
return resolve(results);
});
}
@@ -130,7 +130,7 @@
byteOffsetToDocumentOffset: (byteOffset: number) => number): vscode.DocumentSymbol[] {
const symbols: vscode.DocumentSymbol[] = [];
- (decls || []).forEach(decl => {
+ (decls || []).forEach((decl) => {
if (!includeImports && decl.type === 'import') {
return;
}
diff --git a/src/goPackages.ts b/src/goPackages.ts
index a5c13fe..73799ed 100644
--- a/src/goPackages.ts
+++ b/src/goPackages.ts
@@ -50,9 +50,9 @@
const chunks: any[] = [];
const errchunks: any[] = [];
let err: any;
- cmd.stdout.on('data', d => chunks.push(d));
- cmd.stderr.on('data', d => errchunks.push(d));
- cmd.on('error', e => err = e);
+ cmd.stdout.on('data', (d) => chunks.push(d));
+ cmd.stderr.on('data', (d) => errchunks.push(d));
+ cmd.on('error', (e) => err = e);
cmd.on('close', () => {
const pkgs = new Map<string, PackageInfo>();
if (err && err.code === 'ENOENT') {
@@ -64,7 +64,7 @@
if (errorMsg.startsWith('flag provided but not defined: -workDir')) {
promptForUpdatingTool('gopkgs');
// fallback to gopkgs without -workDir
- return gopkgs().then(result => resolve(result));
+ return gopkgs().then((result) => resolve(result));
}
console.log(`Running gopkgs failed with "${errorMsg}"\nCheck if you can run \`gopkgs -format {{.Name}};{{.ImportPath}}\` in a terminal successfully.`);
@@ -75,7 +75,7 @@
if (output.indexOf(';') === -1) {
// User might be using the old gopkgs tool, prompt to update
promptForUpdatingTool('gopkgs');
- output.split('\n').forEach(pkgPath => {
+ output.split('\n').forEach((pkgPath) => {
if (!pkgPath || !pkgPath.trim()) {
return;
}
@@ -273,7 +273,7 @@
const version = await getGoVersion();
const vendorAlreadyExcluded = version.gt('1.8');
- lines.forEach(line => {
+ lines.forEach((line) => {
const matches = line.match(pkgToFolderMappingRegex);
if (!matches || matches.length !== 3) {
return;
diff --git a/src/goPath.ts b/src/goPath.ts
index 24a289f..5f172d3 100644
--- a/src/goPath.ts
+++ b/src/goPath.ts
@@ -129,7 +129,7 @@
try {
const buffer = stripBOM(fs.readFileSync(path, 'utf8'));
- buffer.split('\n').forEach(line => {
+ buffer.split('\n').forEach((line) => {
const r = line.match(/^\s*([\w\.\-]+)\s*=\s*(.*)?\s*$/);
if (r !== null) {
let value = r[2] || '';
diff --git a/src/goPlayground.ts b/src/goPlayground.ts
index dd03189..c3e5162 100644
--- a/src/goPlayground.ts
+++ b/src/goPlayground.ts
@@ -32,7 +32,7 @@
const code = selection.isEmpty
? editor.document.getText()
: editor.document.getText(selection);
- goPlay(code, getGoConfig(editor.document.uri).get('playground')).then(result => {
+ goPlay(code, getGoConfig(editor.document.uri).get('playground')).then((result) => {
outputChannel.append(result);
}, (e: string) => {
if (e) {
@@ -42,7 +42,7 @@
};
export function goPlay(code: string, goConfig: vscode.WorkspaceConfiguration): Thenable<string> {
- const cliArgs = Object.keys(goConfig).map(key => `-${key}=${goConfig[key]}`);
+ const cliArgs = Object.keys(goConfig).map((key) => `-${key}=${goConfig[key]}`);
const binaryLocation = getBinPath(TOOL_CMD_NAME);
return new Promise<string>((resolve, reject) => {
diff --git a/src/goReferencesCodelens.ts b/src/goReferencesCodelens.ts
index 43ef921..8bc545f 100644
--- a/src/goReferencesCodelens.ts
+++ b/src/goReferencesCodelens.ts
@@ -40,8 +40,8 @@
return Promise.resolve([]);
}
- return this.provideDocumentSymbols(document, token).then(symbols => {
- return symbols.map(symbol => {
+ return this.provideDocumentSymbols(document, token).then((symbols) => {
+ return symbols.map((symbol) => {
let position = symbol.range.start;
// Add offset for functions as go-outline returns position at the keyword func instead of func name
@@ -66,7 +66,7 @@
includeDeclaration: false
};
const referenceProvider = new GoReferenceProvider();
- return referenceProvider.provideReferences(codeLens.document, codeLens.range.start, options, token).then(references => {
+ return referenceProvider.provideReferences(codeLens.document, codeLens.range.start, options, token).then((references) => {
codeLens.command = {
title: references.length === 1
? '1 reference'
@@ -75,7 +75,7 @@
arguments: [codeLens.document.uri, codeLens.range.start, references]
};
return codeLens;
- }, err => {
+ }, (err) => {
console.log(err);
codeLens.command = {
title: 'Error finding references',
@@ -89,7 +89,7 @@
const symbolProvider = new GoDocumentSymbolProvider();
const isTestFile = document.fileName.endsWith('_test.go');
const symbols = await symbolProvider.provideDocumentSymbols(document, token);
- return symbols[0].children.filter(symbol => {
+ return symbols[0].children.filter((symbol) => {
if (symbol.kind === vscode.SymbolKind.Interface) {
return true;
}
diff --git a/src/goRunTestCodelens.ts b/src/goRunTestCodelens.ts
index 53b40c0..4f777a9 100644
--- a/src/goRunTestCodelens.ts
+++ b/src/goRunTestCodelens.ts
@@ -68,7 +68,7 @@
command: 'go.test.file'
})
];
- if (symbols[0].children.some(sym => sym.kind === vscode.SymbolKind.Function && this.benchmarkRegex.test(sym.name))) {
+ if (symbols[0].children.some((sym) => sym.kind === vscode.SymbolKind.Function && this.benchmarkRegex.test(sym.name))) {
packageCodeLens.push(new CodeLens(range, {
title: 'run package benchmarks',
command: 'go.benchmark.package'
@@ -83,8 +83,8 @@
private async getCodeLensForFunctions(vsConfig: vscode.WorkspaceConfiguration, document: TextDocument, token: CancellationToken): Promise<CodeLens[]> {
const codelens: CodeLens[] = [];
- const testPromise = getTestFunctions(document, token).then(testFunctions => {
- testFunctions.forEach(func => {
+ const testPromise = getTestFunctions(document, token).then((testFunctions) => {
+ testFunctions.forEach((func) => {
const runTestCmd: Command = {
title: 'run test',
command: 'go.test.cursor',
@@ -103,8 +103,8 @@
});
});
- const benchmarkPromise = getBenchmarkFunctions(document, token).then(benchmarkFunctions => {
- benchmarkFunctions.forEach(func => {
+ const benchmarkPromise = getBenchmarkFunctions(document, token).then((benchmarkFunctions) => {
+ benchmarkFunctions.forEach((func) => {
const runBenchmarkCmd: Command = {
title: 'run benchmark',
command: 'go.benchmark.cursor',
diff --git a/src/goSignature.ts b/src/goSignature.ts
index 0a211e1..5ab33dc 100755
--- a/src/goSignature.ts
+++ b/src/goSignature.ts
@@ -60,7 +60,7 @@
si = new SignatureInformation(declarationText, res.doc);
sig = declarationText.substring(res.name.length);
}
- si.parameters = getParametersAndReturnType(sig).params.map(paramText => new ParameterInformation(paramText));
+ si.parameters = getParametersAndReturnType(sig).params.map((paramText) => new ParameterInformation(paramText));
result.signatures = [si];
result.activeSignature = 0;
result.activeParameter = Math.min(theCall.commas.length, si.parameters.length - 1);
diff --git a/src/goStatus.ts b/src/goStatus.ts
index 3d4c0fe..e7fc24c 100644
--- a/src/goStatus.ts
+++ b/src/goStatus.ts
@@ -31,7 +31,7 @@
}
if (editor) {
- isModSupported(editor.document.uri).then(isMod => {
+ isModSupported(editor.document.uri).then((isMod) => {
if (isMod) {
statusBarItemModule.show();
} else {
diff --git a/src/goSuggest.ts b/src/goSuggest.ts
index ec79ff0..ecd3a78 100644
--- a/src/goSuggest.ts
+++ b/src/goSuggest.ts
@@ -73,7 +73,7 @@
}
public provideCompletionItems(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Thenable<vscode.CompletionList> {
- return this.provideCompletionItemsInternal(document, position, token, getGoConfig(document.uri)).then(result => {
+ return this.provideCompletionItemsInternal(document, position, token, getGoConfig(document.uri)).then((result) => {
if (!result) {
return new vscode.CompletionList([], false);
}
@@ -96,10 +96,10 @@
return;
}
- return runGodoc(path.dirname(item.fileName), item.package || path.dirname(item.fileName), item.receiver, item.label, token).then(doc => {
+ return runGodoc(path.dirname(item.fileName), item.package || path.dirname(item.fileName), item.receiver, item.label, token).then((doc) => {
item.documentation = new vscode.MarkdownString(doc);
return item;
- }).catch(err => {
+ }).catch((err) => {
console.log(err);
return item;
});
@@ -154,7 +154,7 @@
let inputText = document.getText();
const includeUnimportedPkgs = autocompleteUnimportedPackages && !inString && currentWord.length > 0;
- return this.runGoCode(document, filename, inputText, offset, inString, position, lineText, currentWord, includeUnimportedPkgs, config).then(suggestions => {
+ return this.runGoCode(document, filename, inputText, offset, inString, position, lineText, currentWord, includeUnimportedPkgs, config).then((suggestions) => {
// gocode does not suggest keywords, so we have to do it
suggestions.push(...getKeywordCompletions(currentWord));
@@ -172,18 +172,18 @@
offset += textToAdd.length;
// Now that we have the package imported in the inputText, run gocode again
- return this.runGoCode(document, filename, inputText, offset, inString, position, lineText, currentWord, false, config).then(newsuggestions => {
+ return this.runGoCode(document, filename, inputText, offset, inString, position, lineText, currentWord, false, config).then((newsuggestions) => {
// Since the new suggestions are due to the package that we imported,
// add additionalTextEdits to do the same in the actual document in the editor
// We use additionalTextEdits instead of command so that 'useCodeSnippetsOnFunctionSuggest' feature continues to work
- newsuggestions.forEach(item => {
+ newsuggestions.forEach((item) => {
item.additionalTextEdits = getTextEditForAddImport(pkgPath[0]);
});
resolve(newsuggestions);
}, reject);
}
if (pkgPath.length > 1) {
- pkgPath.forEach(pkg => {
+ pkgPath.forEach((pkg) => {
const item = new vscode.CompletionItem(
`${lineTillCurrentPosition.replace('.', '').trim()} (${pkg})`,
vscode.CompletionItemKind.Module
@@ -244,16 +244,16 @@
// Spawn `gocode` process
const p = cp.spawn(gocode, [...this.gocodeFlags, 'autocomplete', filename, '' + offset], { env });
- p.stdout.on('data', data => stdout += data);
- p.stderr.on('data', data => stderr += data);
- p.on('error', err => {
+ p.stdout.on('data', (data) => stdout += data);
+ p.stderr.on('data', (data) => stderr += data);
+ p.on('error', (err) => {
if (err && (<any>err).code === 'ENOENT') {
promptForMissingTool(gocodeName);
return reject();
}
return reject(err);
});
- p.on('close', code => {
+ p.on('close', (code) => {
try {
if (code !== 0) {
if (stderr.indexOf('rpc: can\'t find service Server.AutoComplete') > -1 && !this.killMsgShown) {
@@ -387,9 +387,9 @@
if (this.previousFile !== currentFile && this.previousFileDir !== path.dirname(currentFile)) {
this.previousFile = currentFile;
this.previousFileDir = path.dirname(currentFile);
- checkModSupport = isModSupported(fileuri).then(result => this.isGoMod = result);
+ checkModSupport = isModSupported(fileuri).then((result) => this.isGoMod = result);
}
- const setPkgsList = getImportablePackages(currentFile, true).then(pkgMap => { this.pkgsList = pkgMap; });
+ const setPkgsList = getImportablePackages(currentFile, true).then((pkgMap) => { this.pkgsList = pkgMap; });
if (!this.setGocodeOptions) {
return Promise.all([checkModSupport, setPkgsList]).then(() => { return; });
@@ -402,7 +402,7 @@
cp.execFile(gocode, ['set'], { env }, (err, stdout, stderr) => {
if (err && stdout.startsWith('gocode: unknown subcommand:')) {
if (goConfig['gocodePackageLookupMode'] === 'gb' && this.globalState && !this.globalState.get(gocodeNoSupportForgbMsgKey)) {
- vscode.window.showInformationMessage('The go.gocodePackageLookupMode setting for gb will not be honored as github.com/mdempskey/gocode doesnt support it yet.', 'Don\'t show again').then(selected => {
+ vscode.window.showInformationMessage('The go.gocodePackageLookupMode setting for gb will not be honored as github.com/mdempskey/gocode doesnt support it yet.', 'Don\'t show again').then((selected) => {
if (selected === 'Don\'t show again') {
this.globalState.update(gocodeNoSupportForgbMsgKey, true);
}
@@ -513,7 +513,7 @@
return [];
}
const completionItems: vscode.CompletionItem[] = [];
- goKeywords.forEach(keyword => {
+ goKeywords.forEach((keyword) => {
if (keyword.startsWith(currentWord)) {
completionItems.push(new vscode.CompletionItem(keyword, vscode.CompletionItemKind.Keyword));
}
@@ -568,7 +568,7 @@
}
const pkgNames = await guessPackageNameFromFile(document.fileName);
- const suggestions = pkgNames.map(pkgName => {
+ const suggestions = pkgNames.map((pkgName) => {
const packageItem = new vscode.CompletionItem('package ' + pkgName);
packageItem.kind = vscode.CompletionItemKind.Snippet;
packageItem.insertText = 'package ' + pkgName + '\r\n\r\n';
diff --git a/src/goSymbol.ts b/src/goSymbol.ts
index 61d6b25..fd4d0eb 100644
--- a/src/goSymbol.ts
+++ b/src/goSymbol.ts
@@ -33,7 +33,7 @@
public provideWorkspaceSymbols(query: string, token: vscode.CancellationToken): Thenable<vscode.SymbolInformation[]> {
const convertToCodeSymbols = (decls: GoSymbolDeclaration[], symbols: vscode.SymbolInformation[]): void => {
- decls.forEach(decl => {
+ decls.forEach((decl) => {
let kind: vscode.SymbolKind;
if (decl.kind !== '') {
kind = this.goKindToCodeKind[decl.kind];
@@ -56,7 +56,7 @@
return;
}
- return getWorkspaceSymbols(root, query, token, goConfig).then(results => {
+ return getWorkspaceSymbols(root, query, token, goConfig).then((results) => {
const symbols: vscode.SymbolInformation[] = [];
convertToCodeSymbols(results, symbols);
return symbols;
diff --git a/src/goTest.ts b/src/goTest.ts
index 43ac695..20af060 100644
--- a/src/goTest.ts
+++ b/src/goTest.ts
@@ -44,8 +44,8 @@
// Otherwise find any test function containing the cursor.
const testFunctionName = args && args.functionName
? args.functionName
- : testFunctions.filter(func => func.range.contains(editor.selection.start))
- .map(el => el.name)[0];
+ : testFunctions.filter((func) => func.range.contains(editor.selection.start))
+ .map((el) => el.name)[0];
if (!testFunctionName) {
vscode.window.showInformationMessage('No test function found at cursor.');
return;
@@ -70,7 +70,7 @@
async function runTestAtCursor(editor: vscode.TextEditor, testFunctionName: string, testFunctions: vscode.DocumentSymbol[], goConfig: vscode.WorkspaceConfiguration, cmd: TestAtCursorCmd, args: any) {
const testConfigFns = cmd !== 'benchmark' && extractInstanceTestName(testFunctionName)
- ? [testFunctionName, ...findAllTestSuiteRuns(editor.document, testFunctions).map(t => t.name)]
+ ? [testFunctionName, ...findAllTestSuiteRuns(editor.document, testFunctions).map((t) => t.name)]
: [testFunctionName];
const isMod = await isModSupported(editor.document.uri);
@@ -98,7 +98,7 @@
const buildFlags = tags ? ['-tags', tags] : [];
const flagsFromConfig = getTestFlags(goConfig);
let foundArgsFlag = false;
- flagsFromConfig.forEach(x => {
+ flagsFromConfig.forEach((x) => {
if (foundArgsFlag) {
args.push(x);
return;
@@ -174,9 +174,9 @@
// Remember this config as the last executed test.
lastTestConfig = testConfig;
- isModSupported(workspaceUri).then(isMod => {
+ isModSupported(workspaceUri).then((isMod) => {
testConfig.isMod = isMod;
- goTest(testConfig).then(null, err => {
+ goTest(testConfig).then(null, (err) => {
console.error(err);
});
});
@@ -203,12 +203,12 @@
const isMod = await isModSupported(editor.document.uri);
return editor.document.save().then(() => {
- return getFunctions(editor.document, null).then(testFunctions => {
+ return getFunctions(editor.document, null).then((testFunctions) => {
const testConfig: TestConfig = {
goConfig,
dir: path.dirname(editor.document.fileName),
flags: getTestFlags(goConfig, args),
- functions: testFunctions.map(sym => sym.name),
+ functions: testFunctions.map((sym) => sym.name),
isBenchmark,
isMod,
applyCodeCoverage: goConfig.get<boolean>('coverOnSingleTestFile')
@@ -217,7 +217,7 @@
lastTestConfig = testConfig;
return goTest(testConfig);
});
- }).then(null, err => {
+ }).then(null, (err) => {
console.error(err);
return Promise.resolve(false);
});
@@ -231,7 +231,7 @@
vscode.window.showInformationMessage('No test has been recently executed.');
return;
}
- goTest(lastTestConfig).then(null, err => {
+ goTest(lastTestConfig).then(null, (err) => {
console.error(err);
});
}
diff --git a/src/goTools.ts b/src/goTools.ts
index f596f04..635cc79 100644
--- a/src/goTools.ts
+++ b/src/goTools.ts
@@ -47,7 +47,7 @@
}
export function containsString(tools: Tool[], toolName: string): boolean {
- return tools.some(tool => tool.name === toolName);
+ return tools.some((tool) => tool.name === toolName);
}
export function getTool(name: string): Tool {
diff --git a/src/goTypeDefinition.ts b/src/goTypeDefinition.ts
index 54a3783..a762261 100644
--- a/src/goTypeDefinition.ts
+++ b/src/goTypeDefinition.ts
@@ -74,14 +74,14 @@
}
// Fall back to position of declaration
- return definitionLocation(document, position, null, false, token).then(definitionInfo => {
+ return definitionLocation(document, position, null, false, token).then((definitionInfo) => {
if (definitionInfo == null || definitionInfo.file == null) {
return null;
}
const definitionResource = vscode.Uri.file(definitionInfo.file);
const pos = new vscode.Position(definitionInfo.line, definitionInfo.column);
resolve(new vscode.Location(definitionResource, pos));
- }, err => {
+ }, (err) => {
const miss = parseMissingError(err);
if (miss[0]) {
promptForMissingTool(miss[1]);
@@ -93,7 +93,7 @@
}
const results: vscode.Location[] = [];
- guruOutput.value.typespos.forEach(ref => {
+ guruOutput.value.typespos.forEach((ref) => {
const match = /^(.*):(\d+):(\d+)/.exec(ref.objpos);
if (!match) {
return;
diff --git a/src/goVet.ts b/src/goVet.ts
index 25c7c92..724fd92 100644
--- a/src/goVet.ts
+++ b/src/goVet.ts
@@ -31,11 +31,11 @@
diagnosticsStatusBarItem.text = 'Vetting...';
goVet(documentUri, goConfig, vetWorkspace)
- .then(warnings => {
+ .then((warnings) => {
handleDiagnosticErrors(editor ? editor.document : null, warnings, vetDiagnosticCollection);
diagnosticsStatusBarItem.hide();
})
- .catch(err => {
+ .catch((err) => {
vscode.window.showInformationMessage('Error: ' + err);
diagnosticsStatusBarItem.text = 'Vetting Failed';
});
@@ -69,7 +69,7 @@
const vetEnv = Object.assign({}, getToolsEnvVars());
const args: string[] = [];
- vetFlags.forEach(flag => {
+ vetFlags.forEach((flag) => {
if (flag.startsWith('--vettool=') || flag.startsWith('-vettool=')) {
let vetToolPath = flag.substr(flag.indexOf('=') + 1).trim();
if (!vetToolPath) {
diff --git a/src/testUtils.ts b/src/testUtils.ts
index 5d5a476..a0d185b 100644
--- a/src/testUtils.ts
+++ b/src/testUtils.ts
@@ -86,15 +86,15 @@
}
}
- Object.keys(fileEnv).forEach(key => envVars[key] = typeof fileEnv[key] === 'string' ? resolvePath(fileEnv[key]) : fileEnv[key]);
- Object.keys(testEnvConfig).forEach(key => envVars[key] = typeof testEnvConfig[key] === 'string' ? resolvePath(testEnvConfig[key]) : testEnvConfig[key]);
+ Object.keys(fileEnv).forEach((key) => envVars[key] = typeof fileEnv[key] === 'string' ? resolvePath(fileEnv[key]) : fileEnv[key]);
+ Object.keys(testEnvConfig).forEach((key) => envVars[key] = typeof testEnvConfig[key] === 'string' ? resolvePath(testEnvConfig[key]) : testEnvConfig[key]);
return envVars;
}
export function getTestFlags(goConfig: vscode.WorkspaceConfiguration, args?: any): string[] {
let testFlags: string[] = goConfig['testFlags'] || goConfig['buildFlags'] || [];
- testFlags = testFlags.map(x => resolvePath(x)); // Use copy of the flags, dont pass the actual object from config
+ testFlags = testFlags.map((x) => resolvePath(x)); // Use copy of the flags, dont pass the actual object from config
return (args && args.hasOwnProperty('flags') && Array.isArray(args['flags'])) ? args['flags'] : testFlags;
}
@@ -112,10 +112,10 @@
const documentSymbolProvider = new GoDocumentSymbolProvider(true);
return documentSymbolProvider
.provideDocumentSymbols(doc, token)
- .then(symbols => symbols[0].children)
- .then(symbols => {
- const testify = symbols.some(sym => sym.kind === vscode.SymbolKind.Namespace && sym.name === '"github.com/stretchr/testify/suite"');
- return symbols.filter(sym =>
+ .then((symbols) => symbols[0].children)
+ .then((symbols) => {
+ const testify = symbols.some((sym) => sym.kind === vscode.SymbolKind.Namespace && sym.name === '"github.com/stretchr/testify/suite"');
+ return symbols.filter((sym) =>
sym.kind === vscode.SymbolKind.Function
&& (testFuncRegex.test(sym.name) || (testify && testMethodRegex.test(sym.name)))
);
@@ -149,7 +149,7 @@
const instanceMethod = extractInstanceTestName(testFunctionName);
if (instanceMethod) {
const testFns = findAllTestSuiteRuns(document, testFunctions);
- const testSuiteRuns = ['-test.run', `^${testFns.map(t => t.name).join('|')}$`];
+ const testSuiteRuns = ['-test.run', `^${testFns.map((t) => t.name).join('|')}$`];
const testSuiteTests = ['-testify.m', `^${instanceMethod}$`];
return [...testSuiteRuns, ...testSuiteTests];
} else {
@@ -164,9 +164,9 @@
*/
export function findAllTestSuiteRuns(doc: vscode.TextDocument, allTests: vscode.DocumentSymbol[]): vscode.DocumentSymbol[] {
// get non-instance test functions
- const testFunctions = allTests.filter(t => !testMethodRegex.test(t.name));
+ const testFunctions = allTests.filter((t) => !testMethodRegex.test(t.name));
// filter further to ones containing suite.Run()
- return testFunctions.filter(t => doc.getText(t.range).includes('suite.Run('));
+ return testFunctions.filter((t) => doc.getText(t.range).includes('suite.Run('));
}
/**
@@ -179,9 +179,9 @@
const documentSymbolProvider = new GoDocumentSymbolProvider();
return documentSymbolProvider
.provideDocumentSymbols(doc, token)
- .then(symbols => symbols[0].children)
- .then(symbols =>
- symbols.filter(sym =>
+ .then((symbols) => symbols[0].children)
+ .then((symbols) =>
+ symbols.filter((sym) =>
sym.kind === vscode.SymbolKind.Function
&& benchmarkRegex.test(sym.name))
);
@@ -239,12 +239,12 @@
targets = ['./...'];
pkgMapPromise = getNonVendorPackages(testconfig.dir); // We need the mapping to get absolute paths for the files in the test output
} else {
- pkgMapPromise = getGoVersion().then(goVersion => {
+ pkgMapPromise = getGoVersion().then((goVersion) => {
if (goVersion.gt('1.8')) {
targets = ['./...'];
return null; // We dont need mapping, as we can derive the absolute paths from package path
}
- return getNonVendorPackages(testconfig.dir).then(pkgMap => {
+ return getNonVendorPackages(testconfig.dir).then((pkgMap) => {
targets = Array.from(pkgMap.keys());
return pkgMap; // We need the individual package paths to pass to `go test`
});
@@ -298,30 +298,30 @@
if (result && (pkgMap.has(result[2]) || currentGoWorkspace)) {
const packageNameArr = result[2].split('/');
const baseDir = pkgMap.get(result[2]) || path.join(currentGoWorkspace, ...packageNameArr);
- testResultLines.forEach(line => outputChannel.appendLine(expandFilePathInOutput(line, baseDir)));
+ testResultLines.forEach((line) => outputChannel.appendLine(expandFilePathInOutput(line, baseDir)));
testResultLines.splice(0);
}
};
// go test emits test results on stdout, which contain file names relative to the package under test
- outBuf.onLine(line => processTestResultLine(line));
- outBuf.onDone(last => {
+ outBuf.onLine((line) => processTestResultLine(line));
+ outBuf.onDone((last) => {
if (last) {
processTestResultLine(last);
}
// If there are any remaining test result lines, emit them to the output channel.
if (testResultLines.length > 0) {
- testResultLines.forEach(line => outputChannel.appendLine(line));
+ testResultLines.forEach((line) => outputChannel.appendLine(line));
}
});
// go test emits build errors on stderr, which contain paths relative to the cwd
- errBuf.onLine(line => outputChannel.appendLine(expandFilePathInOutput(line, testconfig.dir)));
- errBuf.onDone(last => last && outputChannel.appendLine(expandFilePathInOutput(last, testconfig.dir)));
+ errBuf.onLine((line) => outputChannel.appendLine(expandFilePathInOutput(line, testconfig.dir)));
+ errBuf.onDone((last) => last && outputChannel.appendLine(expandFilePathInOutput(last, testconfig.dir)));
- tp.stdout.on('data', chunk => outBuf.append(chunk.toString()));
- tp.stderr.on('data', chunk => errBuf.append(chunk.toString()));
+ tp.stdout.on('data', (chunk) => outBuf.append(chunk.toString()));
+ tp.stderr.on('data', (chunk) => errBuf.append(chunk.toString()));
statusBarItem.show();
@@ -351,7 +351,7 @@
runningTestProcesses.push(tp);
- }, err => {
+ }, (err) => {
outputChannel.appendLine(`Error: ${testType} failed.`);
outputChannel.appendLine(err);
resolve(false);
@@ -375,7 +375,7 @@
*/
export function cancelRunningTests(): Thenable<boolean> {
return new Promise<boolean>((resolve, reject) => {
- runningTestProcesses.forEach(tp => {
+ runningTestProcesses.forEach((tp) => {
tp.kill(sendSignal);
});
// All processes are now dead. Empty the array to prepare for the next run.
@@ -408,10 +408,10 @@
params = ['-bench', util.format('^(%s)$', testconfig.functions.join('|'))];
} else {
let testFunctions = testconfig.functions;
- let testifyMethods = testFunctions.filter(fn => testMethodRegex.test(fn));
+ let testifyMethods = testFunctions.filter((fn) => testMethodRegex.test(fn));
if (testifyMethods.length > 0) {
// filter out testify methods
- testFunctions = testFunctions.filter(fn => !testMethodRegex.test(fn));
+ testFunctions = testFunctions.filter((fn) => !testMethodRegex.test(fn));
testifyMethods = testifyMethods.map(extractInstanceTestName);
}
diff --git a/src/util.ts b/src/util.ts
index 1bef62b..178ca9d 100644
--- a/src/util.ts
+++ b/src/util.ts
@@ -329,7 +329,7 @@
*/
export function isGoPathSet(): boolean {
if (!getCurrentGoPath()) {
- vscode.window.showInformationMessage('Set GOPATH environment variable and restart VS Code or set GOPATH in Workspace settings', 'Set GOPATH in Workspace Settings').then(selected => {
+ vscode.window.showInformationMessage('Set GOPATH environment variable and restart VS Code or set GOPATH in Workspace settings', 'Set GOPATH in Workspace Settings').then((selected) => {
if (selected === 'Set GOPATH in Workspace Settings') {
vscode.commands.executeCommand('workbench.action.openWorkspaceSettings');
}
@@ -409,7 +409,7 @@
const envVars = Object.assign({}, process.env, gopath ? { GOPATH: gopath } : {});
if (toolsEnvVars && typeof toolsEnvVars === 'object') {
- Object.keys(toolsEnvVars).forEach(key => envVars[key] = typeof toolsEnvVars[key] === 'string' ? resolvePath(toolsEnvVars[key]) : toolsEnvVars[key]);
+ Object.keys(toolsEnvVars).forEach((key) => envVars[key] = typeof toolsEnvVars[key] === 'string' ? resolvePath(toolsEnvVars[key]) : toolsEnvVars[key]);
}
return envVars;
@@ -490,11 +490,11 @@
}
private fireLine(line: string) {
- this.lineListeners.forEach(listener => listener(line));
+ this.lineListeners.forEach((listener) => listener(line));
}
private fireDone(last: string) {
- this.lastListeners.forEach(listener => listener(last));
+ this.lastListeners.forEach((listener) => listener(last));
}
onLine(listener: (line: string) => void) {
@@ -578,7 +578,7 @@
const directoryPath = path.dirname(filePath);
const dirName = path.basename(directoryPath);
let segments = dirName.split(/[\.-]/);
- segments = segments.filter(val => val !== 'go');
+ segments = segments.filter((val) => val !== 'go');
if (segments.length === 0 || !/[a-zA-Z_]\w*/.test(segments[segments.length - 1])) {
return reject();
@@ -712,7 +712,7 @@
diagnosticCollection.clear();
const diagnosticMap: Map<string, vscode.Diagnostic[]> = new Map();
- errors.forEach(error => {
+ errors.forEach((error) => {
const canonicalFile = vscode.Uri.file(error.file).toString();
let startColumn = 0;
let endColumn = 1;
@@ -760,8 +760,8 @@
}
function deDupeDiagnostics(buildDiagnostics: vscode.Diagnostic[], otherDiagnostics: vscode.Diagnostic[]): vscode.Diagnostic[] {
- const buildDiagnosticsLines = buildDiagnostics.map(x => x.range.start.line);
- return otherDiagnostics.filter(x => buildDiagnosticsLines.indexOf(x.range.start.line) === -1);
+ const buildDiagnosticsLines = buildDiagnostics.map((x) => x.range.start.line);
+ return otherDiagnostics.filter((x) => buildDiagnosticsLines.indexOf(x.range.start.line) === -1);
}
function mapSeverityToVSCodeSeverity(sev: string): vscode.DiagnosticSeverity {
@@ -851,7 +851,7 @@
export function rmdirRecursive(dir: string) {
if (fs.existsSync(dir)) {
- fs.readdirSync(dir).forEach(file => {
+ fs.readdirSync(dir).forEach((file) => {
const relPath = path.join(dir, file);
if (fs.lstatSync(relPath).isDirectory()) {
rmdirRecursive(dir);
@@ -909,7 +909,7 @@
}
const getCurrentPackagePromise = path.isAbsolute(packagePath) ? getCurrentPackage(packagePath) : Promise.resolve(packagePath);
- return getCurrentPackagePromise.then(packageImportPath => {
+ return getCurrentPackagePromise.then((packageImportPath) => {
return new Promise<string>((resolve, reject) => {
if (receiver) {
receiver = receiver.replace(/^\*/, '');
diff --git a/test/integration/extension.test.ts b/test/integration/extension.test.ts
index 2932714..027acc1 100644
--- a/test/integration/extension.test.ts
+++ b/test/integration/extension.test.ts
@@ -104,7 +104,7 @@
const uri = vscode.Uri.file(path.join(fixturePath, 'gogetdocTestData', 'test.go'));
try {
const textDocument = await vscode.workspace.openTextDocument(uri);
- const promises = testCases.map(([position, expected, expectedDoc, expectedParams]) => provider.provideSignatureHelp(textDocument, position, null).then(sigHelp => {
+ const promises = testCases.map(([position, expected, expectedDoc, expectedParams]) => provider.provideSignatureHelp(textDocument, position, null).then((sigHelp) => {
assert.ok(sigHelp, `No signature for gogetdocTestData/test.go:${position.line + 1}:${position.character + 1}`);
assert.equal(sigHelp.signatures.length, 1, 'unexpected number of overloads');
assert.equal(sigHelp.signatures[0].label, expected);
@@ -126,7 +126,7 @@
const uri = vscode.Uri.file(path.join(fixturePath, 'gogetdocTestData', 'test.go'));
try {
const textDocument = await vscode.workspace.openTextDocument(uri);
- const promises = testCases.map(([position, expectedSignature, expectedDocumentation]) => provider.provideHover(textDocument, position, null).then(res => {
+ const promises = testCases.map(([position, expectedSignature, expectedDocumentation]) => provider.provideHover(textDocument, position, null).then((res) => {
if (expectedSignature === null && expectedDocumentation === null) {
assert.equal(res, null);
return;
@@ -268,13 +268,13 @@
{ line: 7, severity: 'warning', msg: 'exported function Print2 should have comment or be unexported' },
{ line: 11, severity: 'error', msg: 'undefined: prin' },
];
- getGoVersion().then(async version => {
+ getGoVersion().then(async (version) => {
const diagnostics = await check(vscode.Uri.file(path.join(fixturePath, 'errorsTest', 'errors.go')), config);
const sortedDiagnostics = ([] as ICheckResult[])
- .concat.apply([], diagnostics.map(x => x.errors))
+ .concat.apply([], diagnostics.map((x) => x.errors))
.sort((a: any, b: any) => a.line - b.line);
assert.equal(sortedDiagnostics.length > 0, true, `Failed to get linter results`);
- const matchCount = expected.filter(expectedItem => {
+ const matchCount = expected.filter((expectedItem) => {
return sortedDiagnostics.some((diag: any) => {
return expectedItem.line === diag.line
&& expectedItem.severity === diag.severity
@@ -291,7 +291,7 @@
return done();
}
- getGoVersion().then(async version => {
+ getGoVersion().then(async (version) => {
const uri = vscode.Uri.file(path.join(generateTestsSourcePath, 'generatetests.go'));
const document = await vscode.workspace.openTextDocument(uri);
const editor = await vscode.window.showTextDocument(document);
@@ -313,7 +313,7 @@
return done();
}
- getGoVersion().then(async version => {
+ getGoVersion().then(async (version) => {
const uri = vscode.Uri.file(path.join(generateFunctionTestSourcePath, 'generatetests.go'));
const document = await vscode.workspace.openTextDocument(uri);
const editor = await vscode.window.showTextDocument(document);
@@ -338,7 +338,7 @@
return done();
}
- getGoVersion().then(async version => {
+ getGoVersion().then(async (version) => {
const uri = vscode.Uri.file(path.join(generatePackageTestSourcePath, 'generatetests.go'));
const document = await vscode.workspace.openTextDocument(uri);
const editor = await vscode.window.showTextDocument(document);
@@ -426,7 +426,7 @@
try {
const editor = await vscode.window.showTextDocument(textDocument);
await editor.edit((editBuilder) => {
- fileEdits.edits.forEach(edit => {
+ fileEdits.edits.forEach((edit) => {
edit.applyUsingTextEditorEdit(editBuilder);
});
});
@@ -445,7 +445,7 @@
});
const uri = vscode.Uri.file(path.join(fixturePath, 'baseTest', 'sample_test.go'));
- vscode.workspace.openTextDocument(uri).then(async document => {
+ vscode.workspace.openTextDocument(uri).then(async (document) => {
const editor = await vscode.window.showTextDocument(document);
const result = await testCurrentFile(config, false, []);
assert.equal(result, true);
@@ -455,10 +455,10 @@
test('Test Outline', (done) => {
const uri = vscode.Uri.file(path.join(fixturePath, 'outlineTest', 'test.go'));
- vscode.workspace.openTextDocument(uri).then(document => {
+ vscode.workspace.openTextDocument(uri).then((document) => {
const options = { document, fileName: document.fileName, importsOption: GoOutlineImportsOptions.Include };
- documentSymbols(options, null).then(outlines => {
+ documentSymbols(options, null).then((outlines) => {
const packageSymbols = outlines.filter((x: any) => x.kind === vscode.SymbolKind.Package);
const imports = outlines[0].children.filter((x: any) => x.kind === vscode.SymbolKind.Namespace);
const functions = outlines[0].children.filter((x: any) => x.kind === vscode.SymbolKind.Function);
@@ -478,11 +478,11 @@
test('Test Outline imports only', (done) => {
const uri = vscode.Uri.file(path.join(fixturePath, 'outlineTest', 'test.go'));
- vscode.workspace.openTextDocument(uri).then(document => {
+ vscode.workspace.openTextDocument(uri).then((document) => {
const options = { document, fileName: document.fileName, importsOption: GoOutlineImportsOptions.Only };
- documentSymbols(options, null).then(outlines => {
- const packageSymbols = outlines.filter(x => x.kind === vscode.SymbolKind.Package);
+ documentSymbols(options, null).then((outlines) => {
+ const packageSymbols = outlines.filter((x) => x.kind === vscode.SymbolKind.Package);
const imports = outlines[0].children.filter((x: any) => x.kind === vscode.SymbolKind.Namespace);
const functions = outlines[0].children.filter((x: any) => x.kind === vscode.SymbolKind.Function);
@@ -498,9 +498,9 @@
test('Test Outline document symbols', (done) => {
const uri = vscode.Uri.file(path.join(fixturePath, 'outlineTest', 'test.go'));
- vscode.workspace.openTextDocument(uri).then(document => {
- new GoDocumentSymbolProvider().provideDocumentSymbols(document, null).then(outlines => {
- const packages = outlines.filter(x => x.kind === vscode.SymbolKind.Package);
+ vscode.workspace.openTextDocument(uri).then((document) => {
+ new GoDocumentSymbolProvider().provideDocumentSymbols(document, null).then((outlines) => {
+ const packages = outlines.filter((x) => x.kind === vscode.SymbolKind.Package);
const variables = outlines[0].children.filter((x: any) => x.kind === vscode.SymbolKind.Variable);
const functions = outlines[0].children.filter((x: any) => x.kind === vscode.SymbolKind.Function);
const structs = outlines[0].children.filter((x: any) => x.kind === vscode.SymbolKind.Struct);
@@ -520,8 +520,8 @@
test('Test listPackages', (done) => {
const uri = vscode.Uri.file(path.join(fixturePath, 'baseTest', 'test.go'));
- vscode.workspace.openTextDocument(uri).then(document => vscode.window.showTextDocument(document)
- .then(async editor => {
+ vscode.workspace.openTextDocument(uri).then((document) => vscode.window.showTextDocument(document)
+ .then(async (editor) => {
const includeImportedPkgs = await listPackages(false);
const excludeImportedPkgs = await listPackages(true);
assert.equal(includeImportedPkgs.indexOf('fmt') > -1, true);
@@ -551,27 +551,27 @@
];
vendorSupportPromise.then(async (vendorSupport: boolean) => {
- const gopkgsPromise = getAllPackages(workDir).then(pkgMap => {
- const pkgs = Array.from(pkgMap.keys()).filter(p => pkgMap.get(p).name !== 'main');
+ const gopkgsPromise = getAllPackages(workDir).then((pkgMap) => {
+ const pkgs = Array.from(pkgMap.keys()).filter((p) => pkgMap.get(p).name !== 'main');
if (vendorSupport) {
- vendorPkgsFullPath.forEach(pkg => {
+ vendorPkgsFullPath.forEach((pkg) => {
assert.equal(pkgs.indexOf(pkg) > -1, true, `Package not found by goPkgs: ${pkg}`);
});
- vendorPkgsRelativePath.forEach(pkg => {
+ vendorPkgsRelativePath.forEach((pkg) => {
assert.equal(pkgs.indexOf(pkg), -1, `Relative path to vendor package ${pkg} should not be returned by gopkgs command`);
});
}
return Promise.resolve(pkgs);
});
- const listPkgPromise: Thenable<string[]> = vscode.workspace.openTextDocument(vscode.Uri.file(filePath)).then(async document => {
+ const listPkgPromise: Thenable<string[]> = vscode.workspace.openTextDocument(vscode.Uri.file(filePath)).then(async (document) => {
const editor = await vscode.window.showTextDocument(document);
const pkgs = await listPackages();
if (vendorSupport) {
- vendorPkgsRelativePath.forEach(pkg => {
+ vendorPkgsRelativePath.forEach((pkg) => {
assert.equal(pkgs.indexOf(pkg) > -1, true, `Relative path for vendor package ${pkg} not found`);
});
- vendorPkgsFullPath.forEach(pkg => {
+ vendorPkgsFullPath.forEach((pkg) => {
assert.equal(pkgs.indexOf(pkg), -1, `Full path for vendor package ${pkg} should be shown by listPackages method`);
});
}
@@ -613,7 +613,7 @@
cmd.on('close', () => {
const pkgs = chunks.join('').split('\n').filter((pkg) => pkg).sort();
if (vendorSupport) {
- vendorPkgs.forEach(pkg => {
+ vendorPkgs.forEach((pkg) => {
assert.equal(pkgs.indexOf(pkg) > -1, true, `Package not found by goPkgs: ${pkg}`);
});
}
@@ -621,11 +621,11 @@
});
});
- const listPkgPromise: Thenable<void> = vscode.workspace.openTextDocument(vscode.Uri.file(filePath)).then(async document => {
+ const listPkgPromise: Thenable<void> = vscode.workspace.openTextDocument(vscode.Uri.file(filePath)).then(async (document) => {
const editor = await vscode.window.showTextDocument(document);
const pkgs = await listPackages();
if (vendorSupport) {
- vendorPkgs.forEach(pkg => {
+ vendorPkgs.forEach((pkg) => {
assert.equal(pkgs.indexOf(pkg), -1, `Vendor package ${pkg} should not be shown by listPackages method`);
});
}
@@ -673,18 +673,18 @@
}
});
- const withoutIgnoringFolders = getWorkspaceSymbols(workspacePath, 'WinInfo', null, configWithoutIgnoringFolders).then(results => {
+ const withoutIgnoringFolders = getWorkspaceSymbols(workspacePath, 'WinInfo', null, configWithoutIgnoringFolders).then((results) => {
assert.equal(results[0].name, 'WinInfo');
assert.equal(results[0].path, path.join(workspacePath, 'vendor/9fans.net/go/acme/acme.go'));
});
- const withIgnoringFolders = getWorkspaceSymbols(workspacePath, 'WinInfo', null, configWithIgnoringFolders).then(results => {
+ const withIgnoringFolders = getWorkspaceSymbols(workspacePath, 'WinInfo', null, configWithIgnoringFolders).then((results) => {
assert.equal(results.length, 0);
});
- const withoutIncludingGoroot = getWorkspaceSymbols(workspacePath, 'Mutex', null, configWithoutIncludeGoroot).then(results => {
+ const withoutIncludingGoroot = getWorkspaceSymbols(workspacePath, 'Mutex', null, configWithoutIncludeGoroot).then((results) => {
assert.equal(results.length, 0);
});
- const withIncludingGoroot = getWorkspaceSymbols(workspacePath, 'Mutex', null, configWithIncludeGoroot).then(results => {
- assert(results.some(result => result.name === 'Mutex'));
+ const withIncludingGoroot = getWorkspaceSymbols(workspacePath, 'Mutex', null, configWithIncludeGoroot).then((results) => {
+ assert(results.some((result) => result.name === 'Mutex'));
});
return Promise.all([withIgnoringFolders, withoutIgnoringFolders, withIncludingGoroot, withoutIncludingGoroot]);
@@ -704,8 +704,8 @@
const uri = vscode.Uri.file(path.join(fixturePath, 'baseTest', 'test.go'));
vscode.workspace.openTextDocument(uri).then(async (textDocument) => {
const editor = await vscode.window.showTextDocument(textDocument);
- const promises = testCases.map(([position, expectedLabel, expectedDetail, expectedDoc]) => provider.provideCompletionItems(editor.document, position, null).then(async items => {
- const item = items.items.find(x => x.label === expectedLabel);
+ const promises = testCases.map(([position, expectedLabel, expectedDetail, expectedDoc]) => provider.provideCompletionItems(editor.document, position, null).then(async (items) => {
+ const item = items.items.find((x) => x.label === expectedLabel);
assert.equal(!!item, true, 'missing expected item in completion list');
assert.equal(item.detail, expectedDetail);
const resolvedItemResult: vscode.ProviderResult<vscode.CompletionItem> = provider.resolveCompletionItem(item, null);
@@ -740,50 +740,50 @@
const baseConfig = vscode.workspace.getConfiguration('go');
vscode.workspace.openTextDocument(uri).then(async (textDocument) => {
const editor = await vscode.window.showTextDocument(textDocument);
- const noFunctionSnippet = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(9, 6), null, Object.create(baseConfig, { useCodeSnippetsOnFunctionSuggest: { value: false } })).then(items => {
+ const noFunctionSnippet = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(9, 6), null, Object.create(baseConfig, { useCodeSnippetsOnFunctionSuggest: { value: false } })).then((items) => {
items = items instanceof vscode.CompletionList ? items.items : items;
- const item = items.find(x => x.label === 'Print');
+ const item = items.find((x) => x.label === 'Print');
assert.equal(!item.insertText, true);
});
- const withFunctionSnippet = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(9, 6), null, Object.create(baseConfig, { useCodeSnippetsOnFunctionSuggest: { value: true } })).then(items1 => {
+ const withFunctionSnippet = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(9, 6), null, Object.create(baseConfig, { useCodeSnippetsOnFunctionSuggest: { value: true } })).then((items1) => {
items1 = items1 instanceof vscode.CompletionList ? items1.items : items1;
- const item1 = items1.find(x => x.label === 'Print');
+ const item1 = items1.find((x) => x.label === 'Print');
assert.equal((<vscode.SnippetString>item1.insertText).value, 'Print(${1:a ...interface{\\}})');
});
- const withFunctionSnippetNotype = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(9, 6), null, Object.create(baseConfig, { useCodeSnippetsOnFunctionSuggestWithoutType: { value: true } })).then(items2 => {
+ const withFunctionSnippetNotype = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(9, 6), null, Object.create(baseConfig, { useCodeSnippetsOnFunctionSuggestWithoutType: { value: true } })).then((items2) => {
items2 = items2 instanceof vscode.CompletionList ? items2.items : items2;
- const item2 = items2.find(x => x.label === 'Print');
+ const item2 = items2.find((x) => x.label === 'Print');
assert.equal((<vscode.SnippetString>item2.insertText).value, 'Print(${1:a})');
});
- const noFunctionAsVarSnippet = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(11, 3), null, Object.create(baseConfig, { useCodeSnippetsOnFunctionSuggest: { value: false } })).then(items3 => {
+ const noFunctionAsVarSnippet = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(11, 3), null, Object.create(baseConfig, { useCodeSnippetsOnFunctionSuggest: { value: false } })).then((items3) => {
items3 = items3 instanceof vscode.CompletionList ? items3.items : items3;
- const item3 = items3.find(x => x.label === 'funcAsVariable');
+ const item3 = items3.find((x) => x.label === 'funcAsVariable');
assert.equal(!item3.insertText, true);
});
- const withFunctionAsVarSnippet = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(11, 3), null, Object.create(baseConfig, { useCodeSnippetsOnFunctionSuggest: { value: true } })).then(items4 => {
+ const withFunctionAsVarSnippet = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(11, 3), null, Object.create(baseConfig, { useCodeSnippetsOnFunctionSuggest: { value: true } })).then((items4) => {
items4 = items4 instanceof vscode.CompletionList ? items4.items : items4;
- const item4 = items4.find(x => x.label === 'funcAsVariable');
+ const item4 = items4.find((x) => x.label === 'funcAsVariable');
assert.equal((<vscode.SnippetString>item4.insertText).value, 'funcAsVariable(${1:k string})');
});
- const withFunctionAsVarSnippetNoType = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(11, 3), null, Object.create(baseConfig, { useCodeSnippetsOnFunctionSuggestWithoutType: { value: true } })).then(items5 => {
+ const withFunctionAsVarSnippetNoType = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(11, 3), null, Object.create(baseConfig, { useCodeSnippetsOnFunctionSuggestWithoutType: { value: true } })).then((items5) => {
items5 = items5 instanceof vscode.CompletionList ? items5.items : items5;
- const item5 = items5.find(x => x.label === 'funcAsVariable');
+ const item5 = items5.find((x) => x.label === 'funcAsVariable');
assert.equal((<vscode.SnippetString>item5.insertText).value, 'funcAsVariable(${1:k})');
});
- const noFunctionAsTypeSnippet = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(14, 0), null, Object.create(baseConfig, { useCodeSnippetsOnFunctionSuggest: { value: false } })).then(items6 => {
+ const noFunctionAsTypeSnippet = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(14, 0), null, Object.create(baseConfig, { useCodeSnippetsOnFunctionSuggest: { value: false } })).then((items6) => {
items6 = items6 instanceof vscode.CompletionList ? items6.items : items6;
- const item1 = items6.find(x => x.label === 'HandlerFunc');
- const item2 = items6.find(x => x.label === 'HandlerFuncWithArgNames');
- const item3 = items6.find(x => x.label === 'HandlerFuncNoReturnType');
+ const item1 = items6.find((x) => x.label === 'HandlerFunc');
+ const item2 = items6.find((x) => x.label === 'HandlerFuncWithArgNames');
+ const item3 = items6.find((x) => x.label === 'HandlerFuncNoReturnType');
assert.equal(!item1.insertText, true);
assert.equal(!item2.insertText, true);
assert.equal(!item3.insertText, true);
});
- const withFunctionAsTypeSnippet = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(14, 0), null, Object.create(baseConfig, { useCodeSnippetsOnFunctionSuggest: { value: true } })).then(items7 => {
+ const withFunctionAsTypeSnippet = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(14, 0), null, Object.create(baseConfig, { useCodeSnippetsOnFunctionSuggest: { value: true } })).then((items7) => {
items7 = items7 instanceof vscode.CompletionList ? items7.items : items7;
- const item11 = items7.find(x => x.label === 'HandlerFunc');
- const item21 = items7.find(x => x.label === 'HandlerFuncWithArgNames');
- const item31 = items7.find(x => x.label === 'HandlerFuncNoReturnType');
+ const item11 = items7.find((x) => x.label === 'HandlerFunc');
+ const item21 = items7.find((x) => x.label === 'HandlerFuncWithArgNames');
+ const item31 = items7.find((x) => x.label === 'HandlerFuncNoReturnType');
assert.equal((<vscode.SnippetString>item11.insertText).value, 'HandlerFunc(func(${1:arg1} string, ${2:arg2} string) {\n\t$3\n}) (string, string)');
assert.equal((<vscode.SnippetString>item21.insertText).value, 'HandlerFuncWithArgNames(func(${1:w} string, ${2:r} string) {\n\t$3\n}) int');
assert.equal((<vscode.SnippetString>item31.insertText).value, 'HandlerFuncNoReturnType(func(${1:arg1} string, ${2:arg2} string) {\n\t$3\n})');
@@ -810,19 +810,19 @@
const baseConfig = vscode.workspace.getConfiguration('go');
vscode.workspace.openTextDocument(uri).then(async (textDocument) => {
const editor = await vscode.window.showTextDocument(textDocument);
- const symbolFollowedByBrackets = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(5, 10), null, Object.create(baseConfig, { useCodeSnippetsOnFunctionSuggest: { value: true } })).then(items => {
+ const symbolFollowedByBrackets = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(5, 10), null, Object.create(baseConfig, { useCodeSnippetsOnFunctionSuggest: { value: true } })).then((items) => {
items = items instanceof vscode.CompletionList ? items.items : items;
- const item = items.find(x => x.label === 'Print');
+ const item = items.find((x) => x.label === 'Print');
assert.equal(!item.insertText, true, 'Unexpected snippet when symbol is followed by ().');
});
- const symbolAsLastParameter = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(7, 13), null, Object.create(baseConfig, { useCodeSnippetsOnFunctionSuggest: { value: true } })).then(items1 => {
+ const symbolAsLastParameter = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(7, 13), null, Object.create(baseConfig, { useCodeSnippetsOnFunctionSuggest: { value: true } })).then((items1) => {
items1 = items1 instanceof vscode.CompletionList ? items1.items : items1;
- const item1 = items1.find(x => x.label === 'funcAsVariable');
+ const item1 = items1.find((x) => x.label === 'funcAsVariable');
assert.equal(!item1.insertText, true, 'Unexpected snippet when symbol is a parameter inside func call');
});
- const symbolsAsNonLastParameter = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(8, 11), null, Object.create(baseConfig, { useCodeSnippetsOnFunctionSuggest: { value: true } })).then(items2 => {
+ const symbolsAsNonLastParameter = provider.provideCompletionItemsInternal(editor.document, new vscode.Position(8, 11), null, Object.create(baseConfig, { useCodeSnippetsOnFunctionSuggest: { value: true } })).then((items2) => {
items2 = items2 instanceof vscode.CompletionList ? items2.items : items2;
- const item2 = items2.find(x => x.label === 'funcAsVariable');
+ const item2 = items2.find((x) => x.label === 'funcAsVariable');
assert.equal(!item2.insertText, true, 'Unexpected snippet when symbol is one of the parameters inside func call.');
});
await Promise.all([
@@ -849,9 +849,9 @@
vscode.workspace.openTextDocument(uri).then(async (textDocument) => {
const editor = await vscode.window.showTextDocument(textDocument);
- const promises = testCases.map(([position, expected]) => provider.provideCompletionItemsInternal(editor.document, position, null, config).then(items => {
+ const promises = testCases.map(([position, expected]) => provider.provideCompletionItemsInternal(editor.document, position, null, config).then((items) => {
items = items instanceof vscode.CompletionList ? items.items : items;
- const labels = items.map(x => x.label);
+ const labels = items.map((x) => x.label);
for (const entry of expected) {
assert.equal(labels.indexOf(entry) > -1, true, `missing expected item in completion list: ${entry} Actual: ${labels}`);
}
@@ -884,10 +884,10 @@
const editor = await vscode.window.showTextDocument(textDocument);
let items = await provider.provideCompletionItemsInternal(editor.document, position, null, config);
items = items instanceof vscode.CompletionList ? items.items : items;
- const labels = items.map(x => x.label);
- expectedItems.forEach(expectedItem => {
+ const labels = items.map((x) => x.label);
+ expectedItems.forEach((expectedItem) => {
items = items instanceof vscode.CompletionList ? items.items : items;
- const actualItem: vscode.CompletionItem = items.filter(item => item.label === expectedItem.label)[0];
+ const actualItem: vscode.CompletionItem = items.filter((item) => item.label === expectedItem.label)[0];
if (!actualItem) {
assert.fail(actualItem, expectedItem, `Missing expected item in completion list: ${expectedItem.label} Actual: ${labels}`);
return;
@@ -918,8 +918,8 @@
vscode.workspace.openTextDocument(uri).then(async (textDocument) => {
const editor = await vscode.window.showTextDocument(textDocument);
- const promises = testCases.map(([position, expected]) => provider.provideCompletionItems(editor.document, position, null).then(items => {
- const labels = items.items.map(x => x.label);
+ const promises = testCases.map(([position, expected]) => provider.provideCompletionItems(editor.document, position, null).then((items) => {
+ const labels = items.items.map((x) => x.label);
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.forEach((entry, index) => {
assert.equal(entry, labels[index], `mismatch in comment completion list Expected: ${entry} Actual: ${labels[index]}`);
@@ -942,7 +942,7 @@
['// This is a comment, complete with punctuation.', '']
];
- testCases.forEach(run => {
+ testCases.forEach((run) => {
assert.equal(run[1], getImportPath(run[0]));
});
});
@@ -968,7 +968,7 @@
playground: { value: { run: true, openbrowser: false, share: false } }
});
- goPlay(validCode, goConfig['playground']).then(result => {
+ goPlay(validCode, goConfig['playground']).then((result) => {
assert(
result.includes('1 2 3 Go!')
);
@@ -998,7 +998,7 @@
playground: { value: { run: true, openbrowser: false, share: true } }
});
- goPlay(validCode, goConfig['playground']).then(result => {
+ goPlay(validCode, goConfig['playground']).then((result) => {
assert(result.includes('1 2 3 Go!'));
assert(result.includes('https://play.golang.org/'));
}, (e) => {
@@ -1024,7 +1024,7 @@
playground: { value: { run: true, openbrowser: false, share: false } }
});
- goPlay(invalidCode, goConfig['playground']).then(result => {
+ goPlay(invalidCode, goConfig['playground']).then((result) => {
assert.ifError(result);
}, (e) => {
assert.ok(e);
@@ -1039,7 +1039,7 @@
buildTags: { value: 'randomtag' }
});
- const checkWithTags = check(vscode.Uri.file(path.join(fixturePath, 'buildTags', 'hello.go')), config1).then(diagnostics => {
+ const checkWithTags = check(vscode.Uri.file(path.join(fixturePath, 'buildTags', 'hello.go')), config1).then((diagnostics) => {
assert.equal(1, diagnostics.length, 'check with buildtag failed. Unexpected errors found');
assert.equal(1, diagnostics[0].errors.length, 'check with buildtag failed. Unexpected errors found');
assert.equal(diagnostics[0].errors[0].msg, 'undefined: fmt.Prinln');
@@ -1052,7 +1052,7 @@
buildTags: { value: 'randomtag othertag' }
});
- const checkWithMultipleTags = check(vscode.Uri.file(path.join(fixturePath, 'buildTags', 'hello.go')), config2).then(diagnostics => {
+ const checkWithMultipleTags = check(vscode.Uri.file(path.join(fixturePath, 'buildTags', 'hello.go')), config2).then((diagnostics) => {
assert.equal(1, diagnostics.length, 'check with multiple buildtags failed. Unexpected errors found');
assert.equal(1, diagnostics[0].errors.length, 'check with multiple buildtags failed. Unexpected errors found');
assert.equal(diagnostics[0].errors[0].msg, 'undefined: fmt.Prinln');
@@ -1065,7 +1065,7 @@
buildTags: { value: '' }
});
- const checkWithoutTags = check(vscode.Uri.file(path.join(fixturePath, 'buildTags', 'hello.go')), config3).then(diagnostics => {
+ const checkWithoutTags = check(vscode.Uri.file(path.join(fixturePath, 'buildTags', 'hello.go')), config3).then((diagnostics) => {
assert.equal(1, diagnostics.length, 'check without buildtags failed. Unexpected errors found');
assert.equal(1, diagnostics[0].errors.length, 'check without buildtags failed. Unexpected errors found');
assert.equal(diagnostics[0].errors[0].msg.indexOf('can\'t load package: package test/testfixture/buildTags') > -1, true, `check without buildtags failed. Go files not excluded. ${diagnostics[0].errors[0].msg}`);
@@ -1107,8 +1107,8 @@
});
const uri = vscode.Uri.file(path.join(fixturePath, 'testTags', 'hello_test.go'));
- vscode.workspace.openTextDocument(uri).then(document => {
- return vscode.window.showTextDocument(document).then(editor => {
+ vscode.workspace.openTextDocument(uri).then((document) => {
+ return vscode.window.showTextDocument(document).then((editor) => {
return testCurrentFile(config1, false, []).then((result: boolean) => {
assert.equal(result, true);
return testCurrentFile(config2, false, []).then((result: boolean) => {
@@ -1128,8 +1128,8 @@
test('Add imports when no imports', (done) => {
const uri = vscode.Uri.file(path.join(fixturePath, 'importTest', 'noimports.go'));
- vscode.workspace.openTextDocument(uri).then(document => {
- return vscode.window.showTextDocument(document).then(editor => {
+ vscode.workspace.openTextDocument(uri).then((document) => {
+ return vscode.window.showTextDocument(document).then((editor) => {
const expectedText = document.getText() + '\n' + 'import (\n\t"bytes"\n)\n';
const edits = getTextEditForAddImport('bytes');
const edit = new vscode.WorkspaceEdit();
@@ -1144,7 +1144,7 @@
test('Add imports to an import block', (done) => {
const uri = vscode.Uri.file(path.join(fixturePath, 'importTest', 'groupImports.go'));
- vscode.workspace.openTextDocument(uri).then(async document => {
+ vscode.workspace.openTextDocument(uri).then(async (document) => {
const editor = await vscode.window.showTextDocument(document);
const expectedText = document.getText().replace('\t"fmt"\n\t"math"', '\t"bytes"\n\t"fmt"\n\t"math"');
const edits = getTextEditForAddImport('bytes');
@@ -1158,7 +1158,7 @@
test('Add imports and collapse single imports to an import block', (done) => {
const uri = vscode.Uri.file(path.join(fixturePath, 'importTest', 'singleImports.go'));
- vscode.workspace.openTextDocument(uri).then(async document => {
+ vscode.workspace.openTextDocument(uri).then(async (document) => {
const editor = await vscode.window.showTextDocument(document);
const expectedText = document.getText().replace('import "fmt"\nimport . "math" // comment', 'import (\n\t"bytes"\n\t"fmt"\n\t. "math" // comment\n)');
const edits = getTextEditForAddImport('bytes');
diff --git a/test/integration/index.ts b/test/integration/index.ts
index 155cbb8..4a082ae 100644
--- a/test/integration/index.ts
+++ b/test/integration/index.ts
@@ -21,11 +21,11 @@
}
// Add files to the test suite
- files.forEach(f => mocha.addFile(path.resolve(testsRoot, f)));
+ files.forEach((f) => mocha.addFile(path.resolve(testsRoot, f)));
try {
// Run the mocha test
- mocha.run(failures => {
+ mocha.run((failures) => {
if (failures > 0) {
e(new Error(`${failures} tests failed.`));
} else {
diff --git a/test/integration/utils.test.ts b/test/integration/utils.test.ts
index fc8d971..563f58b 100644
--- a/test/integration/utils.test.ts
+++ b/test/integration/utils.test.ts
@@ -26,18 +26,18 @@
});
suite('GuessPackageNameFromFile Tests', () => {
- test('package name from main file', done => {
+ test('package name from main file', (done) => {
const expectedPackageName = 'main';
const filename = 'main.go';
guessPackageNameFromFile(filename)
- .then(result => {
+ .then((result) => {
assert.equal(result, expectedPackageName);
})
.then(() => done(), done);
});
- test('package name from dirpath', done => {
+ test('package name from dirpath', (done) => {
const expectedPackageName = 'package';
const fileDir = 'path/package/file.go';
@@ -48,7 +48,7 @@
.then(() => done(), done);
});
- test('package name from test file', done => {
+ test('package name from test file', (done) => {
const expectedPackageName = 'file';
const expectedPackageTestName = 'file_test';
const fileDir = 'file_test.go';
diff --git a/test/unit/NNDict.test.ts b/test/unit/NNDict.test.ts
index 6ef49a7..d3d7e84 100644
--- a/test/unit/NNDict.test.ts
+++ b/test/unit/NNDict.test.ts
@@ -10,10 +10,10 @@
test('basic insert/get: random', () => {
const dict = new NearestNeighborDict(new Node(0, 0), NearestNeighborDict.NUMERIC_DISTANCE_FUNCTION);
const entries = [5, 2, 9, 23, 3, 0, 1, -4, -2];
- entries.forEach(x => dict.insert(x));
+ entries.forEach((x) => dict.insert(x));
assert(dict.height() < 4);
- entries.forEach(x => {
+ entries.forEach((x) => {
assert.equal(dict.getNearest(x + 0.1).key, x);
assert.equal(dict.getNearest(x - 0.1).key, x);
});
@@ -25,10 +25,10 @@
test('basic insert/get: increasing', () => {
const dict = new NearestNeighborDict(new Node(0, 0), NearestNeighborDict.NUMERIC_DISTANCE_FUNCTION);
const entries = [-10, -5, -4, -1, 0, 1, 5, 10, 23];
- entries.forEach(x => dict.insert(x));
+ entries.forEach((x) => dict.insert(x));
assert(dict.height() < 4);
- entries.forEach(x => {
+ entries.forEach((x) => {
assert.equal(dict.getNearest(x + 0.1).key, x);
assert.equal(dict.getNearest(x - 0.1).key, x);
});
@@ -40,10 +40,10 @@
test('basic insert/get: decreasing', () => {
const dict = new NearestNeighborDict(new Node(0, 0), NearestNeighborDict.NUMERIC_DISTANCE_FUNCTION);
const entries = [-10, -5, -4, -1, 0, 1, 5, 10, 23].reverse();
- entries.forEach(x => dict.insert(x));
+ entries.forEach((x) => dict.insert(x));
assert(dict.height() < 4);
- entries.forEach(x => {
+ entries.forEach((x) => {
assert.equal(dict.getNearest(x + 0.1).key, x);
assert.equal(dict.getNearest(x - 0.1).key, x);
});
diff --git a/tslint.json b/tslint.json
index 2d6380c..e09ba7d 100644
--- a/tslint.json
+++ b/tslint.json
@@ -7,7 +7,7 @@
"statements"
]
},
- // "arrow-parens": true,
+ "arrow-parens": true,
"arrow-return-shorthand": true,
"ban-types": {
"options": [