Fix and cleanup VSCode task building

This commit is contained in:
Lukas Wirth 2024-06-17 14:06:01 +02:00
parent 6b8b8ff4c5
commit 8846b5cf4a
5 changed files with 85 additions and 72 deletions

View file

@ -9,7 +9,12 @@ import {
applySnippetTextEdits, applySnippetTextEdits,
type SnippetTextDocumentEdit, type SnippetTextDocumentEdit,
} from "./snippets"; } from "./snippets";
import { type RunnableQuickPick, selectRunnable, createTask, createCargoArgs } from "./run"; import {
type RunnableQuickPick,
selectRunnable,
createTaskFromRunnable,
createCargoArgs,
} from "./run";
import { AstInspector } from "./ast_inspector"; import { AstInspector } from "./ast_inspector";
import { import {
isRustDocument, isRustDocument,
@ -1096,7 +1101,7 @@ export function run(ctx: CtxInit): Cmd {
item.detail = "rerun"; item.detail = "rerun";
prevRunnable = item; prevRunnable = item;
const task = await createTask(item.runnable, ctx.config); const task = await createTaskFromRunnable(item.runnable, ctx.config);
return await vscode.tasks.executeTask(task); return await vscode.tasks.executeTask(task);
}; };
} }
@ -1139,7 +1144,7 @@ export function runSingle(ctx: CtxInit): Cmd {
const editor = ctx.activeRustEditor; const editor = ctx.activeRustEditor;
if (!editor) return; if (!editor) return;
const task = await createTask(runnable, ctx.config); const task = await createTaskFromRunnable(runnable, ctx.config);
task.group = vscode.TaskGroup.Build; task.group = vscode.TaskGroup.Build;
task.presentationOptions = { task.presentationOptions = {
reveal: vscode.TaskRevealKind.Always, reveal: vscode.TaskRevealKind.Always,

View file

@ -223,8 +223,16 @@ export type OpenCargoTomlParams = {
export type Runnable = { export type Runnable = {
label: string; label: string;
location?: lc.LocationLink; location?: lc.LocationLink;
kind: "cargo" | "shell"; } & (RunnableCargo | RunnableShell);
args: CargoRunnableArgs | ShellRunnableArgs;
type RunnableCargo = {
kind: "cargo";
args: CargoRunnableArgs;
};
type RunnableShell = {
kind: "shell";
args: ShellRunnableArgs;
}; };
export type ShellRunnableArgs = { export type ShellRunnableArgs = {

View file

@ -110,10 +110,13 @@ export function prepareEnv(
return env; return env;
} }
export async function createTask(runnable: ra.Runnable, config: Config): Promise<vscode.Task> { export async function createTaskFromRunnable(
runnable: ra.Runnable,
config: Config,
): Promise<vscode.Task> {
let definition: tasks.RustTargetDefinition; let definition: tasks.RustTargetDefinition;
if (runnable.kind === "cargo") { if (runnable.kind === "cargo") {
const runnableArgs = runnable.args as ra.CargoRunnableArgs; const runnableArgs = runnable.args;
let args = createCargoArgs(runnableArgs); let args = createCargoArgs(runnableArgs);
let program: string; let program: string;
@ -128,17 +131,16 @@ export async function createTask(runnable: ra.Runnable, config: Config): Promise
} }
definition = { definition = {
type: tasks.TASK_TYPE, type: tasks.CARGO_TASK_TYPE,
command: program, command: program,
args, args,
cwd: runnableArgs.workspaceRoot || ".", cwd: runnableArgs.workspaceRoot || ".",
env: prepareEnv(runnable.label, runnableArgs, config.runnablesExtraEnv), env: prepareEnv(runnable.label, runnableArgs, config.runnablesExtraEnv),
}; };
} else { } else {
const runnableArgs = runnable.args as ra.ShellRunnableArgs; const runnableArgs = runnable.args;
definition = { definition = {
type: "shell", type: tasks.SHELL_TASK_TYPE,
command: runnableArgs.program, command: runnableArgs.program,
args: runnableArgs.args, args: runnableArgs.args,
cwd: runnableArgs.cwd, cwd: runnableArgs.cwd,
@ -148,13 +150,13 @@ export async function createTask(runnable: ra.Runnable, config: Config): Promise
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const target = vscode.workspace.workspaceFolders![0]; // safe, see main activate() const target = vscode.workspace.workspaceFolders![0]; // safe, see main activate()
const exec = await tasks.targetToExecution(definition, config.cargoRunner, true);
const task = await tasks.buildRustTask( const task = await tasks.buildRustTask(
target, target,
definition, definition,
runnable.label, runnable.label,
config.problemMatcher, config.problemMatcher,
config.cargoRunner, exec,
true,
); );
task.presentationOptions.clear = true; task.presentationOptions.clear = true;

View file

@ -1,27 +1,30 @@
import * as vscode from "vscode"; import * as vscode from "vscode";
import type { Config } from "./config"; import type { Config } from "./config";
import { log } from "./util"; import { log } from "./util";
import { expectNotUndefined, unwrapUndefinable } from "./undefinable"; import { unwrapUndefinable } from "./undefinable";
import * as toolchain from "./toolchain";
// This ends up as the `type` key in tasks.json. RLS also uses `cargo` and // This ends up as the `type` key in tasks.json. RLS also uses `cargo` and
// our configuration should be compatible with it so use the same key. // our configuration should be compatible with it so use the same key.
export const TASK_TYPE = "cargo"; export const CARGO_TASK_TYPE = "cargo";
export const SHELL_TASK_TYPE = "shell";
export const TASK_SOURCE = "rust"; export const RUST_TASK_SOURCE = "rust";
export interface RustTargetDefinition extends vscode.TaskDefinition { export type RustTargetDefinition = {
// The cargo command, such as "run" or "check". readonly type: typeof CARGO_TASK_TYPE | typeof SHELL_TASK_TYPE;
} & vscode.TaskDefinition &
RustTarget;
export type RustTarget = {
// The command to run, usually `cargo`.
command: string; command: string;
// Additional arguments passed to the cargo command. // Additional arguments passed to the command.
args?: string[]; args?: string[];
// The working directory to run the cargo command in. // The working directory to run the command in.
cwd?: string; cwd?: string;
// The shell environment. // The shell environment.
env?: { [key: string]: string }; env?: { [key: string]: string };
// Override the cargo executable name, such as };
// "my_custom_cargo_bin".
overrideCargo?: string;
}
class RustTaskProvider implements vscode.TaskProvider { class RustTaskProvider implements vscode.TaskProvider {
private readonly config: Config; private readonly config: Config;
@ -31,6 +34,10 @@ class RustTaskProvider implements vscode.TaskProvider {
} }
async provideTasks(): Promise<vscode.Task[]> { async provideTasks(): Promise<vscode.Task[]> {
if (!vscode.workspace.workspaceFolders) {
return [];
}
// Detect Rust tasks. Currently we do not do any actual detection // Detect Rust tasks. Currently we do not do any actual detection
// of tasks (e.g. aliases in .cargo/config) and just return a fixed // of tasks (e.g. aliases in .cargo/config) and just return a fixed
// set of tasks that always exist. These tasks cannot be removed in // set of tasks that always exist. These tasks cannot be removed in
@ -45,15 +52,23 @@ class RustTaskProvider implements vscode.TaskProvider {
{ command: "run", group: undefined }, { command: "run", group: undefined },
]; ];
// FIXME: The server should provide this
const cargo = await toolchain.cargoPath();
const tasks: vscode.Task[] = []; const tasks: vscode.Task[] = [];
for (const workspaceTarget of vscode.workspace.workspaceFolders || []) { for (const workspaceTarget of vscode.workspace.workspaceFolders) {
for (const def of defs) { for (const def of defs) {
const definition = {
command: cargo,
args: [def.command],
};
const exec = await targetToExecution(definition, this.config.cargoRunner);
const vscodeTask = await buildRustTask( const vscodeTask = await buildRustTask(
workspaceTarget, workspaceTarget,
{ type: TASK_TYPE, command: def.command }, { ...definition, type: CARGO_TASK_TYPE },
`cargo ${def.command}`, `cargo ${def.command}`,
this.config.problemMatcher, this.config.problemMatcher,
this.config.cargoRunner, exec,
); );
vscodeTask.group = def.group; vscodeTask.group = def.group;
tasks.push(vscodeTask); tasks.push(vscodeTask);
@ -67,16 +82,24 @@ class RustTaskProvider implements vscode.TaskProvider {
// VSCode calls this for every cargo task in the user's tasks.json, // VSCode calls this for every cargo task in the user's tasks.json,
// we need to inform VSCode how to execute that command by creating // we need to inform VSCode how to execute that command by creating
// a ShellExecution for it. // a ShellExecution for it.
if (task.definition.type === CARGO_TASK_TYPE) {
const definition = task.definition as RustTargetDefinition; const taskDefinition = task.definition as RustTargetDefinition;
const cargo = await toolchain.cargoPath();
if (definition.type === TASK_TYPE) { const exec = await targetToExecution(
{
command: cargo,
args: [taskDefinition.command].concat(taskDefinition.args || []),
cwd: taskDefinition.cwd,
env: taskDefinition.env,
},
this.config.cargoRunner,
);
return await buildRustTask( return await buildRustTask(
task.scope, task.scope,
definition, taskDefinition,
task.name, task.name,
this.config.problemMatcher, this.config.problemMatcher,
this.config.cargoRunner, exec,
); );
} }
@ -89,34 +112,31 @@ export async function buildRustTask(
definition: RustTargetDefinition, definition: RustTargetDefinition,
name: string, name: string,
problemMatcher: string[], problemMatcher: string[],
customRunner?: string, exec: vscode.ProcessExecution | vscode.ShellExecution,
throwOnError: boolean = false,
): Promise<vscode.Task> { ): Promise<vscode.Task> {
const exec = await cargoToExecution(definition, customRunner, throwOnError);
return new vscode.Task( return new vscode.Task(
definition, definition,
// scope can sometimes be undefined. in these situations we default to the workspace taskscope as // scope can sometimes be undefined. in these situations we default to the workspace taskscope as
// recommended by the official docs: https://code.visualstudio.com/api/extension-guides/task-provider#task-provider) // recommended by the official docs: https://code.visualstudio.com/api/extension-guides/task-provider#task-provider)
scope ?? vscode.TaskScope.Workspace, scope ?? vscode.TaskScope.Workspace,
name, name,
TASK_SOURCE, RUST_TASK_SOURCE,
exec, exec,
problemMatcher, problemMatcher,
); );
} }
async function cargoToExecution( export async function targetToExecution(
definition: RustTargetDefinition, definition: RustTarget,
customRunner: string | undefined, customRunner?: string,
throwOnError: boolean, throwOnError: boolean = false,
): Promise<vscode.ProcessExecution | vscode.ShellExecution> { ): Promise<vscode.ProcessExecution | vscode.ShellExecution> {
if (customRunner) { if (customRunner) {
const runnerCommand = `${customRunner}.buildShellExecution`; const runnerCommand = `${customRunner}.buildShellExecution`;
try { try {
const runnerArgs = { const runnerArgs = {
kind: TASK_TYPE, kind: CARGO_TASK_TYPE,
args: definition.args, args: definition.args,
cwd: definition.cwd, cwd: definition.cwd,
env: definition.env, env: definition.env,
@ -136,37 +156,14 @@ async function cargoToExecution(
// fallback to default processing // fallback to default processing
} }
} }
// this is a cargo task; do Cargo-esque processing
if (definition.type === TASK_TYPE) {
// Check whether we must use a user-defined substitute for cargo.
// Split on spaces to allow overrides like "wrapper cargo".
const cargoCommand = definition.overrideCargo?.split(" ") ?? [definition.command];
const definitionArgs = expectNotUndefined(
definition.args,
"args were not provided via runnables; this is a bug.",
);
const args = [...cargoCommand.slice(1), ...definitionArgs];
const processName = unwrapUndefinable(cargoCommand[0]);
return new vscode.ProcessExecution(processName, args, {
cwd: definition.cwd,
env: definition.env,
});
} else {
// we've been handed a process definition by rust-analyzer, trust all its inputs
// and make a shell execution.
const args = unwrapUndefinable(definition.args); const args = unwrapUndefinable(definition.args);
return new vscode.ProcessExecution(definition.command, args, { return new vscode.ProcessExecution(definition.command, args, {
cwd: definition.cwd, cwd: definition.cwd,
env: definition.env, env: definition.env,
}); });
}
} }
export function activateTaskProvider(config: Config): vscode.Disposable { export function activateTaskProvider(config: Config): vscode.Disposable {
const provider = new RustTaskProvider(config); const provider = new RustTaskProvider(config);
return vscode.tasks.registerTaskProvider(TASK_TYPE, provider); return vscode.tasks.registerTaskProvider(CARGO_TASK_TYPE, provider);
} }

View file

@ -151,6 +151,7 @@ export async function getRustcId(dir: string): Promise<string> {
} }
/** Mirrors `toolchain::cargo()` implementation */ /** Mirrors `toolchain::cargo()` implementation */
// FIXME: The server should provide this
export function cargoPath(): Promise<string> { export function cargoPath(): Promise<string> {
return getPathForExecutable("cargo"); return getPathForExecutable("cargo");
} }