From 70fe0e66534812e585ab61c5166aa269c85561be Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Wed, 2 Dec 2026 19:21:34 +0900 Subject: [PATCH] feat(nuget): manage NuGet package sources (#7424) A Package sources panel lists NuGet sources and adds, enables, disables or removes them through dotnet nuget, writing to a chosen NuGet.Config under the workspace or the user-wide file. Edits go only to the config file that defines a source, stale work is cancelled when the project or selection changes, and URL credentials are redacted from errors. CI installs SDK 10 and 11 for the real-CLI tests. Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- .github/workflows/ci.yml | 7 +- e2e/dotnetHost.ts | 95 ++++++++++ e2e/nugetSources.spec.ts | 134 ++++++++++++++ src/features/dotnet/NugetView.tsx | 2 + src/features/dotnet/SourcesPanel.test.tsx | 65 +++++++ src/features/dotnet/SourcesPanel.tsx | 85 +++++++++ src/features/dotnet/cliTestkit.ts | 100 +++++++++++ src/features/dotnet/index.ts | 25 ++- src/features/dotnet/sources.cli.test.ts | 159 ++++++++++++++++ src/features/dotnet/sources.test.ts | 86 +++++++++ src/features/dotnet/sources.ts | 210 ++++++++++++++++++++++ src/platform/locales/text/en.json | 14 ++ src/platform/locales/text/zh-TW.json | 13 ++ src/platform/locales/text/zh.json | 13 ++ 14 files changed, 1005 insertions(+), 3 deletions(-) create mode 100644 e2e/dotnetHost.ts create mode 100644 e2e/nugetSources.spec.ts create mode 100644 src/features/dotnet/SourcesPanel.test.tsx create mode 100644 src/features/dotnet/SourcesPanel.tsx create mode 100644 src/features/dotnet/cliTestkit.ts create mode 100644 src/features/dotnet/sources.cli.test.ts create mode 100644 src/features/dotnet/sources.test.ts create mode 100644 src/features/dotnet/sources.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6471ff3ba..8e03faf83 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -370,9 +370,12 @@ 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`. + # src/features/dotnet/edit.test.ts and *.cli.test.ts run the real `dotnet` CLI; with CI set they fail, not skip, when it is missing. - uses: actions/setup-dotnet@v5 - with: { dotnet-version: 10.0.x } + with: + dotnet-version: | + 10.0.x + 11.0.x - run: pnpm install --frozen-lockfile - run: pnpm typecheck - run: pnpm lint diff --git a/e2e/dotnetHost.ts b/e2e/dotnetHost.ts new file mode 100644 index 000000000..6e84cd19b --- /dev/null +++ b/e2e/dotnetHost.ts @@ -0,0 +1,95 @@ +/** + * A stubbed `dotnet` process host for the NuGet window specs. No CLI runs: `window.__dotnetOut` + * (set by the spec) answers each argument list, and a thrown message becomes a non-zero exit. + * The real-CLI vitest tests (`src/features/dotnet/*.cli.test.ts`) are the evidence for what + * `dotnet` actually does; these specs check the UI and the exact commands it starts. + */ +import type { Locator, Page } from "@playwright/test"; +import { stubDesktop } from "./fixtures"; + +declare global { + interface Window { + __runs: string[][]; + __dotnetOut: (args: string[]) => string; + } +} + +/** One project, `/dev/acme/src/App/App.csproj`, in the workspace rooted at `/dev/acme`. */ +export const PROJECT = "/dev/acme/src/App/App.csproj"; + +export async function installDotnetHost(page: Page) { + await stubDesktop(page); + await page.evaluate( + async ({ project }) => { + window.__runs = []; + window.__dotnetOut = () => ""; + let id = 100; + window.__ipc.handlers.run_start = (args) => { + const config = args.config as { args: string[] }; + window.__runs.push(config.args); + const run = ++id; + setTimeout(() => { + let text: string; + let code = 0; + try { + text = window.__dotnetOut(config.args); + } catch (e) { + text = (e as Error).message; + code = 1; + } + window.__ipc.send(args.onOutput, { kind: "stdout", text }); + window.__ipc.emit({ type: "runExited", run, code }); + }, 20); + return { id: run, configId: "x", name: "dotnet", pid: 1, running: true, pty: false }; + }; + const dotnetStore = "/src/features/dotnet/store.ts"; + const projectStore = "/src/platform/project.ts"; + const { useDotnet } = await import(/* @vite-ignore */ dotnetStore); + const { useProject } = await import(/* @vite-ignore */ projectStore); + useProject.setState({ project: { ...useProject.getState().project, root: "/dev/acme" } }); + useDotnet.setState({ + model: { + projects: [ + { + path: project, + name: "App", + frameworks: ["net9.0"], + configurations: ["Debug"], + references: [], + packages: [], + test: false, + runner: "vstest", + adapter: "mstest", + trx: false, + }, + ], + solutions: [], + }, + selected: project, + framework: "net9.0", + }); + }, + { project: PROJECT }, + ); +} + +export const dotnetRuns = (page: Page) => page.evaluate(() => window.__runs); + +/** Opens the NuGet Packages tool window through its action. */ +export async function openNuget(page: Page) { + await page.evaluate(async () => { + const actions = "/src/platform/actions.ts"; + const { executeAction } = await import(/* @vite-ignore */ actions); + await executeAction("dotnet.packages"); + }); +} + +const SHOTS = process.env.E2E_SHOTS; +/** With `E2E_SHOTS` set: a screenshot of the NuGet Packages window scrolled to `focus` (fixture data only). */ +export async function shot(page: Page, name: string, focus: Locator) { + if (!SHOTS) return; + await focus.scrollIntoViewIfNeeded(); + await page + .locator('section[aria-label="NuGet Packages"]') + .screenshot({ path: `${SHOTS}/${name}.png`, animations: "disabled" }); +} diff --git a/e2e/nugetSources.spec.ts b/e2e/nugetSources.spec.ts new file mode 100644 index 000000000..cce820039 --- /dev/null +++ b/e2e/nugetSources.spec.ts @@ -0,0 +1,134 @@ +/** + * Package sources in the NuGet Packages window (#7420) over a stubbed `dotnet` host + * (`dotnetHost.ts`): the spec checks what the window shows and the exact commands it starts; + * `src/features/dotnet/sources.cli.test.ts` runs the real CLI. + */ +import { expect, test } from "./fixtures"; +import { dotnetRuns, installDotnetHost, openNuget, shot } from "./dotnetHost"; + +const CONFIG = "/dev/acme/NuGet.Config"; +const USER_CONFIG = "/Users/dev/.nuget/NuGet/NuGet.Config"; + +async function stubSources(page: Parameters[0]) { + await installDotnetHost(page); + await page.evaluate( + ({ config, userConfig }) => { + const sources = [ + { name: "local", url: "/dev/acme/feed", enabled: true }, + { name: "shared", url: "https://pkgs.example.com/v3/index.json", enabled: true }, + // A password inside the URL: the window must not show it. + { name: "private", url: "https://bob:s3cret-pw@pkgs.example.com/v3/index.json", enabled: false }, + ]; + window.__dotnetOut = (args) => { + const [, verb, , name] = args; + if (args[0] === "list") return '{"projects":[]}'; + // Other windows of the NuGet view (central package state) ask MSBuild too. + if (args[0] === "msbuild") return '{"Properties":{},"Items":{}}'; + if (args[1] === "config") return `${config}\n${userConfig}\n`; + if (verb === "list") { + const target = args.at(-1); + const listed = + target === config + ? sources.filter((s) => s.name !== "shared") + : target === userConfig + ? sources.filter((s) => s.name === "shared") + : sources; + return `Registered Sources:\n\n${listed + .map((s, i) => ` ${i + 1}. ${s.name} [${s.enabled ? "Enabled" : "Disabled"}]\n ${s.url}`) + .join("\n")}\n`; + } + if (verb === "add") sources.push({ name: args[args.indexOf("--name") + 1]!, url: args[3]!, enabled: true }); + else if (verb === "remove") + sources.splice( + sources.findIndex((s) => s.name === name), + 1, + ); + else sources.find((s) => s.name === name)!.enabled = verb === "enable"; + return "ok\n"; + }; + }, + { config: CONFIG, userConfig: USER_CONFIG }, + ); + await openNuget(page); + await page.getByText("Package sources", { exact: true }).click(); +} + +test("lists the effective sources, masks URL credentials and toggles a source in the workspace file", async ({ + workbench: page, +}) => { + await stubSources(page); + const list = page.getByRole("list", { name: "Package sources" }); + await expect(list.getByText(/local/)).toBeVisible(); + await expect(list.getByText(/private.*Disabled/)).toBeVisible(); + await expect(list).toContainText("https://***@pkgs.example.com"); + await expect(page.getByText("s3cret-pw")).toHaveCount(0); + await expect(page.getByLabel("NuGet.Config file")).toHaveValue(CONFIG); + await expect( + list.getByRole("listitem").filter({ hasText: "shared" }).getByRole("button", { name: "Disable" }), + ).toBeDisabled(); + await shot(page, "d1-sources", list.getByText(/private/)); + await list.getByRole("listitem").filter({ hasText: "private" }).getByRole("button", { name: "Enable" }).click(); + await expect + .poll(() => dotnetRuns(page)) + .toContainEqual(["nuget", "enable", "source", "private", "--configfile", CONFIG]); + await expect(list.getByText(/private.*Disabled/)).toHaveCount(0); + await list.getByRole("listitem").filter({ hasText: "local" }).getByRole("button", { name: "Disable" }).click(); + await expect + .poll(() => dotnetRuns(page)) + .toContainEqual(["nuget", "disable", "source", "local", "--configfile", CONFIG]); + await expect(list.getByText(/local.*Disabled/)).toBeVisible(); +}); + +test("adds and removes a source; the user-wide file is a labelled, explicit choice", async ({ workbench: page }) => { + await stubSources(page); + await page.getByLabel("Source name").fill("team"); + await page.getByLabel("Source URL or folder").fill("https://nuget.team.example/v3/index.json"); + await page.getByRole("button", { name: "Add source" }).click(); + await expect + .poll(() => dotnetRuns(page)) + .toContainEqual([ + "nuget", + "add", + "source", + "https://nuget.team.example/v3/index.json", + "--name", + "team", + "--configfile", + CONFIG, + ]); + const list = page.getByRole("list", { name: "Package sources" }); + await expect(list.getByText(/team/)).toBeVisible(); + // The user-wide file is last, labelled, and warns once picked. + await expect(page.getByRole("status")).toHaveCount(0); + await page.getByLabel("NuGet.Config file").selectOption(USER_CONFIG); + await expect(page.getByRole("status")).toContainText("every project"); + await shot(page, "d1-user-wide", page.getByRole("status")); + await expect( + list.getByRole("listitem").filter({ hasText: "shared" }).getByRole("button", { name: "Disable" }), + ).toBeEnabled(); + await page.getByLabel("NuGet.Config file").selectOption(CONFIG); + await list.getByRole("listitem").filter({ hasText: "team" }).getByRole("button", { name: "Remove" }).click(); + await expect + .poll(() => dotnetRuns(page)) + .toContainEqual(["nuget", "remove", "source", "team", "--configfile", CONFIG]); + await expect(list.getByText(/team/)).toHaveCount(0); +}); + +test("a failing dotnet command shows its message and keeps the list", async ({ workbench: page }) => { + await stubSources(page); + await page.evaluate(() => { + const ok = window.__dotnetOut; + window.__dotnetOut = (args) => { + if (args[2] === "source" && args[1] === "remove") throw new Error("error: Unable to find a source named 'nope'."); + return ok(args); + }; + }); + await page + .getByRole("list", { name: "Package sources" }) + .getByRole("listitem") + .first() + .getByRole("button", { name: "Remove" }) + .click(); + await expect(page.getByRole("alert")).toContainText("Unable to find a source"); + await expect(page.getByRole("list", { name: "Package sources" }).getByRole("listitem")).toHaveCount(3); +}); diff --git a/src/features/dotnet/NugetView.tsx b/src/features/dotnet/NugetView.tsx index f69dc3f4a..99e49b253 100644 --- a/src/features/dotnet/NugetView.tsx +++ b/src/features/dotnet/NugetView.tsx @@ -8,6 +8,7 @@ import { executeAction } from "@/platform/actions"; import { useTx } from "@/platform/i18n"; import { Button, Input } from "@/ui"; import { ensureDotnetModel, useDotnet } from "./store"; +import { SourcesPanel } from "./SourcesPanel"; import styles from "./Nuget.module.css"; export function NugetView() { @@ -54,6 +55,7 @@ export function NugetView() { {project && ( <> +
{ diff --git a/src/features/dotnet/SourcesPanel.test.tsx b/src/features/dotnet/SourcesPanel.test.tsx new file mode 100644 index 000000000..99fad12b3 --- /dev/null +++ b/src/features/dotnet/SourcesPanel.test.tsx @@ -0,0 +1,65 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import * as actions from "@/platform/actions"; +import * as dotnet from "@/platform/dotnet"; +import { useProject } from "@/platform/project"; +import { resetSources, useSources } from "./sources"; +import { SourcesPanel } from "./SourcesPanel"; +import { resetDotnet, useDotnet } from "./store"; + +afterEach(() => { + cleanup(); + resetSources(); + resetDotnet(); + useProject.setState({ project: null }); + vi.restoreAllMocks(); +}); + +function show() { + const run = vi.spyOn(actions, "executeAction").mockResolvedValue(undefined as never); + useProject.setState({ project: { root: "/w" } as never }); + useDotnet.setState({ + selected: "/w/App.csproj", + model: { projects: [{ path: "/w/App.csproj" } as never], solutions: [] }, + }); + vi.spyOn(dotnet, "dotnet").mockResolvedValue(""); + useSources.setState({ + project: "/w/App.csproj", + sources: [ + { name: "local", url: "/feed", enabled: true }, + { name: "priv", url: "https://***@h.example/i.json", enabled: false }, + ], + configs: [ + { path: "/w/NuGet.Config", scope: "workspace", exists: true }, + { path: "/home/u/NuGet.Config", scope: "user", exists: true }, + ], + target: "/w/NuGet.Config", + targetNames: ["local", "priv"], + }); + render(); + return run; +} + +it("shows state and masked URLs, and toggles and removes by name", () => { + const run = show(); + expect(screen.getByText(/priv.*https:\/\/\*\*\*@h\.example/)).toBeTruthy(); + fireEvent.click(screen.getByRole("button", { name: "Disable" })); + fireEvent.click(screen.getByRole("button", { name: "Enable" })); + fireEvent.click(screen.getAllByRole("button", { name: "Remove" })[0]!); + expect(run).toHaveBeenCalledWith("dotnet.sourceChange", { op: "disable", name: "local" }); + expect(run).toHaveBeenCalledWith("dotnet.sourceChange", { op: "enable", name: "priv" }); + expect(run).toHaveBeenCalledWith("dotnet.sourceChange", { op: "remove", name: "local" }); +}); + +it("warns before the user-wide file is the write target and adds a source", async () => { + const run = show(); + expect(screen.queryByRole("status")).toBeNull(); + fireEvent.change(screen.getByLabelText("NuGet.Config file"), { target: { value: "/home/u/NuGet.Config" } }); + expect(screen.getByRole("status").textContent).toMatch(/every project/); + fireEvent.change(screen.getByLabelText("Source name"), { target: { value: "n" } }); + fireEvent.change(screen.getByLabelText("Source URL or folder"), { target: { value: "/f" } }); + const add = screen.getByRole("button", { name: "Add source" }); + await waitFor(() => expect(add.disabled).toBe(false)); + fireEvent.click(add); + expect(run).toHaveBeenCalledWith("dotnet.sourceChange", { op: "add", name: "n", url: "/f" }); +}); diff --git a/src/features/dotnet/SourcesPanel.tsx b/src/features/dotnet/SourcesPanel.tsx new file mode 100644 index 000000000..9d30ac9bd --- /dev/null +++ b/src/features/dotnet/SourcesPanel.tsx @@ -0,0 +1,85 @@ +/** Package sources of the selected project's NuGet.Config hierarchy (#7420). */ +import { useEffect, useState } from "react"; +import { executeAction } from "@/platform/actions"; +import { useTx } from "@/platform/i18n"; +import { Button, Input } from "@/ui"; +import { selectSourceConfig, useSources } from "./sources"; +import styles from "./Nuget.module.css"; + +export function SourcesPanel({ project }: { project: string }) { + const s = useSources(); + const tx = useTx(); + const [name, setName] = useState(""); + const [url, setUrl] = useState(""); + const action = (id: string, arg?: unknown) => void executeAction(`dotnet.${id}`, arg); + useEffect(() => { + action("sources"); + }, [project]); + const target = s.configs.find((c) => c.path === s.target); + return ( +
+ {tx("Package sources")} + {s.error && ( +
+ {s.error} +
+ )} +
    + {s.sources.map((p) => ( +
  • + + {p.name} {p.enabled ? "" : tx("Disabled")} {p.url} + + + +
  • + ))} +
+ {s.sources.some((source) => !s.targetNames.includes(source.name)) && ( +

{tx("Choose the NuGet.Config file that defines this source to change it.")}

+ )} + + {target?.scope === "user" &&
{tx("This file applies to every project of this user.")}
} + { + e.preventDefault(); + action("sourceChange", { op: "add", name, url }); + setName(""); + setUrl(""); + }} + > + setName(e.target.value)} /> + setUrl(e.target.value)} /> + + +
{tx("Credentials are handled by dotnet and its credential providers; the IDE does not store them.")}
+
+ ); +} diff --git a/src/features/dotnet/cliTestkit.ts b/src/features/dotnet/cliTestkit.ts new file mode 100644 index 000000000..12303c89d --- /dev/null +++ b/src/features/dotnet/cliTestkit.ts @@ -0,0 +1,100 @@ +/** + * Runs the real `dotnet` CLI for tests: an isolated HOME (so the user-wide NuGet.Config and + * the package cache are the test's own), one SDK picked per run through `global.json`, and a + * local folder feed packed on the fly so nothing reaches nuget.org. + * + * With `CI` set a missing SDK fails the run instead of skipping it, so a runner without .NET + * cannot pass these tests silently. + */ +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +/** Installed SDK versions whose major version is one of `majors` (10 and 11 are the ones tested). */ +export function cliSdks(majors: number[] = [10, 11]): string[] { + const out = spawnSync("dotnet", ["--list-sdks"], { encoding: "utf8" }); + if (out.status !== 0) { + if (process.env.CI) throw new Error("dotnet is required in CI but was not found"); + return []; + } + const versions = out.stdout + .split(/\r?\n/) + .map((l) => l.split(" ")[0]!) + .filter((v) => majors.includes(Number(v.split(".")[0]))); + // One SDK per major: the newest installed one. + return majors.flatMap((m) => versions.filter((v) => v.startsWith(`${m}.`)).slice(-1)); +} + +export interface Sandbox { + /** Workspace root; its global.json pins the SDK. */ + root: string; + /** The test's HOME: holds the user-wide NuGet.Config. */ + home: string; + major: number; + run(args: string[], cwd?: string): { code: number; out: string }; + /** Like `run` but throws on a non-zero exit, as the IDE's `dotnet()` does. */ + ok(args: string[], cwd?: string): string; + /** Packs `id` at each version into `feed` (a local folder feed). */ + pack(feed: string, id: string, versions: string[], extra?: string): void; + dispose(): void; +} + +export function sandbox(sdk: string): Sandbox { + // realpath: the CLI prints resolved paths (macOS /var -> /private/var). + const base = realpathSync(mkdtempSync(join(tmpdir(), "oi-nuget-"))); + const root = join(base, "ws"); + const home = join(base, "home"); + mkdirSync(root); + mkdirSync(home); + writeFileSync(join(root, "global.json"), JSON.stringify({ sdk: { version: sdk, rollForward: "disable" } })); + const major = Number(sdk.split(".")[0]); + const env = { + ...process.env, + HOME: home, + USERPROFILE: home, + APPDATA: join(home, "AppData"), + DOTNET_CLI_HOME: home, + NUGET_PACKAGES: join(base, "packages"), + DOTNET_CLI_UI_LANGUAGE: "en", + DOTNET_NOLOGO: "1", + DOTNET_CLI_TELEMETRY_OPTOUT: "1", + DOTNET_SKIP_FIRST_TIME_EXPERIENCE: "1", + MSBUILDDISABLENODEREUSE: "1", + }; + const run = (args: string[], cwd = root) => { + const r = spawnSync("dotnet", args, { cwd, env, encoding: "utf8", timeout: 180_000 }); + return { code: r.status ?? -1, out: `${r.stdout}${r.stderr}` }; + }; + const ok = (args: string[], cwd = root) => { + const r = run(args, cwd); + if (r.code !== 0) throw new Error(`dotnet ${args.join(" ")} exited with ${r.code}\n${r.out}`); + return r.out; + }; + return { + root, + home, + major, + run, + ok, + pack(feed, id, versions, extra = "") { + const dir = join(base, `pack-${id}`); + mkdirSync(dir, { recursive: true }); + mkdirSync(feed, { recursive: true }); + writeFileSync( + join(dir, `${id}.csproj`), + `net${major}.0` + + `falsetruefalsefalsefalseNU5128;NU5127` + + `${extra}`, + ); + // Nothing to restore: an empty source list keeps the user's and the test's sources out of packing. + writeFileSync( + join(dir, "NuGet.Config"), + "", + ); + writeFileSync(join(dir, "content.txt"), id); + for (const v of versions) ok(["pack", dir, "-p:PackageVersion=" + v, "-o", feed, "--nologo"], dir); + }, + dispose: () => rmSync(base, { recursive: true, force: true }), + }; +} diff --git a/src/features/dotnet/index.ts b/src/features/dotnet/index.ts index d38bcd679..6cde595fd 100644 --- a/src/features/dotnet/index.ts +++ b/src/features/dotnet/index.ts @@ -15,6 +15,7 @@ import { searchPackages, selectDotnet, } from "./store"; +import { cancelSources, changeSource, loadSources, resetSources, type SourceOperation } from "./sources"; import { addProjectReference, addProjectsToSolution, @@ -54,6 +55,7 @@ export function activate() { category: "Build", run: () => { cancelDotnet(); + cancelSources(); cancelDotnetEdit(); }, }, @@ -145,6 +147,23 @@ export function activate() { return changePackage(a.id, a.version); }, }, + { + id: "dotnet.sources", + title: "Refresh NuGet Package Sources", + category: "Build", + hidden: true, + run: () => loadSources(), + }, + { + id: "dotnet.sourceChange", + title: "Change NuGet Package Source", + category: "Build", + hidden: true, + run: ({ arg }) => { + const a = arg as { op: SourceOperation; name: string; url?: string }; + return changeSource(a.op, a.name, a.url); + }, + }, { id: "dotnet.discover", title: "Discover .NET Tests", @@ -170,7 +189,10 @@ export function activate() { }, ]), useProject.subscribe((s, old) => { - if (s.project?.root !== old.project?.root) resetDotnet(); + if (s.project?.root !== old.project?.root) { + resetDotnet(); + resetSources(); + } }), // #5635: build / restore / clean act on the right-clicked solution or project. registerMenuGroup({ @@ -193,6 +215,7 @@ export function activate() { ]; return () => { resetDotnet(); + resetSources(); disposers.reverse().forEach((d) => d()); }; } diff --git a/src/features/dotnet/sources.cli.test.ts b/src/features/dotnet/sources.cli.test.ts new file mode 100644 index 000000000..7fb643d5c --- /dev/null +++ b/src/features/dotnet/sources.cli.test.ts @@ -0,0 +1,159 @@ +// @vitest-environment node +/** Package sources against the real `dotnet` CLI (SDK 10 and 11) and a local folder feed. */ +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import * as platform from "@/platform/dotnet"; +import { commands } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; +import { cliSdks, type Sandbox, sandbox } from "./cliTestkit"; +import { + changeSource, + configChoices, + loadSources, + parseConfigPaths, + parseSources, + resetSources, + useSources, +} from "./sources"; +import { resetDotnet, useDotnet } from "./store"; + +// Each test packs or restores with the real CLI, slower on a loaded machine. +vi.setConfig({ testTimeout: 120_000 }); + +const sdks = cliSdks(); +it.runIf(sdks.length === 0)("has no SDK 10 or 11 here (CI fails on this)", () => { + expect(process.env.CI).toBeFalsy(); +}); + +describe.each(sdks)("package sources with SDK %s", (sdk) => { + let sb: Sandbox; + let app: string; + beforeEach(() => { + sb = sandbox(sdk); + app = join(sb.root, "app"); + mkdirSync(app); + writeFileSync( + join(app, "App.csproj"), + `net${sb.major}.0`, + ); + }); + afterEach(() => { + sb.dispose(); + resetSources(); + resetDotnet(); + vi.restoreAllMocks(); + }); + + const list = (cwd = app) => parseSources(sb.ok(["nuget", "list", "source", "--format", "detailed"], cwd)); + const paths = (cwd = app) => parseConfigPaths(sb.ok(["nuget", "config", "paths"], cwd)); + + it("lists a disabled source, a local folder and masks nothing it was never given ( in the workspace file)", () => { + mkdirSync(join(sb.root, "feed"), { recursive: true }); + writeFileSync( + join(sb.root, "NuGet.Config"), + `` + + `` + + ``, + ); + const sources = list(); + expect(sources.map((s) => [s.name, s.enabled])).toEqual([ + ["local", true], + ["priv", false], + ]); + expect(JSON.stringify(sources)).not.toContain("s3cret-pw"); + expect(paths().some((p) => p.endsWith("NuGet.Config") && p.includes("ws"))).toBe(true); + }); + + it("merges levels: a nearer file adds to the user-wide one and the workspace file is the default target", () => { + writeFileSync( + join(sb.root, "NuGet.Config"), + ``, + ); + // The user-wide file is created by the CLI on first use; add a user source through it. + sb.ok(["nuget", "add", "source", "https://user.example.invalid/i.json", "-n", "user-feed"], app); + const names = list().map((s) => s.name); + expect(names).toEqual(expect.arrayContaining(["ws", "user-feed"])); + const choices = configChoices(paths(), sb.root); + expect(choices[0]).toMatchObject({ scope: "workspace", exists: true }); + expect(choices.at(-1)!.scope).toBe("user"); + expect(choices.at(-1)!.path.startsWith(sb.home)).toBe(true); + }); + + it("creates the workspace file when none exists and adds, disables, enables and removes through the store", async () => { + const empty = sandbox(sdk); + try { + const proj = join(empty.root, "p"); + mkdirSync(proj); + writeFileSync(join(proj, "P.csproj"), ""); + mkdirSync(join(empty.root, "feed")); + vi.spyOn(platform, "dotnet").mockImplementation(async (args, cwd) => empty.ok(args, cwd)); + vi.spyOn(commands, "fsCreateFileBytes").mockImplementation(async (path, b64) => { + writeFileSync(path, Buffer.from(b64, "base64")); + return { status: "ok", data: null }; + }); + useProject.setState({ project: { root: empty.root } as never }); + useDotnet.setState({ + selected: join(proj, "P.csproj"), + model: { projects: [{ path: join(proj, "P.csproj") } as never], solutions: [] }, + }); + await loadSources(); + expect(useSources.getState().error).toBe(""); + const target = join(empty.root, "NuGet.Config").replace(/\\/g, "/"); + expect(useSources.getState().target).toBe(target); + expect(existsSync(target)).toBe(false); + + await changeSource("add", "local", join(empty.root, "feed")); + expect(useSources.getState().error).toBe(""); + expect(readFileSync(target, "utf8")).toContain('key="local"'); + expect(useSources.getState().sources.find((s) => s.name === "local")?.enabled).toBe(true); + + await changeSource("disable", "local"); + expect(useSources.getState().sources.find((s) => s.name === "local")?.enabled).toBe(false); + await changeSource("enable", "local"); + expect(useSources.getState().sources.find((s) => s.name === "local")?.enabled).toBe(true); + await changeSource("remove", "local"); + expect(useSources.getState().sources.some((s) => s.name === "local")).toBe(false); + // The created file carries no : the user-wide nuget.org source stays in effect. + expect(useSources.getState().sources.map((s) => s.name)).toContain("nuget.org"); + } finally { + empty.dispose(); + } + }); + + it("blocks edits to a source absent from the selected config and keeps the list", async () => { + vi.spyOn(platform, "dotnet").mockImplementation(async (args, cwd) => sb.ok(args, cwd)); + useProject.setState({ project: { root: sb.root } as never }); + useDotnet.setState({ + selected: join(app, "App.csproj"), + model: { projects: [{ path: join(app, "App.csproj") } as never], solutions: [] }, + }); + await loadSources(); + const before = useSources.getState().sources; + await changeSource("remove", "no-such-source"); + expect(useSources.getState().error).toContain("Choose the NuGet.Config file that defines this source"); + expect(useSources.getState().sources).toEqual(before); + expect(useSources.getState().busy).toBe(false); + }); + + it("search and install keep using the effective sources (a local feed packed here)", () => { + const feed = join(sb.root, "feed"); + sb.pack(feed, "Demo.Pkg", ["1.0.0", "2.0.0-beta.1"]); + writeFileSync( + join(sb.root, "NuGet.Config"), + ``, + ); + expect(sb.ok(["package", "search", "Demo.Pkg", "--format", "json"], app)).toContain("Demo.Pkg"); + sb.ok(["add", join(app, "App.csproj"), "package", "Demo.Pkg", "--version", "1.0.0"], app); + expect(readFileSync(join(app, "App.csproj"), "utf8")).toContain("Demo.Pkg"); + }, 240_000); + + it("fails with the CLI's message when the SDK is missing or the file is malformed", () => { + const bad = join(sb.root, "bad"); + mkdirSync(bad, { recursive: true }); + writeFileSync(join(bad, "NuGet.Config"), ""); + const r = sb.run(["nuget", "list", "source", "--format", "detailed"], bad); + expect(r.code).not.toBe(0); + expect(r.out).toMatch(/NuGet\.Config|XML|configuration/i); + }); +}); diff --git a/src/features/dotnet/sources.test.ts b/src/features/dotnet/sources.test.ts new file mode 100644 index 000000000..99f2d2280 --- /dev/null +++ b/src/features/dotnet/sources.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it } from "vitest"; +import { configChoices, maskUrl, parseConfigPaths, parseSources, sourceArgs } from "./sources"; + +describe("package source parsing", () => { + it("reads enabled and disabled sources, names with spaces and local folders", () => { + const text = [ + "Registered Sources:", + "", + " 1. nuget.org [Enabled]", + " https://api.nuget.org/v3/index.json", + " 2. My Feed [Disabled]", + " /srv/feed", + "", + ].join("\n"); + expect(parseSources(text)).toEqual([ + { name: "nuget.org", url: "https://api.nuget.org/v3/index.json", enabled: true }, + { name: "My Feed", url: "/srv/feed", enabled: false }, + ]); + }); + it("reads CRLF output and an empty list", () => { + expect(parseSources("Registered Sources:\r\n\r\n 1. a [Enabled]\r\n /f\r\n")).toHaveLength(1); + expect(parseSources("No sources found.\n")).toEqual([]); + }); + it("masks credentials embedded in a source URL", () => { + expect(maskUrl("https://user:secret@pkgs.example.com/v3/index.json")).toBe( + "https://***@pkgs.example.com/v3/index.json", + ); + expect(maskUrl("https://token@pkgs.example.com/i.json")).toBe("https://***@pkgs.example.com/i.json"); + expect(maskUrl("https://pkgs.example.com/a@b")).toBe("https://pkgs.example.com/a@b"); + const [source] = parseSources(" 1. p [Enabled]\n https://u:ClearTextPassword@h.example/i.json\n"); + expect(source!.url).not.toContain("ClearTextPassword"); + }); + it("reads the config path list, ignoring other lines", () => { + expect(parseConfigPaths("/w/NuGet.Config\nC:\\Users\\a\\NuGet.Config\nwarning: x\n")).toEqual([ + "/w/NuGet.Config", + "C:\\Users\\a\\NuGet.Config", + ]); + }); +}); + +describe("choosing the NuGet.Config to write", () => { + it("defaults to the workspace file nearest the root, user-wide files last", () => { + expect( + configChoices(["/w/app/NuGet.Config", "/w/NuGet.Config", "/home/u/.nuget/NuGet/NuGet.Config"], "/w"), + ).toEqual([ + { path: "/w/NuGet.Config", scope: "workspace", exists: true }, + { path: "/w/app/NuGet.Config", scope: "workspace", exists: true }, + { path: "/home/u/.nuget/NuGet/NuGet.Config", scope: "user", exists: true }, + ]); + }); + it("offers a new root file when no workspace file exists, never defaulting to the user file", () => { + const [first, second] = configChoices(["/home/u/.nuget/NuGet/NuGet.Config"], "/w"); + expect(first).toEqual({ path: "/w/NuGet.Config", scope: "workspace", exists: false }); + expect(second!.scope).toBe("user"); + }); + it("keeps distinct POSIX directories separate", () => { + const files = configChoices(["/home/user/project/NuGet.Config"], "/home/user/Project"); + expect(files.map((file) => file.scope)).toEqual(["workspace", "user"]); + }); + it("matches Windows paths case-insensitively", () => { + expect(configChoices(["c:\\Repo\\nuget.config"], "C:\\Repo")[0]!.scope).toBe("workspace"); + }); +}); + +describe("dotnet nuget arguments", () => { + it("always names the file", () => { + expect(sourceArgs("add", "/w/NuGet.Config", "n", "/f")).toEqual([ + "nuget", + "add", + "source", + "/f", + "--name", + "n", + "--configfile", + "/w/NuGet.Config", + ]); + expect(sourceArgs("disable", "/w/NuGet.Config", "n")).toEqual([ + "nuget", + "disable", + "source", + "n", + "--configfile", + "/w/NuGet.Config", + ]); + }); +}); diff --git a/src/features/dotnet/sources.ts b/src/features/dotnet/sources.ts new file mode 100644 index 000000000..e81c3e687 --- /dev/null +++ b/src/features/dotnet/sources.ts @@ -0,0 +1,210 @@ +import { create } from "zustand"; +import { call, commands, IpcError } from "@/platform/ipc"; +import { tx } from "@/platform/i18n"; +import { toBase64 } from "@/platform/base64"; +import { dotnet } from "@/platform/dotnet"; +import { dirname, useProject } from "@/platform/project"; +import { selectedProject, useDotnet } from "./store"; + +export interface PackageSource { + name: string; + url: string; + enabled: boolean; +} +export interface ConfigFile { + path: string; + /** Where the file lives: next to the project, or in the user / machine-wide hierarchy. */ + scope: "workspace" | "user"; + /** False for the `NuGet.Config` offered next to the root when no file exists yet. */ + exists: boolean; +} +interface State { + sources: PackageSource[]; + configs: ConfigFile[]; + /** The NuGet.Config the next add / enable / disable / remove writes to. */ + target: string; + targetNames: string[]; + project: string; + busy: boolean; + error: string; +} +const initial: State = { sources: [], configs: [], target: "", targetNames: [], project: "", busy: false, error: "" }; +export const useSources = create(() => initial); +let controller: AbortController | undefined; +let generation = 0; +export function resetSources() { + generation++; + controller?.abort(); + useSources.setState(initial); +} + +/** A password or token written into a source URL (`https://user:secret@host`) is never shown. */ +export function maskUrl(url: string): string { + return url.replace(/\b([a-z][a-z0-9+.-]*:\/\/)[^/@\s]+@/gi, "$1***@"); +} + +/** `dotnet nuget list source --format detailed`: a numbered `name [Enabled|Disabled]` line, then the URL line. */ +export function parseSources(text: string): PackageSource[] { + const result: PackageSource[] = []; + const lines = text.split(/\r?\n/); + for (let i = 0; i < lines.length; i++) { + const head = /^\s*\d+\.\s+(.+?)\s+\[(Enabled|Disabled)(?:,[^\]]*)?\]\s*$/.exec(lines[i]!); + if (!head) continue; + result.push({ name: head[1]!, url: maskUrl((lines[i + 1] ?? "").trim()), enabled: head[2] === "Enabled" }); + } + return result; +} + +/** `dotnet nuget config paths`: one file per line, nearest first. */ +export function parseConfigPaths(text: string): string[] { + return text + .split(/\r?\n/) + .map((l) => l.trim()) + .filter((l) => /^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(l)); +} + +const norm = (p: string) => p.replace(/\\/g, "/").replace(/\/+$/, ""); +function inside(path: string, dir: string): boolean { + const file = norm(path); + const root = norm(dir); + if (/^[a-z]:$|^[a-z]:\/|^\/\//i.test(root)) return file.toLowerCase().startsWith(`${root.toLowerCase()}/`); + return file.startsWith(`${root}/`); +} + +/** + * The files a source can be written to: those under the workspace root, nearest to the + * root first, with `/NuGet.Config` offered (and created on first write) when none + * exists, then the user-wide ones. The default is the first workspace file. + */ +export function configChoices(paths: string[], root: string): ConfigFile[] { + const workspace = paths.filter((p) => inside(p, root)); + const fallback = `${norm(root)}/NuGet.Config`; + const files: ConfigFile[] = (workspace.length ? workspace : [fallback]).map((path) => ({ + path, + scope: "workspace" as const, + exists: workspace.length > 0, + })); + files.sort((a, b) => norm(a.path).length - norm(b.path).length); + return [ + ...files, + ...paths.filter((p) => !inside(p, root)).map((path) => ({ path, scope: "user" as const, exists: true })), + ]; +} + +export type SourceOperation = "add" | "enable" | "disable" | "remove"; +export function sourceArgs(op: SourceOperation, config: string, name: string, url = ""): string[] { + return op === "add" + ? ["nuget", "add", "source", url, "--name", name, "--configfile", config] + : ["nuget", op, "source", name, "--configfile", config]; +} + +export const EMPTY_CONFIG = toBase64( + new TextEncoder().encode('\n\n\n'), +); + +async function run(work: (signal: AbortSignal, cwd: string, root: string, project: string) => Promise>) { + const project = selectedProject(); + const root = useProject.getState().project?.root; + if (!project || !root) return; + controller?.abort(); + const current = ++generation; + const abort = new AbortController(); + controller = abort; + const isCurrent = () => selectedProject()?.path === project.path && useProject.getState().project?.root === root; + const stopIfChanged = () => { + if (!isCurrent()) abort.abort(); + }; + const stopProject = useProject.subscribe(stopIfChanged); + const stopSelection = useDotnet.subscribe(stopIfChanged); + useSources.setState({ busy: true, error: "" }); + try { + const patch = await work(abort.signal, dirname(project.path), root, project.path); + if (current === generation && !abort.signal.aborted) useSources.setState(patch); + } catch (e) { + if (current === generation && !abort.signal.aborted) useSources.setState({ error: maskUrl(String(e)) }); + } finally { + stopProject(); + stopSelection(); + if (current === generation) { + controller = undefined; + useSources.setState({ busy: false }); + } + } +} + +async function namesInConfig(file: ConfigFile | undefined, cwd: string, signal: AbortSignal): Promise { + if (!file?.exists) return []; + const list = await dotnet( + ["nuget", "list", "source", "--format", "detailed", "--configfile", file.path], + cwd, + signal, + ); + return parseSources(list).map((source) => source.name); +} + +async function load( + cwd: string, + root: string, + project: string, + signal: AbortSignal, + keep: string, +): Promise> { + const [list, paths] = await Promise.all([ + dotnet(["nuget", "list", "source", "--format", "detailed"], cwd, signal), + dotnet(["nuget", "config", "paths"], cwd, signal), + ]); + const configs = configChoices(parseConfigPaths(paths), root); + const target = configs.find((config) => config.path === keep) ?? configs[0]; + return { + project, + sources: parseSources(list), + configs, + target: target?.path ?? "", + targetNames: await namesInConfig(target, cwd, signal), + }; +} + +export function loadSources() { + return run((signal, cwd, root, project) => { + const current = useSources.getState(); + return load(cwd, root, project, signal, current.project === project ? current.target : ""); + }); +} + +export function selectSourceConfig(path: string) { + const { configs, project } = useSources.getState(); + const config = configs.find((candidate) => candidate.path === path); + if (!config || selectedProject()?.path !== project) return; + useSources.setState({ target: path, targetNames: [] }); + return run(async (signal, cwd) => ({ targetNames: await namesInConfig(config, cwd, signal) })); +} + +export function cancelSources() { + controller?.abort(); +} +export function changeSource(op: SourceOperation, name: string, url = "") { + const { project, target, configs, targetNames } = useSources.getState(); + const config = configs.find((candidate) => candidate.path === target); + if (!config || !name.trim() || selectedProject()?.path !== project) return; + const address = url.trim(); + if (op === "add" && maskUrl(address) !== address) { + useSources.setState({ error: tx("Remove credentials from the package source URL before adding it.") }); + return; + } + if (op !== "add" && !targetNames.includes(name)) { + useSources.setState({ error: tx("Choose the NuGet.Config file that defines this source to change it.") }); + return; + } + return run(async (signal, cwd, root, activeProject) => { + if (op === "add" && !config.exists) { + // The default template adds , which hides the inherited sources. + try { + await call(commands.fsCreateFileBytes(target, EMPTY_CONFIG)); + } catch (e) { + if (!(e instanceof IpcError) || e.kind !== "alreadyExists") throw e; + } + } + await dotnet(sourceArgs(op, target, name.trim(), address), cwd, signal); + return load(cwd, root, activeProject, signal, target); + }); +} diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 2f13548b5..4c42b0d97 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -5127,6 +5127,20 @@ "Cannot resolve module \"{rawSpec}\" from {importerPath}": "Cannot resolve module \"{rawSpec}\" from {importerPath}", "Open External Link?": "Open External Link?", "This MDX preview wants to open an external URL in your browser:": "This MDX preview wants to open an external URL in your browser:", + "Package sources": "Package sources", + "Disabled": "Disabled", + "Disable": "Disable", + "Enable": "Enable", + "Write changes to": "Write changes to", + "NuGet.Config file": "NuGet.Config file", + "User-wide: {path}": "User-wide: {path}", + "This file applies to every project of this user.": "This file applies to every project of this user.", + "Source name": "Source name", + "Source URL or folder": "Source URL or folder", + "Add source": "Add source", + "Credentials are handled by dotnet and its credential providers; the IDE does not store them.": "Credentials are handled by dotnet and its credential providers; the IDE does not store them.", + "Refresh NuGet Package Sources": "Refresh NuGet Package Sources", + "Change NuGet Package Source": "Change NuGet Package Source", "Build Xcode projects in the background for code insight": "Build Xcode projects in the background for code insight", "Until an Xcode project's first build, sourcekit-lsp can't resolve types from its other targets. Builds what Run builds, at low priority, once.": "Until an Xcode project's first build, sourcekit-lsp can't resolve types from its other targets. Builds what Run builds, at low priority, once.", "Code insight for {container} reads its last build. Without one yet, it is built in the background.": "Code insight for {container} reads its last build. Without one yet, it is built in the background.", diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index 5167543d2..867593394 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -9664,6 +9664,19 @@ "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 僅能為單一儲存庫啟用來自外掛市場的外掛。", + "Package sources": "套件來源", + "Write changes to": "將變更寫入", + "NuGet.Config file": "NuGet.Config 檔案", + "User-wide: {path}": "使用者層級:{path}", + "This file applies to every project of this user.": "此檔案適用於此使用者的所有專案。", + "Source name": "來源名稱", + "Source URL or folder": "來源網址或資料夾", + "Add source": "新增來源", + "Credentials are handled by dotnet and its credential providers; the IDE does not store them.": "認證由 dotnet 及其認證提供者處理,IDE 不會儲存。", + "Refresh NuGet Package Sources": "重新整理 NuGet 套件來源", + "Change NuGet Package Source": "變更 NuGet 套件來源", + "Remove credentials from the package source URL before adding it.": "新增前,請先移除套件來源網址中的認證資訊。", + "Choose the NuGet.Config file that defines this source to change it.": "若要變更此來源,請選擇定義該來源的 NuGet.Config 檔案。", "Add Existing Project": "加入現有專案", "Could not add the project to the solution": "無法將專案加入方案", "Could not remove the project from the solution": "無法從方案中移除專案", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 4002f5c38..e827c3e33 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -11993,6 +11993,19 @@ "Use letters, digits, spaces, hyphens and underscores, starting with a letter, digit or underscore": "只能使用字母、数字、空格、连字符和下划线,并以字母、数字或下划线开头", "iOS": "iOS", "macOS": "macOS", + "Package sources": "包源", + "Write changes to": "修改写入到", + "NuGet.Config file": "NuGet.Config 文件", + "User-wide: {path}": "用户级:{path}", + "This file applies to every project of this user.": "此文件对该用户的所有项目生效。", + "Source name": "源名称", + "Source URL or folder": "源地址或文件夹", + "Add source": "添加源", + "Credentials are handled by dotnet and its credential providers; the IDE does not store them.": "凭据由 dotnet 及其凭据提供程序处理,IDE 不保存。", + "Refresh NuGet Package Sources": "刷新 NuGet 包源", + "Change NuGet Package Source": "修改 NuGet 包源", + "Remove credentials from the package source URL before adding it.": "添加前,请先删除包源 URL 中的凭据信息。", + "Choose the NuGet.Config file that defines this source to change it.": "要修改此源,请选择定义该源的 NuGet.Config 文件。", "Add Existing Project": "添加现有项目", "Could not add the project to the solution": "无法将项目添加到解决方案", "Could not remove the project from the solution": "无法从解决方案中移除项目",