From 4e5ae49aa9eaf41ad01f2a5de494cc0aa607a943 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Wed, 2 Dec 2026 19:05:25 +0900 Subject: [PATCH] feat(dotnet): edit solutions and project references from the Project view (#7426) Add Existing Project, Add/Remove Project Reference and Remove from Solution on .NET solution and project nodes, running dotnet sln/reference one at a time. Queued edits are cancelled when the workspace changes, the tree refreshes after a partially failed CLI edit, and solution paths are normalized before comparing them. Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- .github/workflows/ci.yml | 3 + e2e/dotnetSolutionEdit.spec.ts | 115 ++++++++ src/features/dotnet/edit.test.ts | 300 +++++++++++++++++++++ src/features/dotnet/edit.ts | 195 ++++++++++++++ src/features/dotnet/edit.untrusted.test.ts | 56 ++++ src/features/dotnet/index.ts | 60 ++++- src/features/dotnet/tree.test.ts | 2 + src/features/dotnet/tree.ts | 1 + src/features/dotnet/window.test.ts | 4 + src/features/project-tree/ProjectView.tsx | 8 + src/features/project-tree/model.ts | 5 + src/platform/dotnet.ts | 8 +- src/platform/locales/text/zh-TW.json | 17 +- src/platform/locales/text/zh.json | 15 ++ src/workbench/contributions.ts | 2 + 15 files changed, 785 insertions(+), 6 deletions(-) create mode 100644 e2e/dotnetSolutionEdit.spec.ts create mode 100644 src/features/dotnet/edit.test.ts create mode 100644 src/features/dotnet/edit.ts create mode 100644 src/features/dotnet/edit.untrusted.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c609eaa0f..6471ff3ba 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -370,6 +370,9 @@ jobs: node-version: 22 cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }} package-manager-cache: ${{ runner.environment != 'self-hosted' }} + # src/features/dotnet/edit.test.ts runs the real `dotnet sln` / `dotnet add reference`. + - uses: actions/setup-dotnet@v5 + with: { dotnet-version: 10.0.x } - run: pnpm install --frozen-lockfile - run: pnpm typecheck - run: pnpm lint diff --git a/e2e/dotnetSolutionEdit.spec.ts b/e2e/dotnetSolutionEdit.spec.ts new file mode 100644 index 000000000..bbc3d7a8a --- /dev/null +++ b/e2e/dotnetSolutionEdit.spec.ts @@ -0,0 +1,115 @@ +/** + * Solution and project-reference edits from the Project view (#7421). The host is stubbed at the IPC + * layer (no `dotnet` runs; `src/features/dotnet/edit.test.ts` runs the real CLI): the spec checks + * the menus and the exact `dotnet` commands they start. + */ +import type { Page } from "@playwright/test"; +import { expect, stubDesktop, test } from "./fixtures"; + +const SHOTS = process.env.E2E_SHOTS; + +/** Stubs the process host: records the `dotnet` argument lists and answers `sln list` with `listed`. */ +async function stubHost(page: Page, listed: string[]) { + await stubDesktop(page); + await page.evaluate( + async ({ listed }) => { + const h = window.__ipc.handlers; + const runs: string[][] = []; + (window as unknown as { __runs: string[][] }).__runs = runs; + let id = 100; + h.run_start = (args) => { + const config = args.config as { args: string[] }; + runs.push(config.args); + const run = ++id; + setTimeout(() => { + const text = config.args[2] === "list" ? `Project(s)\n----------\n${listed.join("\n")}\n` : "ok\n"; + window.__ipc.send(args.onOutput, { kind: "stdout", text }); + window.__ipc.emit({ type: "runExited", run, code: 0 }); + }, 20); + return { id: run, configId: "x", name: "dotnet", pid: 1, running: true, pty: false }; + }; + h["plugin:dialog|open"] = () => ["/dev/acme-api/Lib/Lib.csproj"]; + const storeModule = "/src/features/dotnet/store.ts"; + const { useDotnet } = await import(/* @vite-ignore */ storeModule); + const project = (path: string, name: string, references: string[] = []) => ({ + path, + name, + frameworks: ["net9.0"], + configurations: ["Debug"], + references, + packages: [], + test: false, + runner: "vstest", + adapter: "mstest", + trx: false, + }); + useDotnet.setState({ + model: { + projects: [ + project("/dev/acme-api/App/App.csproj", "App", ["/dev/acme-api/Core/Core.csproj"]), + project("/dev/acme-api/Core/Core.csproj", "Core"), + ], + solutions: [ + { + path: "/dev/acme-api/Acme.sln", + projects: ["/dev/acme-api/App/App.csproj", "/dev/acme-api/Core/Core.csproj"], + }, + ], + }, + }); + }, + { listed }, + ); +} + +const runs = (page: Page) => page.evaluate(() => (window as unknown as { __runs: string[][] }).__runs); + +test("the solution node adds an existing project with dotnet sln add", async ({ workbench: page }) => { + await stubHost(page, ["Lib/Lib.csproj"]); + const solution = page.getByRole("treeitem", { name: /Solution 'Acme'/ }); + await solution.click({ button: "right" }); + await expect(page.getByRole("menuitem", { name: "Build .NET Project" })).toBeVisible(); + if (SHOTS) await page.screenshot({ path: `${SHOTS}/b1-solution-menu.png`, animations: "disabled" }); + await page.getByRole("menuitem", { name: "Add Existing Project…" }).click(); + await expect + .poll(() => runs(page)) + .toContainEqual(["sln", "/dev/acme-api/Acme.sln", "add", "/dev/acme-api/Lib/Lib.csproj"]); + // The project is listed afterwards, so no warning balloon. + await expect(page.getByText("was not added")).toHaveCount(0); +}); + +test("a same-named project the CLI skipped gets a warning", async ({ workbench: page }) => { + await stubHost(page, ["Other/Lib.csproj"]); + await page.getByRole("treeitem", { name: /Solution 'Acme'/ }).click({ button: "right" }); + await page.getByRole("menuitem", { name: "Add Existing Project…" }).click(); + await expect(page.getByText("The project was not added to the solution")).toBeVisible(); + if (SHOTS) await page.screenshot({ path: `${SHOTS}/b1-same-name-warning.png`, animations: "disabled" }); +}); + +test("a project node offers reference and solution edits", async ({ workbench: page }) => { + await stubHost(page, []); + await page.getByRole("treeitem", { name: /Solution 'Acme'/ }).click(); + await page.keyboard.press("ArrowRight"); + const app = page.getByRole("treeitem", { name: "App", exact: true }); + await app.click({ button: "right" }); + await expect(page.getByRole("menuitem", { name: "Add Project Reference…" })).toBeVisible(); + await expect(page.getByRole("menuitem", { name: "Remove Project Reference" })).toBeVisible(); + if (SHOTS) await page.screenshot({ path: `${SHOTS}/b1-project-menu.png`, animations: "disabled" }); + await page.getByRole("menuitem", { name: "Remove from Solution" }).click(); + await expect + .poll(() => runs(page)) + .toContainEqual(["sln", "/dev/acme-api/Acme.sln", "remove", "/dev/acme-api/App/App.csproj"]); +}); + +// The model reloads after each edit (the stubbed workspace has no solution), so each edit gets a test. +test("Remove Project Reference removes the chosen reference", async ({ workbench: page }) => { + await stubHost(page, []); + await page.getByRole("treeitem", { name: /Solution 'Acme'/ }).click(); + await page.keyboard.press("ArrowRight"); + await page.getByRole("treeitem", { name: "App", exact: true }).click({ button: "right" }); + await page.getByRole("menuitem", { name: "Remove Project Reference" }).hover(); + await page.getByRole("menuitem", { name: "Core.csproj" }).click(); + await expect + .poll(() => runs(page)) + .toContainEqual(["remove", "/dev/acme-api/App/App.csproj", "reference", "/dev/acme-api/Core/Core.csproj"]); +}); diff --git a/src/features/dotnet/edit.test.ts b/src/features/dotnet/edit.test.ts new file mode 100644 index 000000000..ed4bf1145 --- /dev/null +++ b/src/features/dotnet/edit.test.ts @@ -0,0 +1,300 @@ +import { execFile, execFileSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +vi.setConfig({ testTimeout: 90_000, hookTimeout: 90_000 }); + +const mocks = vi.hoisted(() => ({ reload: vi.fn(async () => {}), pick: vi.fn(), notify: vi.fn() })); +vi.mock("./store", async (orig) => ({ ...(await orig()), reloadDotnet: mocks.reload })); +vi.mock("@/platform/choosePath", () => ({ choosePaths: mocks.pick })); +// The real `dotnet` CLI stands in for the Tauri process host: the arguments under test run unchanged. +vi.mock("@/platform/dotnet", async (orig) => ({ + ...(await orig()), + dotnet: (args: string[], cwd: string, signal?: AbortSignal) => + new Promise((resolve, reject) => { + const child = execFile( + "dotnet", + args, + { cwd, signal, env: { ...process.env, DOTNET_CLI_UI_LANGUAGE: "en" } }, + (err, out, errOut) => (err ? reject(new Error(`${out}${errOut}`.trim() || err.message)) : resolve(out)), + ); + child.on("error", reject); + }), +})); + +import { useProject } from "@/platform/project"; +import { provideNotificationService } from "@/workbench/contributions"; +import { useDotnet } from "./store"; +import { + addProjectReference, + addProjectsToSolution, + cancelDotnetEdit, + editItems, + referenceArgs, + removeProjectFromSolution, + removeProjectReference, + slnArgs, +} from "./edit"; + +const hasDotnet = (() => { + try { + execFileSync("dotnet", ["--version"], { stdio: "ignore" }); + return true; + } catch { + return false; + } +})(); +// CI installs the SDK (setup-dotnet), so a missing one there must fail, not skip. +const real = it.skipIf(!hasDotnet && !process.env.CI); + +const csproj = (extra = "") => + `net9.0${extra}`; + +let dir = ""; +const file = (rel: string, text = csproj()) => { + const path = join(dir, rel); + mkdirSync(join(path, ".."), { recursive: true }); + writeFileSync(path, text); + return path; +}; +const solution = (format: "sln" | "slnx", name = "App") => { + mkdirSync(join(dir, "sln"), { recursive: true }); + execFileSync("dotnet", ["new", "sln", "-n", name, "--format", format, "-o", join(dir, "sln")], { stdio: "ignore" }); + return join(dir, "sln", `${name}.${format}`); +}; +const read = (path: string) => readFileSync(path, "utf8"); + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "dotnet-edit-")); + mocks.reload.mockClear(); + mocks.notify.mockClear(); + provideNotificationService({ notify: mocks.notify }); +}); +afterEach(() => rmSync(dir, { recursive: true, force: true })); + +describe("CLI arguments", () => { + it("builds solution and reference commands", () => { + expect(slnArgs("add", "/a/App.sln", ["/a/B.csproj"])).toEqual(["sln", "/a/App.sln", "add", "/a/B.csproj"]); + expect(referenceArgs("remove", "/a/A.csproj", ["/b/B.csproj"])).toEqual([ + "remove", + "/a/A.csproj", + "reference", + "/b/B.csproj", + ]); + }); +}); + +it("does not run an edit queued for the previous project", async () => { + const previous = useProject.getState().project; + const projectAt = (root: string) => ({ root }) as NonNullable; + useProject.setState({ project: projectAt("/first") }); + try { + const queued = removeProjectFromSolution("/first/App.sln", "/first/App.csproj"); + useProject.setState({ project: projectAt("/second") }); + await queued; + expect(mocks.notify).not.toHaveBeenCalled(); + expect(mocks.reload).not.toHaveBeenCalled(); + } finally { + useProject.setState({ project: previous }); + } +}); + +describe.each(["sln", "slnx"] as const)("solution edits on .%s (real dotnet CLI)", (format) => { + real("adds a project, then removes it, reloading after each", async () => { + const sln = solution(format); + const project = file("src/Lib/Lib.csproj"); + await addProjectsToSolution(sln, [project]); + expect(read(sln)).toContain("Lib.csproj"); + expect(mocks.reload).toHaveBeenCalledTimes(1); + await removeProjectFromSolution(sln, project); + expect(read(sln)).not.toContain("Lib.csproj"); + expect(mocks.reload).toHaveBeenCalledTimes(2); + expect(mocks.notify).not.toHaveBeenCalled(); + }); + + real("an empty solution gains its first project", async () => { + const sln = solution(format); + expect(read(sln)).not.toContain("proj"); + await addProjectsToSolution(sln, [file("A/A.csproj")]); + expect(read(sln)).toContain("A.csproj"); + }); + + real("adds a project outside the solution folder (relative .. path)", async () => { + const sln = solution(format); + await addProjectsToSolution(sln, [file("elsewhere/Out/Out.csproj")]); + expect(read(sln).replace(/\\/g, "/")).toContain("../elsewhere/Out/Out.csproj"); + }); + + real("handles spaces and non-ASCII (中文) in paths", async () => { + const sln = solution(format); + const project = file("my 项目/测试 App/测试 App.csproj"); + await addProjectsToSolution(sln, [project]); + expect(read(sln)).toContain("测试 App.csproj"); + await removeProjectFromSolution(sln, project); + expect(read(sln)).not.toContain("测试 App.csproj"); + }); + + real("a project that was added raises no warning (relative .. path resolved against the list)", async () => { + const sln = solution(format); + await addProjectsToSolution(sln, [file("out/Out/Out.csproj"), file("in/In.csproj")]); + expect(mocks.notify).not.toHaveBeenCalled(); + }); + + real("adds several picked projects in one command", async () => { + const sln = solution(format); + await addProjectsToSolution(sln, [file("A/A.csproj"), file("B/B.csproj")]); + expect(read(sln)).toContain("A.csproj"); + expect(read(sln)).toContain("B.csproj"); + }); + + real("same-named projects from two folders: the CLI keeps the first and a warning names the other", async () => { + const sln = solution(format); + await addProjectsToSolution(sln, [file("one/Core/Core.csproj"), file("two/Core/Core.csproj")]); + // `dotnet sln add` matches by file name and exits 0 with "already contains project". + expect(read(sln).match(/Core\.csproj/g)).toHaveLength(1); + expect(mocks.notify).toHaveBeenCalledTimes(1); + expect(mocks.notify.mock.calls[0]![0]).toMatchObject({ + level: "warning", + body: expect.stringContaining("Core.csproj"), + }); + expect(mocks.reload).toHaveBeenCalledTimes(1); + }); + + real("removes a project whose file was deleted from disk", async () => { + const sln = solution(format); + const project = file("Gone/Gone.csproj"); + await addProjectsToSolution(sln, [project]); + rmSync(join(dir, "Gone"), { recursive: true }); + await removeProjectFromSolution(sln, project); + // The CLI refuses a missing file on some SDKs: either it is gone from the file, or an error was reported. + expect(read(sln).includes("Gone.csproj") ? mocks.notify.mock.calls.length : 1).toBeGreaterThan(0); + }); + + real("a project in two solutions is edited in one only", async () => { + const a = solution(format, "A"); + const b = solution(format, "B"); + const project = file("Shared/Shared.csproj"); + await addProjectsToSolution(a, [project]); + await addProjectsToSolution(b, [project]); + await removeProjectFromSolution(a, project); + expect(read(a)).not.toContain("Shared.csproj"); + expect(read(b)).toContain("Shared.csproj"); + }); + + real("reports a CLI failure and refreshes the model after the process exits", async () => { + const sln = solution(format); + await addProjectsToSolution(sln, [join(dir, "missing/Nope.csproj")]); + expect(mocks.notify).toHaveBeenCalledTimes(1); + expect(mocks.notify.mock.calls[0]![0]).toMatchObject({ + level: "error", + title: expect.stringContaining("solution"), + }); + expect(mocks.reload).toHaveBeenCalledTimes(1); + }); + + real("a read-only solution file fails with a notification", async () => { + if (process.platform === "win32" || process.getuid?.() === 0) return; + const sln = solution(format); + execFileSync("chmod", ["444", sln]); + await addProjectsToSolution(sln, [file("A/A.csproj")]); + expect(mocks.notify).toHaveBeenCalledTimes(1); + expect(mocks.reload).toHaveBeenCalledTimes(1); + }); + + real("concurrent edits run one after another and both land", async () => { + const sln = solution(format); + await Promise.all([ + addProjectsToSolution(sln, [file("A/A.csproj")]), + addProjectsToSolution(sln, [file("B/B.csproj")]), + ]); + expect(read(sln)).toContain("A.csproj"); + expect(read(sln)).toContain("B.csproj"); + expect(mocks.reload).toHaveBeenCalledTimes(2); + }); + + it("no pick means no command", async () => { + mocks.pick.mockResolvedValue([]); + await addProjectsToSolution("/nowhere/App.sln"); + expect(mocks.notify).not.toHaveBeenCalled(); + expect(mocks.reload).not.toHaveBeenCalled(); + }); +}); + +describe("project reference edits (real dotnet CLI)", () => { + real("adds and removes a reference, also for a multi-targeted project", async () => { + const lib = file("Lib/Lib.csproj", csproj().replace("net9.0", "net8.0")); + const app = file( + "App/App.csproj", + csproj().replace( + "net9.0", + "net8.0;net9.0", + ), + ); + await addProjectReference(app, lib); + expect(read(app)).toContain("ProjectReference"); + await removeProjectReference(app, lib); + expect(read(app)).not.toContain("ProjectReference"); + expect(mocks.reload).toHaveBeenCalledTimes(2); + expect(mocks.notify).not.toHaveBeenCalled(); + }); + + real("handles spaces and non-ASCII in the referenced path", async () => { + const lib = file("库 文件/库 Lib/库 Lib.csproj"); + const app = file("App/App.csproj"); + await addProjectReference(app, lib); + expect(read(app)).toContain("库 Lib.csproj"); + }); + + real("reports a reference to a missing project", async () => { + const app = file("App/App.csproj"); + await addProjectReference(app, join(dir, "nope/Nope.csproj")); + expect(mocks.notify).toHaveBeenCalledTimes(1); + expect(mocks.reload).toHaveBeenCalledTimes(1); + }); + + real("cancelling a queued edit reports nothing and skips the reload", async () => { + const sln = solution("sln"); + const running = addProjectsToSolution(sln, [file("A/A.csproj")]); + cancelDotnetEdit(); + await running; + expect(mocks.notify).not.toHaveBeenCalled(); + expect(mocks.reload).not.toHaveBeenCalled(); + }); +}); + +describe("Project view menu items", () => { + const project = (path: string, references: string[] = []) => ({ path, name: path, references }) as never; + beforeEach(() => { + useDotnet.setState({ + model: { + projects: [project("/s/A/A.csproj", ["/s/B/B.csproj"]), project("/s/B/B.csproj")], + solutions: [ + { path: "/s/One.sln", projects: ["/s/A/A.csproj"] }, + { path: "/s/Two.slnx", projects: ["/s/A/A.csproj"] }, + ], + }, + }); + }); + afterEach(() => useDotnet.setState({ model: { projects: [], solutions: [] } })); + + it("a solution offers Add Existing Project", () => { + expect(editItems("/s/One.sln")).toContainEqual( + expect.objectContaining({ action: "dotnet.solution.addProject", arg: { solution: "/s/One.sln" } }), + ); + }); + + it("a project offers add / remove reference and one removal per owning solution", () => { + const items = editItems("/s/A/A.csproj"); + expect(items.filter((i) => "action" in i && i.action === "dotnet.solution.removeProject")).toHaveLength(2); + expect(items.some((i) => "submenu" in i)).toBe(true); + expect(items).toContainEqual(expect.objectContaining({ action: "dotnet.project.addReference" })); + }); + + it("a project without references or solutions offers only Add Project Reference", () => { + const items = editItems("/s/B/B.csproj"); + expect(items.some((i) => "submenu" in i)).toBe(false); + expect(items.filter((i) => "action" in i)).toHaveLength(1); + }); +}); diff --git a/src/features/dotnet/edit.ts b/src/features/dotnet/edit.ts new file mode 100644 index 000000000..af7cf68d4 --- /dev/null +++ b/src/features/dotnet/edit.ts @@ -0,0 +1,195 @@ +/** + * Solution and project-reference edits from the Project view (#7421): `dotnet sln add|remove` + * and `dotnet add|remove reference` through the same trusted, cancellable process host as + * Build / Restore / Clean. Edits run one at a time (two writers on one `.sln` would race); + * afterwards the workspace reloads so the tree shows the new state, and a CLI failure + * surfaces as a notification. + */ +import { dotnet, dotnetAbsolutePath } from "@/platform/dotnet"; +import { IpcError } from "@/platform/ipc"; +import { tx } from "@/platform/i18n"; +import { choosePaths } from "@/platform/choosePath"; +import { basename, dirname, useProject } from "@/platform/project"; +import type { MenuItem } from "@/ui/Menu"; +import { notifications } from "@/workbench/contributions"; +import { reloadDotnet, useDotnet } from "./store"; +import { isDotnetSolutionPath } from "./target"; + +let queue: Promise = Promise.resolve(); +/** Edits that are queued or running: Cancel aborts all of them. */ +const pending = new Set(); + +export const cancelDotnetEdit = () => pending.forEach((c) => c.abort()); + +/** The CLI arguments of an edit; `solution` and `project` are absolute paths. */ +export const slnArgs = (op: "add" | "remove", solution: string, projects: string[]) => [ + "sln", + solution, + op, + ...projects, +]; +export const referenceArgs = (op: "add" | "remove", project: string, references: string[]) => [ + op, + project, + "reference", + ...references, +]; + +/** + * `dotnet sln add` exits 0 without adding a project whose file name another project of the + * solution already has ("already contains project"); the projects missing from `dotnet sln list` + * afterwards are warned about instead of passing as added. + */ +async function warnIfNotAdded(solution: string, projects: string[], signal: AbortSignal) { + let output: string; + try { + output = await dotnet(["sln", solution, "list"], dirname(solution), signal); + } catch { + return; // The add itself succeeded; a failing list is not worth a false alarm. + } + const listed = output + .split(/\r?\n/) + .filter((line) => /\.(?:cs|fs|vb)proj$/i.test(line.trim())) + .map((line) => dotnetAbsolutePath(dirname(solution), line.trim())); + const missing = projects.filter((path) => !listed.includes(dotnetAbsolutePath(dirname(solution), path))); + const names = missing.map(basename).join(", "); + if (missing.length) + notifications().notify({ + level: "warning", + title: tx("The project was not added to the solution"), + body: tx`The solution already contains a project with the same name as ${names}.`, + group: "tools", + }); +} + +/** Runs `args` after the edits queued before it, then reloads the model. */ +function run( + title: string, + args: string[], + cwd: string, + check?: (signal: AbortSignal) => Promise, +): Promise { + const root = useProject.getState().project?.root; + const stillInProject = () => useProject.getState().project?.root === root; + const abort = new AbortController(); + const unsubscribe = useProject.subscribe(() => { + if (!stillInProject()) abort.abort(); + }); + pending.add(abort); + const next = queue + .catch(() => {}) + .then(async () => { + try { + if (abort.signal.aborted) return; + let refresh = false; + try { + await dotnet(args, cwd, abort.signal); + refresh = true; + await check?.(abort.signal); + } catch (e) { + // A CLI process can have written part of a multi-entry edit before failing. + // An IPC rejection means the process could not be started. + refresh ||= !(e instanceof IpcError); + if (!abort.signal.aborted) + notifications().notify({ level: "error", title, body: String(e).trim(), group: "tools" }); + } + if (refresh && stillInProject()) await reloadDotnet(); + } finally { + unsubscribe(); + pending.delete(abort); + } + }); + queue = next; + return next; +} + +const PROJECT_FILTER = [{ name: ".NET project", extensions: ["csproj", "fsproj", "vbproj"] }]; + +export async function addProjectsToSolution(solution: string, projects?: string[]) { + const root = useProject.getState().project?.root; + const picked = + projects ?? + (await choosePaths({ + directory: false, + title: tx("Add Existing Project"), + defaultPath: dirname(solution), + filters: PROJECT_FILTER, + })); + if (!picked.length || useProject.getState().project?.root !== root) return; + return run( + tx("Could not add the project to the solution"), + slnArgs("add", solution, picked), + dirname(solution), + (signal) => warnIfNotAdded(solution, picked, signal), + ); +} + +export function removeProjectFromSolution(solution: string, project: string) { + return run( + tx("Could not remove the project from the solution"), + slnArgs("remove", solution, [project]), + dirname(solution), + ); +} + +export async function addProjectReference(project: string, reference?: string) { + const root = useProject.getState().project?.root; + const picked = + reference ?? + (await choosePaths({ + directory: false, + title: tx("Add Project Reference"), + defaultPath: dirname(project), + filters: PROJECT_FILTER, + })); + const list = typeof picked === "string" ? [picked] : picked; + if (!list.length || useProject.getState().project?.root !== root) return; + return run(tx("Could not add the project reference"), referenceArgs("add", project, list), dirname(project)); +} + +export function removeProjectReference(project: string, reference: string) { + return run( + tx("Could not remove the project reference"), + referenceArgs("remove", project, [reference]), + dirname(project), + ); +} + +/** #7421: the solution / reference edits of a solution or project node. */ +const solutionName = (path: string) => basename(path).replace(/\.slnx?$/i, ""); + +export function editItems(path: string): MenuItem[] { + const { model } = useDotnet.getState(); + if (isDotnetSolutionPath(path)) + return [ + { kind: "separator" }, + { kind: "action", action: "dotnet.solution.addProject", arg: { solution: path }, label: "Add Existing Project…" }, + ]; + const solutions = model.solutions.filter((s) => s.projects.includes(path)); + const references = model.projects.find((p) => p.path === path)?.references ?? []; + return [ + { kind: "separator" }, + { kind: "action", action: "dotnet.project.addReference", arg: { project: path }, label: "Add Project Reference…" }, + ...(references.length + ? [ + { + label: "Remove Project Reference", + submenu: references.map((reference): MenuItem => ({ + kind: "action", + action: "dotnet.project.removeReference", + arg: { project: path, reference }, + label: basename(reference), + verbatim: true, + })), + } satisfies MenuItem, + ] + : []), + ...solutions.map((s): MenuItem => ({ + kind: "action", + action: "dotnet.solution.removeProject", + arg: { solution: s.path, project: path }, + label: solutions.length > 1 ? tx`Remove from Solution '${solutionName(s.path)}'` : "Remove from Solution", + verbatim: solutions.length > 1, + })), + ]; +} diff --git a/src/features/dotnet/edit.untrusted.test.ts b/src/features/dotnet/edit.untrusted.test.ts new file mode 100644 index 000000000..34cbee8a5 --- /dev/null +++ b/src/features/dotnet/edit.untrusted.test.ts @@ -0,0 +1,56 @@ +/** + * Restricted Mode: every edit goes through `dotnet()` → `run_start`, which the backend refuses in an + * untrusted project (`crates/ide-host/tests/rpc.rs` asserts that for `run_start`). Here the real + * `dotnet()` wrapper meets that refusal: nothing is reloaded, the user gets the error, and no + * process or file is involved. + */ +import { beforeEach, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + runStart: vi.fn(async () => ({ + status: "error" as const, + error: { kind: "unavailable", message: "Restricted Mode: trust this project to run it" }, + })), + notify: vi.fn(), + reload: vi.fn(async () => {}), +})); +vi.mock("@/platform/ipc", async (original) => { + const real = await original(); + return { + ...real, + commands: { ...real.commands, runStart: mocks.runStart }, + ideEventsReady: async () => {}, + onIdeEvent: () => () => {}, + }; +}); +vi.mock("@tauri-apps/api/core", async (original) => ({ + ...(await original()), + Channel: class { + onmessage: unknown; + }, +})); +vi.mock("./store", async (orig) => ({ ...(await orig()), reloadDotnet: mocks.reload })); + +import { provideNotificationService } from "@/workbench/contributions"; +import { addProjectReference, addProjectsToSolution, removeProjectFromSolution, removeProjectReference } from "./edit"; + +beforeEach(() => { + vi.clearAllMocks(); + provideNotificationService({ notify: mocks.notify }); +}); + +it.each([ + ["add project to solution", () => addProjectsToSolution("/s/App.sln", ["/s/A/A.csproj"])], + ["remove project from solution", () => removeProjectFromSolution("/s/App.sln", "/s/A/A.csproj")], + ["add project reference", () => addProjectReference("/s/A/A.csproj", "/s/B/B.csproj")], + ["remove project reference", () => removeProjectReference("/s/A/A.csproj", "/s/B/B.csproj")], +])("%s is refused in an untrusted project", async (_name, edit) => { + await edit(); + expect(mocks.runStart).toHaveBeenCalledTimes(1); + expect(mocks.notify).toHaveBeenCalledTimes(1); + expect(mocks.notify.mock.calls[0]![0]).toMatchObject({ + level: "error", + body: expect.stringContaining("Restricted Mode"), + }); + expect(mocks.reload).not.toHaveBeenCalled(); +}); diff --git a/src/features/dotnet/index.ts b/src/features/dotnet/index.ts index b151f455b..d38bcd679 100644 --- a/src/features/dotnet/index.ts +++ b/src/features/dotnet/index.ts @@ -15,6 +15,14 @@ import { searchPackages, selectDotnet, } from "./store"; +import { + addProjectReference, + addProjectsToSolution, + cancelDotnetEdit, + editItems, + removeProjectFromSolution, + removeProjectReference, +} from "./edit"; import { isDotnetProjectPath, isDotnetSolutionPath } from "./target"; import { activateTree } from "./tree"; @@ -40,7 +48,56 @@ export function activate() { when: "projectOpen", run: () => reloadDotnet(), }, - { id: "dotnet.cancel", title: "Cancel .NET Operation", category: "Build", run: () => cancelDotnet() }, + { + id: "dotnet.cancel", + title: "Cancel .NET Operation", + category: "Build", + run: () => { + cancelDotnet(); + cancelDotnetEdit(); + }, + }, + // #7421: solution and project-reference edits; the Project view menu passes the paths. + { + id: "dotnet.solution.addProject", + title: "Add Existing Project to Solution", + category: "Build", + hidden: true, + run: ({ arg }) => { + const a = arg as { solution: string; projects?: string[] }; + return addProjectsToSolution(a.solution, a.projects); + }, + }, + { + id: "dotnet.solution.removeProject", + title: "Remove Project from Solution", + category: "Build", + hidden: true, + run: ({ arg }) => { + const a = arg as { solution: string; project: string }; + return removeProjectFromSolution(a.solution, a.project); + }, + }, + { + id: "dotnet.project.addReference", + title: "Add Project Reference", + category: "Build", + hidden: true, + run: ({ arg }) => { + const a = arg as { project: string; reference?: string }; + return addProjectReference(a.project, a.reference); + }, + }, + { + id: "dotnet.project.removeReference", + title: "Remove Project Reference", + category: "Build", + hidden: true, + run: ({ arg }) => { + const a = arg as { project: string; reference: string }; + return removeProjectReference(a.project, a.reference); + }, + }, { id: "dotnet.select", title: "Select .NET Project", @@ -127,6 +184,7 @@ export function activate() { { kind: "action", action: "dotnet.build", arg: path }, { kind: "action", action: "dotnet.restore", arg: path }, { kind: "action", action: "dotnet.clean", arg: path }, + ...editItems(path), ]; }, }), diff --git a/src/features/dotnet/tree.test.ts b/src/features/dotnet/tree.test.ts index e101832f7..81790b9f7 100644 --- a/src/features/dotnet/tree.test.ts +++ b/src/features/dotnet/tree.test.ts @@ -99,6 +99,8 @@ describe("the .NET solution tree", () => { ["App", "/repo/src/App/App.csproj", true], ["App.Tests", "/repo/tests/App.Tests/App.Tests.csproj", true], ]); + // The group node's context menu is its `.sln`'s (#7421). + expect(solution.menuPath).toBe("/repo/App.sln"); }); it("shows the solution label through the tx template", async () => { diff --git a/src/features/dotnet/tree.ts b/src/features/dotnet/tree.ts index 721520824..1618ae62f 100644 --- a/src/features/dotnet/tree.ts +++ b/src/features/dotnet/tree.ts @@ -104,6 +104,7 @@ export function treeRoots( id: solutionId(solution.path), label: tx`Solution '${solutionName(solution.path)}'`, icon: ICON, + menuPath: solution.path, beforeProject: true, children: solution.projects.map(leaf), }); diff --git a/src/features/dotnet/window.test.ts b/src/features/dotnet/window.test.ts index 2aaa616bc..8fd19562f 100644 --- a/src/features/dotnet/window.test.ts +++ b/src/features/dotnet/window.test.ts @@ -72,12 +72,16 @@ describe("standalone .NET tool window removal", () => { "dotnet.restore /repo/src/App/App.csproj", "dotnet.clean /repo/src/App/App.csproj", "separator", + "dotnet.project.addReference [object Object]", + "separator", ]); expect(actions("/repo/Demo.sln")).toEqual([ "dotnet.build /repo/Demo.sln", "dotnet.restore /repo/Demo.sln", "dotnet.clean /repo/Demo.sln", "separator", + "dotnet.solution.addProject [object Object]", + "separator", ]); expect(actions("/repo/src/App/Program.cs")).toEqual([]); }); diff --git a/src/features/project-tree/ProjectView.tsx b/src/features/project-tree/ProjectView.tsx index 1f18f69e3..cad326053 100644 --- a/src/features/project-tree/ProjectView.tsx +++ b/src/features/project-tree/ProjectView.tsx @@ -35,6 +35,7 @@ import { OWNS_FILE_DROP, getFileDecoration, opensExternally, + menuGroupItems, prepareMenuGroups, useFileDecoration, useFileDecorations, @@ -750,6 +751,13 @@ export function ProjectView() { } const nodes = [...sel].map((k) => m.byKey.get(k)).filter((n): n is ProjectNode => !!n && !n.placeholder); const target = nodes.length ? nodes : [node]; + const menuPath = target.length === 1 ? target[0]!.menuPath : undefined; + if (menuPath) { + // A solution group: only the contributed items of its `.sln` (Build, Add Existing Project…). + const items = menuGroupItems("projectView", { paths: [menuPath], dirs: [false] }); + if (items.length) showContextMenu(e, items); + return; + } if (target.every((n) => n.group) || target.some((n) => n.member)) return; // Contributed groups and collapsed library folders may read the filesystem first (bounded wait). const at = { x: e.clientX, y: e.clientY }; diff --git a/src/features/project-tree/model.ts b/src/features/project-tree/model.ts index 23a225432..b51457301 100644 --- a/src/features/project-tree/model.ts +++ b/src/features/project-tree/model.ts @@ -61,6 +61,8 @@ export interface ProjectNode { detail?: string; /** A node grouping other nodes, without a folder of its own ("External Libraries"). */ group?: boolean; + /** A group node: the file whose context-menu groups its menu shows (a solution's `.sln`). */ + menuPath?: string; /** Library sources: no new / rename / move / delete. */ readOnly?: boolean; /** A declaration of the file itself ("Show Members"); navigating lands on its `selection_range`. */ @@ -293,6 +295,8 @@ export interface ExtraRoot { file?: boolean; children?: readonly ExtraRoot[]; detail?: string; + /** A group node: the file whose context-menu groups the node shows. */ + menuPath?: string; readOnly?: boolean; /** Listed above the project folder (IDEA's module group of the build). */ beforeProject?: boolean; @@ -456,6 +460,7 @@ export function withExtraRoots( icon: extra.icon, detail: extra.detail, group: true, + menuPath: extra.menuPath, readOnly: true, }; out.byKey.set(key, node); diff --git a/src/platform/dotnet.ts b/src/platform/dotnet.ts index a436fdf3f..b27387e8a 100644 --- a/src/platform/dotnet.ts +++ b/src/platform/dotnet.ts @@ -92,7 +92,7 @@ export function jsonOutput>(text: string): T { return JSON.parse(text.slice(start, end + 1)); } -function absolute(base: string, relative: string): string { +export function dotnetAbsolutePath(base: string, relative: string): string { const path = relative.replace(/\\/g, "/"); if (/^(?:[A-Za-z]:\/|\/)/.test(path)) return path; const parts = base.replace(/\\/g, "/").split("/"); @@ -109,7 +109,7 @@ export function solutionPaths(text: string, xml: boolean, dir: string): string[] (p) => p.getAttribute("Path") || "", ) : Array.from(text.matchAll(/^Project\([^\r\n]+?=\s*"[^"]*",\s*"([^"]+)"/gm), (m) => m[1]!); - return [...new Set(names.filter((p) => /\.(?:cs|fs|vb)proj$/i.test(p)).map((p) => absolute(dir, p)))]; + return [...new Set(names.filter((p) => /\.(?:cs|fs|vb)proj$/i.test(p)).map((p) => dotnetAbsolutePath(dir, p)))]; } export function globalRunner(text: string): DotnetRunner { @@ -185,7 +185,7 @@ export async function evaluateProject( name: p.MSBuildProjectName || path.split("/").at(-1) || path, frameworks: (p.TargetFrameworks || p.TargetFramework || "").split(";").filter(Boolean), configurations: (p.Configurations || "Debug;Release").split(";"), - references: (data.Items?.ProjectReference ?? []).map((x) => absolute(dirname(path), x.Identity!)), + references: (data.Items?.ProjectReference ?? []).map((x) => dotnetAbsolutePath(dirname(path), x.Identity!)), packages, test: p.IsTestProject === "true" || @@ -274,7 +274,7 @@ export async function prepareDotnetTest(config: RunConfig): Promise { const root = useProject.getState().project?.root; if (!root || !config.params?.project) return config; let project = await evaluateProject( - absolute(root, config.params.project), + dotnetAbsolutePath(root, config.params.project), config.params.configuration, config.params.framework, ); diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index 374270bd4..55ce8d4b6 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -9663,5 +9663,20 @@ "unsupported manifest": "不支援的清單格式", "Plugins installed by each agent harness, grouped by harness and scope. Changes update the harness's own configuration without staging or converting plugin files.": "依代理與作用域顯示各代理原生安裝的外掛。變更會寫入目標代理自己的設定,不會暫存或轉換外掛檔案。", "Replace the existing plugin directory": "取代既有的外掛目錄", - "Copilot enables plugins for one repository only when they come from a marketplace.": "Copilot 僅能為單一儲存庫啟用來自外掛市場的外掛。" + "Copilot enables plugins for one repository only when they come from a marketplace.": "Copilot 僅能為單一儲存庫啟用來自外掛市場的外掛。", + "Add Existing Project": "加入現有專案", + "Could not add the project to the solution": "無法將專案加入方案", + "Could not remove the project from the solution": "無法從方案中移除專案", + "Add Project Reference": "加入專案參考", + "Could not add the project reference": "無法加入專案參考", + "Could not remove the project reference": "無法移除專案參考", + "Add Existing Project…": "加入現有專案…", + "Add Project Reference…": "加入專案參考…", + "Remove Project Reference": "移除專案參考", + "Remove from Solution": "從方案中移除", + "Add Existing Project to Solution": "將現有專案加入方案", + "Remove Project from Solution": "從方案中移除專案", + "Remove from Solution '{name}'": "從方案 '{name}' 中移除", + "The project was not added to the solution": "專案未加入方案", + "The solution already contains a project with the same name as {names}.": "方案中已有與 {names} 同名的專案。" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 101acfb3d..c40872f50 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -11986,5 +11986,20 @@ "Use letters, digits, spaces, hyphens and underscores, starting with a letter, digit or underscore": "只能使用字母、数字、空格、连字符和下划线,并以字母、数字或下划线开头", "iOS": "iOS", "macOS": "macOS", + "Add Existing Project": "添加现有项目", + "Could not add the project to the solution": "无法将项目添加到解决方案", + "Could not remove the project from the solution": "无法从解决方案中移除项目", + "Add Project Reference": "添加项目引用", + "Could not add the project reference": "无法添加项目引用", + "Could not remove the project reference": "无法移除项目引用", + "Add Existing Project…": "添加现有项目…", + "Add Project Reference…": "添加项目引用…", + "Remove Project Reference": "移除项目引用", + "Remove from Solution": "从解决方案中移除", + "Add Existing Project to Solution": "将现有项目添加到解决方案", + "Remove Project from Solution": "从解决方案中移除项目", + "Remove from Solution '{name}'": "从解决方案 '{name}' 中移除", + "The project was not added to the solution": "项目未添加到解决方案", + "The solution already contains a project with the same name as {names}.": "解决方案中已有与 {names} 同名的项目。", "Language server updates are available": "语言服务器有可用更新" } diff --git a/src/workbench/contributions.ts b/src/workbench/contributions.ts index 29f968aff..1603d52db 100644 --- a/src/workbench/contributions.ts +++ b/src/workbench/contributions.ts @@ -1536,6 +1536,8 @@ export interface ProjectViewRootEntry { children?: readonly ProjectViewRootEntry[]; /** Grey text after the label ("library root"). */ detail?: string; + /** A group node: the file whose Project view context-menu groups the node shows (a solution's `.sln`). */ + menuPath?: string; /** Library sources: shown read-only (no new / rename / move / delete). */ readOnly?: boolean; }