From 2b0cc6b733385707bde7185ad38715b069eb596e Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Fri, 4 Dec 2026 10:38:02 +0800 Subject: [PATCH] fix(dotnet): build, clean and restore .NET projects in the Build window (#7922) Build, Restore and Clean .NET Project ran dotnet as a background task of the .NET tool window, with no Build window output, no status bar progress and no notification; the output appeared only in the NuGet Packages window afterwards. They now run through a new build_dotnet_command host command on the shared .NET build runner, so output and errors stream into the Build window, Stop Build cancels, Rerun repeats, and a notification reports the result. The selected project is re-evaluated (and audited after a restore) only when the command succeeds. Fixes #7853 --- crates/ide-build/src/compile/mod.rs | 67 +++++++++++++-- crates/ide-host/src/ops/build.rs | 19 +++++ docs/en/languages/csharp.mdx | 2 +- docs/zh/languages/csharp.mdx | 2 +- e2e/dotnetBuild.spec.ts | 67 +++++++++++++++ src-tauri/tests/commands.snap | 1 + src/bindings.ts | 8 ++ src/features/build/build.test.tsx | 60 ++++++++++++++ src/features/build/index.ts | 20 +++++ src/features/build/store.ts | 50 ++++++++++-- src/features/dotnet/store.test.ts | 122 +++++++++++++++++++++------- src/features/dotnet/store.ts | 70 +++++----------- src/platform/locales/text/en.json | 5 ++ src/platform/locales/text/zh.json | 5 ++ 14 files changed, 407 insertions(+), 91 deletions(-) create mode 100644 e2e/dotnetBuild.spec.ts diff --git a/crates/ide-build/src/compile/mod.rs b/crates/ide-build/src/compile/mod.rs index dc694e332e..4c541900d3 100644 --- a/crates/ide-build/src/compile/mod.rs +++ b/crates/ide-build/src/compile/mod.rs @@ -569,23 +569,54 @@ fn dotnet_steps(dir: &Path, kind: BuildKind) -> IdeResult> { Ok(vec![step]) } +/// A `dotnet` command the .NET tool window runs on a solution or project file. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum DotnetCommand { + Build, + Clean, + Restore, +} + +/// `dotnet build` / `clean` / `restore` of one solution or project file, followed by `options` +/// (`--configuration`, `--framework`, `-p:…`). +pub fn dotnet_command_plan(file: &Path, command: DotnetCommand, options: &[String]) -> IdeResult { + let verb = match command { + DotnetCommand::Build => "build", + DotnetCommand::Clean => "clean", + DotnetCommand::Restore => "restore", + }; + dotnet_file_plan(file, verb, true, options) +} + /// `dotnet publish` of one project file with the publish dialog's `options` (`-p:PublishProfile=…`, /// or `--configuration` / `--runtime` / `--output`). pub fn dotnet_publish_plan(file: &Path, options: &[String]) -> IdeResult { + dotnet_file_plan(file, "publish", false, options) +} + +fn dotnet_file_plan(file: &Path, verb: &str, solutions: bool, options: &[String]) -> IdeResult { let ext = file.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); - let (Some(dir), Some(name), true) = - (file.parent(), file.file_name(), matches!(ext.as_str(), "csproj" | "fsproj" | "vbproj")) - else { - return Err(IdeError::invalid("dotnet publish needs a C#, F# or VB project")); + let accepted = match ext.as_str() { + "csproj" | "fsproj" | "vbproj" => true, + "sln" | "slnx" => solutions, + _ => false, + }; + let (Some(dir), Some(name), true) = (file.parent(), file.file_name(), accepted) else { + return Err(IdeError::invalid(if solutions { + format!("dotnet {verb} needs a solution or a C#, F# or VB project") + } else { + format!("dotnet {verb} needs a C#, F# or VB project") + })); }; if !file.is_file() { return Err(IdeError::not_found(format!("{} does not exist", file.display()))); } let name = name.to_string_lossy(); - let mut step = BuildStep::new("dotnet", &["publish", &name, "-nologo", "-clp:NoSummary"], dir, Format::Msbuild); + let mut step = BuildStep::new("dotnet", &[verb, &name, "-nologo", "-clp:NoSummary"], dir, Format::Msbuild); step.args.extend_from_slice(options); step.env.insert("MSBUILDTERMINALLOGGER".into(), "off".into()); - Ok(BuildPlan { system: BuildSystem::Dotnet, title: format!("dotnet publish {name}"), steps: vec![step] }) + Ok(BuildPlan { system: BuildSystem::Dotnet, title: format!("dotnet {verb} {name}"), steps: vec![step] }) } /// `dotnet format` of a solution or C# / VB project file; `verify` only reports what it would @@ -2363,6 +2394,30 @@ mod tests { } } + #[test] + fn dotnet_commands_run_on_one_solution_or_project_file() { + use super::DotnetCommand; + let dir = tempfile::tempdir().unwrap(); + for name in ["App.csproj", "Sln.sln", "Sln.slnx", "notes.txt"] { + std::fs::write(dir.path().join(name), "").unwrap(); + } + let options = ["--configuration".to_owned(), "Release".to_owned()]; + for (name, command, verb) in [ + ("Sln.sln", DotnetCommand::Build, "build"), + ("Sln.slnx", DotnetCommand::Clean, "clean"), + ("App.csproj", DotnetCommand::Restore, "restore"), + ] { + let plan = super::dotnet_command_plan(&dir.path().join(name), command, &options).unwrap(); + assert_eq!(plan.title, format!("dotnet {verb} {name}")); + assert_eq!(plan.steps[0].args, [verb, name, "-nologo", "-clp:NoSummary", "--configuration", "Release"]); + assert_eq!(plan.steps[0].cwd, dir.path()); + } + for name in ["notes.txt", "Missing.sln"] { + assert!(super::dotnet_command_plan(&dir.path().join(name), DotnetCommand::Build, &[]).is_err(), "{name}"); + } + assert!(super::dotnet_publish_plan(&dir.path().join("Sln.sln"), &[]).is_err(), "publish takes a project"); + } + /// The real `dotnet publish` (`-- --ignored`): publishes, reports compile errors, and stops /// when cancelled. #[test] diff --git a/crates/ide-host/src/ops/build.rs b/crates/ide-host/src/ops/build.rs index 0e80fa93c1..eda7a60d70 100644 --- a/crates/ide-host/src/ops/build.rs +++ b/crates/ide-host/src/ops/build.rs @@ -1602,6 +1602,24 @@ pub async fn build_dotnet_publish( run_dotnet_plan(host, window, file, plan, request, clear, on_event).await } +/// `dotnet build` / `clean` / `restore` of a solution or project from the .NET tool window, +/// streaming like a build; cancellable with `cancel_request(request)`. +#[allow(clippy::too_many_arguments)] +#[command(trust = trusted)] +pub async fn build_dotnet_command( + host: &Host, + window: &str, + file: std::path::PathBuf, + command: compile::DotnetCommand, + options: Vec, + request: RequestId, + clear: Vec, + on_event: Channel, +) -> IdeResult { + let plan = move |file: &Path| compile::dotnet_command_plan(file, command, &options); + run_dotnet_plan(host, window, file, plan, request, clear, on_event).await +} + async fn run_dotnet_plan( host: &Host, window: &str, @@ -2080,6 +2098,7 @@ mod maven_completion_tests { ide_command::domain!( build: build_compile_file, + build_dotnet_command, build_dotnet_format, build_dotnet_publish, build_model, diff --git a/docs/en/languages/csharp.mdx b/docs/en/languages/csharp.mdx index 03dca3368e..937f11fb48 100644 --- a/docs/en/languages/csharp.mdx +++ b/docs/en/languages/csharp.mdx @@ -79,7 +79,7 @@ To format or check a whole solution or C# / VB project with `dotnet format`, rig The **Project** tool window lists the .NET solutions and projects it finds, without a manual reload. Each solution is a `Solution ''` node with its projects under it, and a project that is in no solution is a node of its own, above the project folder. Only solution and project files directly in a content root are listed this way; .NET code in subfolders stays in its folders. While the workspace is being scanned, or when the scan failed, a **.NET** node above the project folder shows that in grey text. -Right-click a solution (`.sln`, `.slnx`) or a project (`.csproj`, `.fsproj`, `.vbproj`) to **Build .NET Project**, **Restore .NET Project** or **Clean .NET Project**. The same actions are in **Find Action…** (`⌘⇧A` / `Ctrl+Shift+A`) and act on the file selected in the Project view, else the project of the active editor's file, else the first solution. **Reload .NET Workspace** scans the folder again, and **Cancel .NET Operation** stops a running build, restore or clean. +Right-click a solution (`.sln`, `.slnx`) or a project (`.csproj`, `.fsproj`, `.vbproj`) to **Build .NET Project**, **Restore .NET Project** or **Clean .NET Project**. The same actions are in **Find Action…** (`⌘⇧A` / `Ctrl+Shift+A`) and act on the file selected in the Project view, else the project of the active editor's file, else the first solution. They run in the **Build** tool window, with progress in the status bar, errors in the tree and a notification when they finish; **Stop Build** stops them. **Reload .NET Workspace** scans the folder again, and **Cancel .NET Operation** stops a running workspace scan or NuGet operation. Project evaluation uses MSBuild, so the target frameworks, output paths and packages come from what MSBuild computes, including imported properties. Builds use the `Debug` configuration. diff --git a/docs/zh/languages/csharp.mdx b/docs/zh/languages/csharp.mdx index 347c453aa2..a2a3168f69 100644 --- a/docs/zh/languages/csharp.mdx +++ b/docs/zh/languages/csharp.mdx @@ -58,7 +58,7 @@ C# 在装了 Roslyn 语言服务器时用它,否则用 csharp-ls。Roslyn 是 **项目**工具窗口会列出找到的 .NET 解决方案和项目,无需手动重新加载。每个解决方案是一个 `Solution '<名称>'` 节点,其下是它的项目;不属于任何解决方案的项目单独成一个节点,位于项目文件夹之上。只有直接位于内容根目录的解决方案和项目文件会这样显示,子文件夹中的 .NET 代码仍留在各自的文件夹里。工作区正在扫描或扫描失败时,项目文件夹之上的 **.NET** 节点会用灰色文字显示状态。 -在解决方案(`.sln`、`.slnx`)或项目(`.csproj`、`.fsproj`、`.vbproj`)上右键,可以执行 **构建 .NET 项目**、**还原 .NET 项目**、**清理 .NET 项目**。同样的操作也在 **查找操作…**(`⌘⇧A` / `Ctrl+Shift+A`)中,作用对象依次为:项目视图中选中的文件、当前编辑器文件所在的项目、第一个解决方案。**重新加载 .NET 工作区** 会重新扫描文件夹,**取消 .NET 操作** 会停止正在进行的构建、还原或清理。 +在解决方案(`.sln`、`.slnx`)或项目(`.csproj`、`.fsproj`、`.vbproj`)上右键,可以执行 **构建 .NET 项目**、**还原 .NET 项目**、**清理 .NET 项目**。同样的操作也在 **查找操作…**(`⌘⇧A` / `Ctrl+Shift+A`)中,作用对象依次为:项目视图中选中的文件、当前编辑器文件所在的项目、第一个解决方案。它们在 **构建** 工具窗口中运行:状态栏显示进度,错误列在树中,完成时会有通知;**停止构建** 可以中止。**重新加载 .NET 工作区** 会重新扫描文件夹,**取消 .NET 操作** 会停止正在进行的工作区扫描或 NuGet 操作。 项目信息由 MSBuild 求值得到,因此目标框架、输出路径和包都是 MSBuild 实际计算的结果,包括导入的属性。构建使用 `Debug` 配置。 diff --git a/e2e/dotnetBuild.spec.ts b/e2e/dotnetBuild.spec.ts new file mode 100644 index 0000000000..88bbe203a0 --- /dev/null +++ b/e2e/dotnetBuild.spec.ts @@ -0,0 +1,67 @@ +/** + * Build a .NET solution from the Project view (#7853). The host is stubbed at the IPC layer (no + * `dotnet` runs; the `ide-build` test checks the command line): the spec checks that the build + * streams into the Build window and ends with a notification, as Build Project does. + */ +import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; + +const SHOTS = process.env.E2E_SHOTS; +const FILE = "/dev/acme-api/App/Program.cs"; + +test("Build .NET Project on a solution runs in the Build window", async ({ workbench: page }) => { + await stubDesktop(page); + await page.evaluate(async (file) => { + window.__ipc.handlers.build_dotnet_command = (args) => { + const title = `dotnet ${args.command as string} Acme.sln`; + const messages = [ + { + severity: "error", + text: "; expected", + path: file, + range: { start: { line: 0, col: 12 }, end: { line: 0, col: 12 } }, + code: "CS1002", + }, + ]; + window.__ipc.send(args.onEvent, { kind: "started", system: "dotnet", title }); + window.__ipc.send(args.onEvent, { + kind: "step", + command: `dotnet ${args.command as string} Acme.sln -nologo -clp:NoSummary`, + cwd: "/dev/acme-api", + }); + return { system: "dotnet", title, success: false, errors: 1, warnings: 0, durationMs: 1200, messages }; + }; + const storeModule = "/src/features/dotnet/store.ts"; + const { useDotnet } = await import(/* @vite-ignore */ storeModule); + const project = "/dev/acme-api/App/App.csproj"; + useDotnet.setState({ + configuration: "Release", + model: { + projects: [ + { + path: project, + name: "App", + frameworks: ["net9.0"], + configurations: ["Debug", "Release"], + references: [], + packages: [], + test: false, + runner: "vstest", + adapter: "mstest", + trx: false, + }, + ], + solutions: [{ path: "/dev/acme-api/Acme.sln", projects: [project] }], + }, + }); + }, FILE); + + await page.getByRole("treeitem", { name: /Solution 'Acme'/ }).click({ button: "right" }); + await page.getByRole("menuitem", { name: "Build .NET Project" }).click(); + await expect(page.getByText("; expected").first()).toBeVisible(); + await expect(page.getByText("Build failed: 1 error").first()).toBeVisible(); + if (SHOTS) await page.screenshot({ path: `${SHOTS}/dotnet-build-window.png`, animations: "disabled" }); + + expect(await ipcCalls(page, "build_dotnet_command")).toMatchObject([ + { file: "/dev/acme-api/Acme.sln", command: "build", options: ["--configuration", "Release"] }, + ]); +}); diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 801c16c422..f2ce52f4b2 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -124,6 +124,7 @@ app_update_status always desktop bin app_update_window_ready always desktop bindings sync apply_workspace_edit always project_host bindings async build_compile_file trusted project_host bindings async +build_dotnet_command trusted project_host bindings async build_dotnet_format trusted project_host bindings async build_dotnet_publish trusted project_host bindings async build_model trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 8f1cda91d9..5938805dd2 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -368,6 +368,11 @@ export const commands = { * the new messages are published as `build` diagnostics. */ buildCompileFile: (file: string, request: RequestId, clear: string[], onEvent: Channel) => typedError(__TAURI_INVOKE("build_compile_file", { file, request, clear, onEvent })), + /** + * `dotnet build` / `clean` / `restore` of a solution or project from the .NET tool window, + * streaming like a build; cancellable with `cancel_request(request)`. + */ + buildDotnetCommand: (file: string, command: DotnetCommand, options: string[], request: RequestId, clear: string[], onEvent: Channel) => typedError(__TAURI_INVOKE("build_dotnet_command", { file, command, options, request, clear, onEvent })), /** * Run dotnet format: `dotnet format` on a solution or project file (`verify`: * `--verify-no-changes`), streaming like a build; cancellable with `cancel_request(request)`. @@ -9011,6 +9016,9 @@ export type DocumentTextChange = { insert: string, }; +/** A `dotnet` command the .NET tool window runs on a solution or project file. */ +export type DotnetCommand = "build" | "clean" | "restore"; + /** One file of a [`remote_download_local`] transfer starting: `done` of `total` files are finished. */ export type DownloadProgress = { path: string, diff --git a/src/features/build/build.test.tsx b/src/features/build/build.test.tsx index 80e3abe525..29d2c17857 100644 --- a/src/features/build/build.test.tsx +++ b/src/features/build/build.test.tsx @@ -143,6 +143,21 @@ class FakeBackend implements BuildBackend { this.fail = reject; }); } + dotnetCommand( + file: string, + command: string, + options: string[], + _request: number, + clear: string[], + onEvent: (e: BuildEvent) => void, + ) { + this.calls.push({ kind: `${command} ${options.join(" ")}`, file, clear }); + this.emit = onEvent; + return new Promise((resolve, reject) => { + this.finish = resolve; + this.fail = reject; + }); + } cancel(request: number) { this.cancelled.push(request); } @@ -267,6 +282,51 @@ describe("build feature", () => { expect(notes.at(-1)).toMatchObject({ title: "dotnet publish completed", level: "info" }); }); + it("builds a .NET solution in the Build window, reports its errors and reruns it (#7853)", async () => { + const build = { kind: "build --configuration Release", file: "/p/Big.sln" }; + const done: boolean[] = []; + const ran = executeAction("build.dotnetCommand", { + file: build.file, + command: "build", + options: ["--configuration", "Release"], + onDone: (success: boolean) => done.push(success), + }); + await act(async () => {}); + expect(fake.calls.at(-1)).toMatchObject(build); + expect(useBuildRun.getState()).toMatchObject({ title: "dotnet build", status: "running" }); + const failure = result( + [{ severity: "error", text: "; expected", path: "/p/App/Program.cs", range: null, code: "CS1002" }], + false, + ); + await act(async () => { + fake.resolve(failure); + }); + await ran; + expect(done).toEqual([false]); + expect(notes.at(-1)).toMatchObject({ title: "Build failed: 1 error", level: "error" }); + + void rerunBuild(); + await act(async () => {}); + expect(fake.calls.at(-1)).toMatchObject(build); + await act(async () => { + fake.resolve(result([], true)); + }); + expect(notes.at(-1)).toMatchObject({ level: "info" }); + }); + + it("titles dotnet clean and restore after the command", async () => { + const finish = async (command: string) => { + void executeAction("build.dotnetCommand", { file: "/p/App/App.csproj", command }); + await act(async () => {}); + await act(async () => { + fake.resolve(result([], true)); + }); + return notes.at(-1)?.title; + }; + expect(await finish("clean")).toBe("dotnet clean completed"); + expect(await finish("restore")).toBe("dotnet restore completed"); + }); + it("shows the CMake hammer and builds the selected target through the shared action", async () => { setContext("run.cmakeBuild", "cmake:release:hello:build"); setContext("run.buildTargetName", "hello [Release]"); diff --git a/src/features/build/index.ts b/src/features/build/index.ts index 0cafefdef9..864f60cd09 100644 --- a/src/features/build/index.ts +++ b/src/features/build/index.ts @@ -4,6 +4,7 @@ * the build system of the project or module: Maven, Gradle, Cargo, Go, * TypeScript, CMake or javac. */ +import type { DotnetCommand } from "@/bindings"; import { getContext, type ContextKeys } from "@/platform/context"; import { registerActions } from "@/platform/actions"; import { tx } from "@/platform/i18n"; @@ -22,6 +23,7 @@ import { resetBuildRun, startBuild, startCompileFile, + startDotnetCommand, startDotnetFormat, startDotnetPublish, stopBuild, @@ -175,6 +177,24 @@ export function activate(): () => void { void startDotnetPublish(a.file, a.options); }, }, + // The .NET tool window's Build, Clean and Restore run this; `onDone` gets whether it succeeded. + { + id: "build.dotnetCommand", + title: "Run dotnet build, clean or restore", + category: "Build", + hidden: true, + when: WHEN, + run: async ({ arg }) => { + const a = arg as { + file: string; + command: DotnetCommand; + options?: string[]; + onDone?: (success: boolean) => unknown; + }; + const result = await startDotnetCommand(a.file, a.command, a.options ?? []); + if (result) await a.onDone?.(result.success); + }, + }, { id: "build.stop", title: "Stop Build", diff --git a/src/features/build/store.ts b/src/features/build/store.ts index 9b87e8432c..4566d9ad23 100644 --- a/src/features/build/store.ts +++ b/src/features/build/store.ts @@ -22,6 +22,7 @@ import { type BuildMessage, type BuildResult, type BuildSystem, + type DotnetCommand, type RequestId, } from "@/platform/ipc"; import { useProject } from "@/platform/project"; @@ -92,6 +93,14 @@ export interface BuildBackend { clear: string[], onEvent: (e: BuildEvent) => void, ): Promise; + dotnetCommand( + file: string, + command: DotnetCommand, + options: string[], + request: RequestId, + clear: string[], + onEvent: (e: BuildEvent) => void, + ): Promise; cancel(request: RequestId): void; } @@ -116,6 +125,11 @@ const tauriBackend: BuildBackend = { channel.onmessage = onEvent; return call(commands.buildDotnetPublish(file, options, request, clear, channel)); }, + dotnetCommand(file, command, options, request, clear, onEvent) { + const channel = new Channel(); + channel.onmessage = onEvent; + return call(commands.buildDotnetCommand(file, command, options, request, clear, channel)); + }, cancel(request) { void commands.cancelRequest(request); }, @@ -138,6 +152,8 @@ export interface BuildState { formatVerify: boolean | null; /** Set when the window shows `dotnet publish` of `file`: what followed the project, for Rerun. */ publishOptions: string[] | null; + /** Set when the window shows `dotnet build` / `clean` / `restore` of `file`, for Rerun. */ + dotnetCommand: { command: DotnetCommand; options: string[] } | null; title: string; system: BuildSystem | null; status: BuildStatus | null; @@ -162,6 +178,7 @@ const INITIAL: BuildState = { cmake: null, formatVerify: null, publishOptions: null, + dotnetCommand: null, title: "", system: null, status: null, @@ -272,7 +289,7 @@ async function startDotnetTask( kind: DotnetTask, taskTitle: string, file: string, - state: Pick, "formatVerify" | "publishOptions">, + state: Pick, "formatVerify" | "publishOptions" | "dotnetCommand">, invoke: (request: RequestId, previous: string[], onEvent: (e: BuildEvent) => void) => Promise, ): Promise { if (isBuilding() || !useProject.getState().project) return null; @@ -311,11 +328,31 @@ export function startDotnetPublish(file: string, options: string[]): Promise { + return startDotnetTask( + command === "build" ? "dotnetBuild" : command === "clean" ? "dotnetClean" : "dotnetRestore", + `dotnet ${command}`, + file, + { dotnetCommand: { command, options } }, + (request, files, onEvent) => backend.dotnetCommand(file, command, options, request, files, onEvent), + ); +} + +/** Notification titles of the dotnet tasks; `null` reports errors and warnings like a build. */ const DOTNET_SUMMARIES = { dotnetFormat: ["dotnet format completed", "dotnet format failed"], dotnetPublish: ["dotnet publish completed", "dotnet publish failed"], + dotnetBuild: null, + dotnetClean: ["dotnet clean completed", "dotnet clean failed"], + dotnetRestore: ["dotnet restore completed", "dotnet restore failed"], } as const; type DotnetTask = keyof typeof DOTNET_SUMMARIES; +const isDotnetTask = (kind: string): kind is DotnetTask => kind in DOTNET_SUMMARIES; /** The latest build: its channel may still deliver output after its result (see `executeBuild`). */ let currentBuild: RequestId | null = null; @@ -379,8 +416,8 @@ async function executeBuild( files: messageFiles(result.messages), message: null, }); - const dotnet = meta.kind === "dotnetFormat" || meta.kind === "dotnetPublish" ? meta.kind : null; - const summary = dotnet ? DOTNET_SUMMARIES[dotnet][result.success ? 0 : 1] : finishSummary(result); + const fixed = isDotnetTask(meta.kind) ? DOTNET_SUMMARIES[meta.kind] : null; + const summary = fixed ? fixed[result.success ? 0 : 1] : finishSummary(result); notifications().notify({ group: "run", level: result.success ? (result.warnings ? "warning" : "info") : "error", @@ -393,8 +430,8 @@ async function executeBuild( : [{ label: "Show Build", run: () => toolWindowService().show("build", true) }], }); if (result.success) { - // Formatting and publishing leave nothing for HotSwap and deployment to pick up. - if (meta.kind !== "dotnetFormat" && meta.kind !== "dotnetPublish") + // The .NET tool window's commands leave nothing for HotSwap and deployment to pick up. + if (!isDotnetTask(meta.kind)) notifyBuildCompleted({ kind: meta.kind, file: meta.file, @@ -550,9 +587,10 @@ export function stopBuild() { /** Runs the last build again (the tool window's rerun button). */ export function rerunBuild() { - const { kind, file, cmake, formatVerify, publishOptions } = useBuildRun.getState(); + const { kind, file, cmake, formatVerify, publishOptions, dotnetCommand } = useBuildRun.getState(); if (formatVerify !== null && file) return startDotnetFormat(file, formatVerify); if (publishOptions && file) return startDotnetPublish(file, publishOptions); + if (dotnetCommand && file) return startDotnetCommand(file, dotnetCommand.command, dotnetCommand.options); if (!kind) return file ? startCompileFile(file) : startBuild("build", null); return startBuild(kind, file, true, cmake); } diff --git a/src/features/dotnet/store.test.ts b/src/features/dotnet/store.test.ts index 9b05bc1000..bf9e7bf6b9 100644 --- a/src/features/dotnet/store.test.ts +++ b/src/features/dotnet/store.test.ts @@ -10,13 +10,38 @@ import { selectDotnet, useDotnet, } from "./store"; +import { registerActions } from "@/platform/actions"; import * as platform from "@/platform/dotnet"; import { useProject } from "@/platform/project"; import { EditorService, provideEditorService, provideProjectViewSelection } from "@/workbench/contributions"; +/** What the .NET tool window asked the Build window to run; each one succeeds unless `buildFails`. */ +interface DotnetCommandArg { + file: string; + command: string; + options: string[]; + onDone: (success: boolean) => unknown; +} +const dotnetCommands: DotnetCommandArg[] = []; +let buildFails = false; +registerActions([ + { + id: "build.dotnetCommand", + title: "Run dotnet build, clean or restore", + run: async ({ arg }) => { + const a = arg as DotnetCommandArg; + dotnetCommands.push(a); + await a.onDone(!buildFails); + }, + }, +]); +const ran = () => dotnetCommands.map(({ file, command, options }) => ({ file, command, options })); + afterEach(() => { resetDotnet(); vi.restoreAllMocks(); + dotnetCommands.length = 0; + buildFails = false; }); it("recovers a project that failed the initial workspace scan", async () => { @@ -102,8 +127,6 @@ describe("reloading a .NET workspace", () => { const evaluate = vi .spyOn(platform, "evaluateProject") .mockImplementation(async (_path, _config, framework) => (framework === "net9.0" ? selected : release)); - const command = vi.spyOn(platform, "dotnet").mockResolvedValue(""); - await reloadDotnet(); expect(useDotnet.getState()).toMatchObject({ @@ -114,11 +137,11 @@ describe("reloading a .NET workspace", () => { }); expect(evaluate).toHaveBeenLastCalledWith(path, "Release", "net9.0", expect.any(AbortSignal)); await buildDotnet("build"); - expect(command).toHaveBeenCalledWith( - ["build", path, "--configuration", "Release", "--framework", "net9.0"], - "/repo", - expect.any(AbortSignal), - ); + expect(ran()).toEqual([ + { file: path, command: "build", options: ["--configuration", "Release", "--framework", "net9.0"] }, + ]); + // The built project is evaluated again with the same selection. + expect(evaluate).toHaveBeenLastCalledWith(path, "Release", "net9.0", expect.any(AbortSignal)); }); it("uses a supported configuration and framework when the saved choices were removed", async () => { @@ -232,22 +255,18 @@ describe("acting on the context before the model was ever loaded (#5635)", () => it("loads the workspace once, then builds the project of the active editor's file", async () => { const scan = vi.spyOn(platform, "dotnetWorkspace").mockResolvedValue({ projects: [project], solutions: [] }); vi.spyOn(platform, "evaluateProject").mockResolvedValue(project); - const command = vi.spyOn(platform, "dotnet").mockResolvedValue(""); await buildDotnet("build"); expect(scan).toHaveBeenCalledTimes(1); - expect(command).toHaveBeenCalledWith( - ["build", path, "--configuration", "Debug", "--framework", "net9.0"], - "/repo/src/App", - expect.any(AbortSignal), - ); + expect(ran()).toEqual([ + { file: path, command: "build", options: ["--configuration", "Debug", "--framework", "net9.0"] }, + ]); }); it("shares one workspace load between concurrent context actions", async () => { const scan = vi.spyOn(platform, "dotnetWorkspace").mockResolvedValue({ projects: [project], solutions: [] }); vi.spyOn(platform, "evaluateProject").mockResolvedValue(project); - vi.spyOn(platform, "dotnet").mockResolvedValue(""); await Promise.all([buildDotnet("build"), buildDotnet("build")]); @@ -270,27 +289,21 @@ describe("acting on the context before the model was ever loaded (#5635)", () => it("builds a project selected in the Project view without loading the model", async () => { selectInProjectView(path); const scan = vi.spyOn(platform, "dotnetWorkspace"); - const command = vi.spyOn(platform, "dotnet").mockResolvedValue(""); await buildDotnet("build"); expect(scan).not.toHaveBeenCalled(); - expect(command).toHaveBeenCalledWith( - ["build", path, "--configuration", "Debug"], - "/repo/src/App", - expect.any(AbortSignal), - ); + expect(ran()).toEqual([{ file: path, command: "build", options: ["--configuration", "Debug"] }]); }); it("scans once and stays a no-op in a workspace without .NET projects", async () => { const scan = vi.spyOn(platform, "dotnetWorkspace").mockResolvedValue({ projects: [], solutions: [] }); - const command = vi.spyOn(platform, "dotnet").mockResolvedValue(""); await buildDotnet("build"); await buildDotnet("build"); expect(scan).toHaveBeenCalledTimes(1); - expect(command).not.toHaveBeenCalled(); + expect(ran()).toEqual([]); }); it("retries the workspace load on the next action after a failed scan", async () => { @@ -299,7 +312,6 @@ describe("acting on the context before the model was ever loaded (#5635)", () => .mockRejectedValueOnce(new Error("scan failed")) .mockResolvedValue({ projects: [project], solutions: [] }); vi.spyOn(platform, "evaluateProject").mockResolvedValue(project); - const command = vi.spyOn(platform, "dotnet").mockResolvedValue(""); await buildDotnet("build"); expect(useDotnet.getState().error).toContain("scan failed"); @@ -309,10 +321,64 @@ describe("acting on the context before the model was ever loaded (#5635)", () => expect(scan).toHaveBeenCalledTimes(2); expect(useDotnet.getState().error).toBe(""); - expect(command).toHaveBeenCalledWith( - ["build", path, "--configuration", "Debug", "--framework", "net9.0"], - "/repo/src/App", - expect.any(AbortSignal), - ); + expect(ran()).toEqual([ + { file: path, command: "build", options: ["--configuration", "Debug", "--framework", "net9.0"] }, + ]); + }); +}); + +describe("Build, Clean and Restore run in the Build window (#7853)", () => { + const path = "/repo/App/App.csproj"; + const project: platform.DotnetProject = { + path, + name: "App", + frameworks: ["net9.0"], + configurations: ["Debug", "Release"], + references: [], + packages: [], + test: false, + runner: "vstest", + adapter: "mstest", + trx: false, + }; + beforeEach(() => { + useDotnet.setState({ + model: { projects: [project], solutions: [], errors: [] }, + selected: path, + configuration: "Release", + framework: "net9.0", + }); + }); + + it("builds a whole solution with the chosen configuration and evaluates no project after it", async () => { + const evaluate = vi.spyOn(platform, "evaluateProject"); + const command = vi.spyOn(platform, "dotnet"); + + await buildDotnet("build", "/repo/Big.sln"); + await buildDotnet("clean", "/repo/Big.slnx"); + + expect(ran()).toEqual([ + { file: "/repo/Big.sln", command: "build", options: ["--configuration", "Release"] }, + { file: "/repo/Big.slnx", command: "clean", options: ["--configuration", "Release"] }, + ]); + expect(evaluate).not.toHaveBeenCalled(); + expect(command).not.toHaveBeenCalled(); + expect(useDotnet.getState().output).toBe(""); + }); + + it("audits after a restore that succeeded, and neither evaluates nor audits after a failure", async () => { + const evaluate = vi.spyOn(platform, "evaluateProject").mockResolvedValue(project); + const audit = vi.fn(async () => {}); + + buildFails = true; + await buildDotnet("restore", path, audit); + expect(ran()).toEqual([{ file: path, command: "restore", options: ["-p:Configuration=Release"] }]); + expect(evaluate).not.toHaveBeenCalled(); + expect(audit).not.toHaveBeenCalled(); + + buildFails = false; + await buildDotnet("restore", path, audit); + expect(evaluate).toHaveBeenCalledWith(path, "Release", "net9.0", expect.any(AbortSignal)); + expect(audit).toHaveBeenCalledWith(path); }); }); diff --git a/src/features/dotnet/store.ts b/src/features/dotnet/store.ts index a866ca0ef8..94eb1d7155 100644 --- a/src/features/dotnet/store.ts +++ b/src/features/dotnet/store.ts @@ -205,6 +205,11 @@ export function selectDotnet(path: string, configuration?: string, framework?: s }); } +/** + * Build, clean or restore a solution or project in the Build tool window. The selected project + * keeps its chosen configuration and framework; another project builds with its own defaults. + * A project is evaluated again afterwards; a solution has no project to re-evaluate. + */ export async function buildDotnet( operation: "build" | "restore" | "clean", arg?: unknown, @@ -212,58 +217,25 @@ export async function buildDotnet( ) { const target = await contextTarget(arg); if (!target) return; - // A solution builds as a whole: `dotnet` takes the `.sln` directly, there is no - // project to re-evaluate afterwards. - if (isDotnetSolutionPath(target)) { - const { configuration } = useDotnet.getState(); - return task(async (signal) => ({ - output: await dotnet( - [ - operation, - target, - ...(operation === "restore" ? [`-p:Configuration=${configuration}`] : ["--configuration", configuration]), - ], - dirname(target), - signal, - ), - })); - } - const selected = selectedProject(); - const { framework, configuration } = useDotnet.getState(); - const afterSuccess = operation === "restore" && afterRestore ? () => afterRestore(target) : undefined; - // The selected project keeps its chosen configuration and framework; another - // project builds with its own defaults. - if (selected?.path !== target) + const solution = isDotnetSolutionPath(target); + const { configuration, framework } = useDotnet.getState(); + const own = !solution && selectedProject()?.path === target; + const chosen = solution || own ? configuration : "Debug"; + const options = + operation === "restore" + ? [`-p:Configuration=${chosen}`] + : ["--configuration", chosen, ...(own && framework ? ["--framework", framework] : [])]; + const onDone = (success: boolean) => { + if (!success || solution) return; + const afterSuccess = operation === "restore" && afterRestore ? () => afterRestore(target) : undefined; return task(async (signal) => { - const options = operation === "restore" ? ["-p:Configuration=Debug"] : ["--configuration", "Debug"]; - const output = await dotnet([operation, target, ...options], dirname(target), signal); const model = useDotnet.getState().model; - if (!model.projects.some((p) => p.path === target)) return { output }; - const project = await evaluateProject(target, "Debug", "", signal); - return { - output, - model: { ...model, projects: model.projects.map((item) => (item.path === target ? project : item)) }, - }; + if (!model.projects.some((p) => p.path === target)) return {}; + const project = await evaluateProject(target, own ? configuration : "Debug", own ? framework : "", signal); + return { model: { ...model, projects: model.projects.map((item) => (item.path === target ? project : item)) } }; }, afterSuccess); - return task(async (signal) => { - const output = await dotnet( - [ - operation, - target, - ...(operation === "restore" - ? [`-p:Configuration=${configuration}`] - : ["--configuration", configuration, ...(framework ? ["--framework", framework] : [])]), - ], - dirname(target), - signal, - ); - const project = await evaluateProject(target, configuration, framework, signal); - const model = useDotnet.getState().model; - return { - output, - model: { ...model, projects: model.projects.map((item) => (item.path === target ? project : item)) }, - }; - }, afterSuccess); + }; + await executeAction("build.dotnetCommand", { file: target, command: operation, options, onDone }); } interface PackageJson { diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 8ec44e37f2..07c2501cb3 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1968,6 +1968,11 @@ "Applies saved changes with hot reload or restarts the app. Debug runs without it": "Applies saved changes with hot reload or restarts the app. Debug runs without it", "dotnet publish completed": "dotnet publish completed", "dotnet publish failed": "dotnet publish failed", + "Run dotnet build, clean or restore": "Run dotnet build, clean or restore", + "dotnet clean completed": "dotnet clean completed", + "dotnet clean failed": "dotnet clean failed", + "dotnet restore completed": "dotnet restore completed", + "dotnet restore failed": "dotnet restore failed", "Build .NET Project": "Build .NET Project", "Restore .NET Project": "Restore .NET Project", "Clean .NET Project": "Clean .NET Project", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index c993046242..4b50ffdf1f 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -8860,6 +8860,11 @@ "Applies saved changes with hot reload or restarts the app. Debug runs without it": "保存的改动通过热重载生效,否则重启应用。调试时不使用", "dotnet publish completed": "dotnet publish 已完成", "dotnet publish failed": "dotnet publish 失败", + "Run dotnet build, clean or restore": "运行 dotnet build、clean 或 restore", + "dotnet clean completed": "dotnet clean 已完成", + "dotnet clean failed": "dotnet clean 失败", + "dotnet restore completed": "dotnet restore 已完成", + "dotnet restore failed": "dotnet restore 失败", "Build .NET Project": "构建 .NET 项目", "Restore .NET Project": "还原 .NET 项目", "Clean .NET Project": "清理 .NET 项目",