Skip to content
This repository has been archived by the owner on Jul 15, 2023. It is now read-only.

Commit

Permalink
Refactor to async/await, consts and more functional style
Browse files Browse the repository at this point in the history
  • Loading branch information
Vlad Barosan committed Feb 21, 2019
1 parent beb8719 commit fde1159
Show file tree
Hide file tree
Showing 5 changed files with 113 additions and 127 deletions.
60 changes: 27 additions & 33 deletions src/goGenerateTests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export function toggleTestFile(): void {
vscode.commands.executeCommand('vscode.open', vscode.Uri.file(targetFilePath));
}

export function generateTestCurrentPackage(): Thenable<boolean> {
export function generateTestCurrentPackage(): Promise<boolean> {
let editor = checkActiveEditor();
if (!editor) {
return;
Expand All @@ -74,7 +74,7 @@ export function generateTestCurrentPackage(): Thenable<boolean> {
vscode.workspace.getConfiguration('go', editor.document.uri));
}

export function generateTestCurrentFile(): Thenable<boolean> {
export function generateTestCurrentFile(): Promise<boolean> {
let editor = checkActiveEditor();
if (!editor) {
return;
Expand All @@ -83,32 +83,30 @@ export function generateTestCurrentFile(): Thenable<boolean> {
vscode.workspace.getConfiguration('go', editor.document.uri));
}

export function generateTestCurrentFunction(): Thenable<boolean> {
let editor = checkActiveEditor();
export async function generateTestCurrentFunction(): Promise<boolean> {
const editor = checkActiveEditor();
if (!editor) {
return;
}

return getFunctions(editor.document).then(functions => {
let currentFunction: vscode.DocumentSymbol;
for (let func of functions) {
let selection = editor.selection;
if (selection && func.range.contains(selection.start)) {
currentFunction = func;
break;
}
}
if (!currentFunction) {
vscode.window.showInformationMessage('No function found at cursor.');
return Promise.resolve(false);
}
let funcName = currentFunction.name;
if (funcName.includes('.')) {
funcName = funcName.split('.')[1];
const functions = await getFunctions(editor.document);
const selection = editor.selection;
const currentFunction: vscode.DocumentSymbol = functions.find(func => {
if (selection && func.range.contains(selection.start)) {
return true;
}
return generateTests({ dir: editor.document.uri.fsPath, func: funcName },
vscode.workspace.getConfiguration('go', editor.document.uri));
return false;
});

if (!currentFunction) {
vscode.window.showInformationMessage('No function found at cursor.');
return Promise.resolve(false);
}
let funcName = currentFunction.name;
if (funcName.includes('.')) {
funcName = funcName.split('.')[1];
}
return generateTests({ dir: editor.document.uri.fsPath, func: funcName }, vscode.workspace.getConfiguration('go', editor.document.uri));
}

/**
Expand All @@ -120,12 +118,12 @@ interface Config {
*/
dir: string;
/**
* Specific function names to generate tests squeleton.
* Specific function names to generate tests skeleton.
*/
func?: string;
}

function generateTests(conf: Config, goConfig: vscode.WorkspaceConfiguration): Thenable<boolean> {
function generateTests(conf: Config, goConfig: vscode.WorkspaceConfiguration): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
let cmd = getBinPath('gotests');
let args = ['-w'];
Expand Down Expand Up @@ -193,13 +191,9 @@ function generateTests(conf: Config, goConfig: vscode.WorkspaceConfiguration): T
});
}

function getFunctions(doc: vscode.TextDocument): Thenable<vscode.DocumentSymbol[]> {
let documentSymbolProvider = new GoDocumentSymbolProvider();
return documentSymbolProvider
.provideDocumentSymbols(doc, null)
.then(symbols => symbols[0].children)
.then(symbols =>
symbols.filter(sym =>
sym.kind === vscode.SymbolKind.Function)
);
async function getFunctions(doc: vscode.TextDocument): Promise<vscode.DocumentSymbol[]> {
const documentSymbolProvider = new GoDocumentSymbolProvider();
const symbols = await documentSymbolProvider.provideDocumentSymbols(doc, null);
const symbols_1 = symbols[0].children;
return symbols_1.filter(sym => sym.kind === vscode.SymbolKind.Function);
}
45 changes: 24 additions & 21 deletions src/goImport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ import { getImportablePackages } from './goPackages';

const missingToolMsg = 'Missing tool: ';

export function listPackages(excludeImportedPkgs: boolean = false): Thenable<string[]> {
let importsPromise = excludeImportedPkgs && vscode.window.activeTextEditor ? getImports(vscode.window.activeTextEditor.document) : Promise.resolve([]);
let pkgsPromise = getImportablePackages(vscode.window.activeTextEditor.document.fileName, true);
export function listPackages(excludeImportedPkgs: boolean = false): Promise<string[]> {
const importsPromise = excludeImportedPkgs && vscode.window.activeTextEditor ? getImports(vscode.window.activeTextEditor.document) : Promise.resolve([]);
const pkgsPromise = getImportablePackages(vscode.window.activeTextEditor.document.fileName, true);
return Promise.all([pkgsPromise, importsPromise]).then(([pkgMap, importedPkgs]) => {
importedPkgs.forEach(pkg => {
pkgMap.delete(pkg);
Expand All @@ -31,26 +31,29 @@ export function listPackages(excludeImportedPkgs: boolean = false): Thenable<str
* @param document TextDocument whose imports need to be returned
* @returns Array of imported package paths wrapped in a promise
*/
function getImports(document: vscode.TextDocument): Promise<string[]> {
let options = { fileName: document.fileName, importsOption: GoOutlineImportsOptions.Only, document, skipRanges: true };
return documentSymbols(options, null).then(symbols => {
if (!symbols || !symbols.length) {
return [];
}
// import names will be of the form "math", so strip the quotes in the beginning and the end
let imports = symbols.filter(x => x.kind === vscode.SymbolKind.Namespace).map(x => x.name.substr(1, x.name.length - 2));
return imports;
});
async function getImports(document: vscode.TextDocument): Promise<string[]> {
const options = { fileName: document.fileName, importsOption: GoOutlineImportsOptions.Only, document, skipRanges: true };
const symbols = await documentSymbols(options, null);
if (!symbols || !symbols.length) {
return [];
}
// import names will be of the form "math", so strip the quotes in the beginning and the end
let imports = symbols
.filter(x => x.kind === vscode.SymbolKind.Namespace)
.map(x => x.name.substr(1, x.name.length - 2));
return imports;
}

function askUserForImport(): Thenable<string> {
return listPackages(true).then(packages => {
async function askUserForImport(): Promise<string> {
try {
const packages = await listPackages(true);
return vscode.window.showQuickPick(packages);
}, err => {
}
catch (err) {
if (typeof err === 'string' && err.startsWith(missingToolMsg)) {
promptForMissingTool(err.substr(missingToolMsg.length));
}
});
}
}

export function getTextEditForAddImport(arg: string): vscode.TextEdit[] {
Expand Down Expand Up @@ -98,9 +101,9 @@ export function getTextEditForAddImport(arg: string): vscode.TextEdit[] {
}

export function addImport(arg: string) {
let p = arg ? Promise.resolve(arg) : askUserForImport();
const p = arg ? Promise.resolve(arg) : askUserForImport();
p.then(imp => {
let edits = getTextEditForAddImport(imp);
const edits = getTextEditForAddImport(imp);
if (edits && edits.length > 0) {
const edit = new vscode.WorkspaceEdit();
edit.set(vscode.window.activeTextEditor.document.uri, edits);
Expand Down Expand Up @@ -132,7 +135,7 @@ export function addImportToWorkspace() {

if (importPath === '') {
// Failing that use the current line
let selectedText = editor.document.lineAt(selection.active.line).text;
const selectedText = editor.document.lineAt(selection.active.line).text;
importPath = getImportPath(selectedText);
}

Expand All @@ -145,7 +148,7 @@ export function addImportToWorkspace() {
const env = getToolsEnvVars();

cp.execFile(goRuntimePath, ['list', '-f', '{{.Dir}}', importPath], { env }, (err, stdout, stderr) => {
let dirs = (stdout || '').split('\n');
const dirs = (stdout || '').split('\n');
if (!dirs.length || !dirs[0].trim()) {
vscode.window.showErrorMessage(`Could not find package ${importPath}`);
return;
Expand Down
20 changes: 10 additions & 10 deletions src/goOutline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,14 @@ export interface GoOutlineOptions {
skipRanges?: boolean;
}

export function documentSymbols(options: GoOutlineOptions, token: vscode.CancellationToken): Promise<vscode.DocumentSymbol[]> {
return runGoOutline(options, token).then(decls => {
return convertToCodeSymbols(
options.document,
decls,
options.importsOption !== GoOutlineImportsOptions.Exclude,
(options.skipRanges || !options.document) ? null : makeMemoizedByteOffsetConverter(new Buffer(options.document.getText())));
});
export async function documentSymbols(options: GoOutlineOptions, token: vscode.CancellationToken): Promise<vscode.DocumentSymbol[]> {
const decls = await runGoOutline(options, token);
return convertToCodeSymbols(options.document,
decls,
options.importsOption !== GoOutlineImportsOptions.Exclude,
(options.skipRanges || !options.document)
? null
: makeMemoizedByteOffsetConverter(new Buffer(options.document.getText())));
}

export function runGoOutline(options: GoOutlineOptions, token: vscode.CancellationToken): Promise<GoOutlineDeclaration[]> {
Expand Down Expand Up @@ -185,10 +185,10 @@ export class GoDocumentSymbolProvider implements vscode.DocumentSymbolProvider {

public provideDocumentSymbols(document: vscode.TextDocument, token: vscode.CancellationToken): Thenable<vscode.DocumentSymbol[]> {
if (typeof this.includeImports !== 'boolean') {
let gotoSymbolConfig = vscode.workspace.getConfiguration('go', document.uri)['gotoSymbol'];
const gotoSymbolConfig = vscode.workspace.getConfiguration('go', document.uri)['gotoSymbol'];
this.includeImports = gotoSymbolConfig ? gotoSymbolConfig['includeImports'] : false;
}
let options = { fileName: document.fileName, document: document, importsOption: this.includeImports ? GoOutlineImportsOptions.Include : GoOutlineImportsOptions.Exclude };
const options = { fileName: document.fileName, document: document, importsOption: this.includeImports ? GoOutlineImportsOptions.Include : GoOutlineImportsOptions.Exclude };
return documentSymbols(options, token);
}
}
46 changes: 20 additions & 26 deletions src/goReferencesCodelens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ export class GoReferencesCodeLensProvider extends GoBaseCodeLensProvider {
if (!this.enabled) {
return [];
}
let codeLensConfig: { [key: string]: any } = vscode.workspace.getConfiguration('go', document.uri).get('enableCodeLens');
let codelensEnabled = codeLensConfig ? codeLensConfig['references'] : false;
const codeLensConfig: { [key: string]: any } = vscode.workspace.getConfiguration('go', document.uri).get('enableCodeLens');
const codelensEnabled = codeLensConfig ? codeLensConfig['references'] : false;
if (!codelensEnabled) {
return Promise.resolve([]);
}
Expand All @@ -44,16 +44,16 @@ export class GoReferencesCodeLensProvider extends GoBaseCodeLensProvider {
}

public resolveCodeLens?(inputCodeLens: CodeLens, token: CancellationToken): CodeLens | Thenable<CodeLens> {
let codeLens = inputCodeLens as ReferencesCodeLens;
const codeLens = inputCodeLens as ReferencesCodeLens;

if (token.isCancellationRequested) {
return Promise.resolve(codeLens);
}

let options = {
const options = {
includeDeclaration: false
};
let referenceProvider = new GoReferenceProvider();
const referenceProvider = new GoReferenceProvider();
return referenceProvider.provideReferences(codeLens.document, codeLens.range.start, options, token).then(references => {
codeLens.command = {
title: references.length === 1
Expand All @@ -73,28 +73,22 @@ export class GoReferencesCodeLensProvider extends GoBaseCodeLensProvider {
});
}

private provideDocumentSymbols(document: TextDocument, token: CancellationToken): Thenable<vscode.DocumentSymbol[]> {
let symbolProvider = new GoDocumentSymbolProvider();
let isTestFile = document.fileName.endsWith('_test.go');
return symbolProvider.provideDocumentSymbols(document, token)
.then(symbols => symbols[0].children)
.then(symbols => {
return symbols.filter(symbol => {

if (symbol.kind === vscode.SymbolKind.Interface) {
return true;
}

if (symbol.kind === vscode.SymbolKind.Function) {
if (isTestFile && (symbol.name.startsWith('Test') || symbol.name.startsWith('Example') || symbol.name.startsWith('Benchmark'))) {
return false;
}
return true;
}

private async provideDocumentSymbols(document: TextDocument, token: CancellationToken): Promise<vscode.DocumentSymbol[]> {
const symbolProvider = new GoDocumentSymbolProvider();
const isTestFile = document.fileName.endsWith('_test.go');
const symbols = await symbolProvider.provideDocumentSymbols(document, token);
const symbols_1 = symbols[0].children;
return symbols_1.filter(symbol => {
if (symbol.kind === vscode.SymbolKind.Interface) {
return true;
}
if (symbol.kind === vscode.SymbolKind.Function) {
if (isTestFile && (symbol.name.startsWith('Test') || symbol.name.startsWith('Example') || symbol.name.startsWith('Benchmark'))) {
return false;
}
);
});
return true;
}
return false;
});
}
}
69 changes: 32 additions & 37 deletions src/goRunTestCodelens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ export class GoRunTestCodeLensProvider extends GoBaseCodeLensProvider {
if (!this.enabled) {
return [];
}
let config = vscode.workspace.getConfiguration('go', document.uri);
let codeLensConfig: { [key: string]: any } = config.get('enableCodeLens');
let codelensEnabled = codeLensConfig ? codeLensConfig['runtest'] : false;
const config = vscode.workspace.getConfiguration('go', document.uri);
const codeLensConfig: { [key: string]: any } = config.get('enableCodeLens');
const codelensEnabled = codeLensConfig ? codeLensConfig['runtest'] : false;
if (!codelensEnabled || !document.fileName.endsWith('_test.go')) {
return [];
}
Expand All @@ -51,40 +51,35 @@ export class GoRunTestCodeLensProvider extends GoBaseCodeLensProvider {
});
}

private getCodeLensForPackage(document: TextDocument, token: CancellationToken): Thenable<CodeLens[]> {
let documentSymbolProvider = new GoDocumentSymbolProvider();
return documentSymbolProvider.provideDocumentSymbols(document, token)
.then(symbols => symbols[0].children)
.then(symbols => {
const pkg = symbols.find(sym => sym.kind === vscode.SymbolKind.Package && !!sym.name);
if (!pkg) {
return;
}
const range = pkg.range;
const packageCodeLens = [
new CodeLens(range, {
title: 'run package tests',
command: 'go.test.package'
}),
new CodeLens(range, {
title: 'run file tests',
command: 'go.test.file'
})
];
if (symbols.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'
}),
new CodeLens(range, {
title: 'run file benchmarks',
command: 'go.benchmark.file'
})
);
}
return packageCodeLens;
});
private async getCodeLensForPackage(document: TextDocument, token: CancellationToken): Promise<CodeLens[]> {
const documentSymbolProvider = new GoDocumentSymbolProvider();
const symbols = await documentSymbolProvider.provideDocumentSymbols(document, token);
const symbols_1 = symbols[0].children;
const pkg = symbols_1.find(sym => sym.kind === vscode.SymbolKind.Package && !!sym.name);
if (!pkg) {
return;
}
const range = pkg.range;
const packageCodeLens = [
new CodeLens(range, {
title: 'run package tests',
command: 'go.test.package'
}),
new CodeLens(range, {
title: 'run file tests',
command: 'go.test.file'
})
];
if (symbols_1.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'
}), new CodeLens(range, {
title: 'run file benchmarks',
command: 'go.benchmark.file'
}));
}
return packageCodeLens;
}

private getCodeLensForFunctions(vsConfig: vscode.WorkspaceConfiguration, document: TextDocument, token: CancellationToken): Thenable<CodeLens[]> {
Expand Down

0 comments on commit fde1159

Please sign in to comment.