Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code completion (review comments addressed) #246

Merged
merged 3 commits into from
Oct 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 126 additions & 0 deletions src/completion-provider/bazel_completion_provider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// Copyright 2018 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import * as vscode from "vscode";
import { queryQuickPickTargets } from "../bazel";

function insertCompletionItemIfUnique(
options: vscode.CompletionItem[],
option: vscode.CompletionItem,
) {
if (
options.find((value: vscode.CompletionItem) => {
return value.label === option.label && value.kind === option.kind;
}) === undefined
) {
options.push(option);
}
}

function getCandidateTargetFromDocumentPosition(
document: vscode.TextDocument,
position: vscode.Position,
): string | undefined {
const linePrefix = document
.lineAt(position)
.text.substr(0, position.character);
const index = linePrefix.indexOf('"//');
if (index === -1) {
return undefined;
}
return linePrefix.substring(index + 1);
}

function stripLastPackageOrTargetName(target: string) {
const slashIndex = target.lastIndexOf("/");
const colonIndex = target.lastIndexOf(":");
const index = Math.max(slashIndex, colonIndex);
if (index !== -1) {
target = target.substring(0, index + 1);
}
return target;
}

function getNextPackage(target: string) {
const nextPackage = target.split("/", 2);
if (nextPackage.length > 1) {
return nextPackage[0];
} else if (nextPackage[0] !== "") {
const withoutTarget = nextPackage[0].split(":", 2);
if (withoutTarget.length > 1) {
return withoutTarget[0];
}
}
return undefined;
}

export class BazelCompletionItemProvider
implements vscode.CompletionItemProvider {
private targets: string[] = [];

/**
* Returns completion items matching the given prefix.
*
* Only label started with "//: is supported at the moment.
*/
public provideCompletionItems(
document: vscode.TextDocument,
position: vscode.Position,
) {
let candidateTarget = getCandidateTargetFromDocumentPosition(
document,
position,
);
if (candidateTarget === undefined) {
return [];
}

if (!candidateTarget.endsWith("/") && !candidateTarget.endsWith(":")) {
candidateTarget = stripLastPackageOrTargetName(candidateTarget);
}

const completionItems = new Array<vscode.CompletionItem>();
this.targets.forEach((target) => {
if (!target.startsWith(candidateTarget)) {
return;
}
const sufix = target.replace(candidateTarget, "");

let completionKind = vscode.CompletionItemKind.Folder;
let label = getNextPackage(sufix);
if (label === undefined) {
completionKind = vscode.CompletionItemKind.Field;
label = sufix;
}
insertCompletionItemIfUnique(
completionItems,
new vscode.CompletionItem(label, completionKind),
);
});
return completionItems;
}

/**
* Runs a bazel query command to acquire labels of all the targets in the
* workspace.
*/
public async refresh() {
const queryTargets = await queryQuickPickTargets("kind('.* rule', ...)");
if (queryTargets.length !== 0) {
this.targets = queryTargets.map((queryTarget) => {
return queryTarget.label;
});
}
}
}
15 changes: 15 additions & 0 deletions src/completion-provider/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Copyright 2018 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

export * from "./bazel_completion_provider";
19 changes: 15 additions & 4 deletions src/extension/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import {
checkBuildifierIsAvailable,
} from "../buildifier";
import { BazelBuildCodeLensProvider } from "../codelens";
import { BazelCompletionItemProvider } from "../completion-provider";
import { BazelTargetSymbolProvider } from "../symbols";
import { BazelWorkspaceTreeProvider } from "../workspace-tree";
import { getDefaultBazelExecutablePath } from "./configuration";
Expand All @@ -46,8 +47,17 @@ export function activate(context: vscode.ExtensionContext) {
const workspaceTreeProvider = new BazelWorkspaceTreeProvider(context);
const codeLensProvider = new BazelBuildCodeLensProvider(context);
const buildifierDiagnostics = new BuildifierDiagnosticsManager();
const completionItemProvider = new BazelCompletionItemProvider();

completionItemProvider.refresh();

context.subscriptions.push(
vscode.languages.registerCompletionItemProvider(
[{ pattern: "**/BUILD" }, { pattern: "**/BUILD.bazel" }],
completionItemProvider,
"/",
":",
),
vscode.window.registerTreeDataProvider(
"bazelWorkspace",
workspaceTreeProvider,
Expand All @@ -71,6 +81,7 @@ export function activate(context: vscode.ExtensionContext) {
),
vscode.commands.registerCommand("bazel.clean", bazelClean),
vscode.commands.registerCommand("bazel.refreshBazelBuildTargets", () => {
completionItemProvider.refresh();
workspaceTreeProvider.refresh();
}),
vscode.commands.registerCommand(
Expand Down Expand Up @@ -173,7 +184,9 @@ async function bazelBuildTargetWithDebugging(
}
return;
}
const bazelConfigCmdLine = vscode.workspace.getConfiguration("bazel.commandLine");
const bazelConfigCmdLine = vscode.workspace.getConfiguration(
"bazel.commandLine",
);
const startupOptions = bazelConfigCmdLine.get<string[]>("startupOptions");
const commandArgs = bazelConfigCmdLine.get<string[]>("commandArgs");

Expand Down Expand Up @@ -412,9 +425,7 @@ function onTaskProcessEnd(event: vscode.TaskProcessEndEvent) {
} else {
const timeInSeconds = measurePerformance(bazelTaskInfo.startTime);
vscode.window.showInformationMessage(
`Bazel ${
bazelTaskInfo.command
} completed successfully in ${timeInSeconds} seconds.`,
`Bazel ${bazelTaskInfo.command} completed successfully in ${timeInSeconds} seconds.`,
);
}
}
Expand Down