From 62bac6ec8cd3677c575cd74ef049980b99d16a81 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Thu, 3 Dec 2026 17:39:50 +0900 Subject: [PATCH] feat(dotnet): run configurations for F# and Visual Basic projects (#7632) Run configuration detection and its .sln / .slnx reader only accepted .csproj, so F# and Visual Basic projects got no run configurations. .fsproj and .vbproj now follow the C# rules. Visual Basic keeps launch profiles in My Project/launchSettings.json, where dotnet run looks, so profiles and the gutter run icons in that file read it. The real dotnet CLI test is ignored by default (no SDK in CI). Closes #7631 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-run/src/detect/dotnet.rs | 9 +- crates/ide-run/src/dotnet.rs | 18 ++-- crates/ide-run/tests/dotnet.rs | 95 ++++++++++++++++++- crates/ide-run/tests/dotnet_cli.rs | 83 ++++++++++++++++ docs/en/languages/csharp.mdx | 6 +- docs/zh/languages/csharp.mdx | 6 +- e2e/launchSettingsVb.spec.ts | 49 ++++++++++ src/features/run/launchSettingsGutter.test.ts | 15 +++ src/features/run/launchSettingsGutter.ts | 14 ++- 9 files changed, 275 insertions(+), 20 deletions(-) create mode 100644 crates/ide-run/tests/dotnet_cli.rs create mode 100644 e2e/launchSettingsVb.spec.ts diff --git a/crates/ide-run/src/detect/dotnet.rs b/crates/ide-run/src/detect/dotnet.rs index 3575b70d32..e2c0a1e98b 100644 --- a/crates/ide-run/src/detect/dotnet.rs +++ b/crates/ide-run/src/detect/dotnet.rs @@ -2,7 +2,7 @@ use crate::{ RunConfig, - dotnet::{parse_project, profiles, solution_projects}, + dotnet::{is_project_file, parse_project, profiles, solution_projects}, }; use std::{ collections::{BTreeMap, BTreeSet}, @@ -32,10 +32,11 @@ pub(crate) fn detect(root: &Path, out: &mut Vec) { dirs.push(path); } } else if entry.file_type().is_ok_and(|t| t.is_file()) { + if is_project_file(&path) { + projects.insert(path); + continue; + } match path.extension().and_then(|e| e.to_str()).unwrap_or_default().to_ascii_lowercase().as_str() { - "csproj" => { - projects.insert(path); - } "sln" | "slnx" => { if let Ok(src) = fs::read_to_string(&path) { for project in solution_projects( diff --git a/crates/ide-run/src/dotnet.rs b/crates/ide-run/src/dotnet.rs index 46216dce4f..61103d3b3e 100644 --- a/crates/ide-run/src/dotnet.rs +++ b/crates/ide-run/src/dotnet.rs @@ -165,6 +165,13 @@ pub fn parse_profiles(json: &str) -> BTreeMap { .collect() } +/// An MSBuild project file of C#, F# or Visual Basic. +pub(crate) fn is_project_file(path: &Path) -> bool { + path.extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| ["csproj", "fsproj", "vbproj"].iter().any(|ext| e.eq_ignore_ascii_case(ext))) +} + pub fn solution_projects(src: &str, xml: bool) -> Vec { let paths: Vec = if xml { elements(src) @@ -184,17 +191,16 @@ pub fn solution_projects(src: &str, xml: bool) -> Vec { }) .collect() }; - paths - .into_iter() - .filter(|p| p.to_ascii_lowercase().ends_with(".csproj")) - .map(|p| PathBuf::from(p.replace('\\', "/"))) - .collect() + paths.into_iter().map(|p| PathBuf::from(p.replace('\\', "/"))).filter(|p| is_project_file(p)).collect() } pub(crate) fn profiles(project: &Path) -> BTreeMap { + // Where `dotnet run` looks: Visual Basic keeps its properties folder as `My Project`. + let vb = project.extension().is_some_and(|e| e.eq_ignore_ascii_case("vbproj")); + let folder = if vb { "My Project" } else { "Properties" }; project .parent() - .and_then(|p| fs::read_to_string(p.join("Properties/launchSettings.json")).ok()) + .and_then(|p| fs::read_to_string(p.join(folder).join("launchSettings.json")).ok()) .map(|s| parse_profiles(&s)) .unwrap_or_default() } diff --git a/crates/ide-run/tests/dotnet.rs b/crates/ide-run/tests/dotnet.rs index 9e7d9a4456..5662da8ce0 100644 --- a/crates/ide-run/tests/dotnet.rs +++ b/crates/ide-run/tests/dotnet.rs @@ -116,7 +116,10 @@ fn solution_paths_support_windows_separators_folders_and_entities() { [PathBuf::from("src/App/App.csproj"), PathBuf::from("../other/Other.csproj")] ); let slnx = r#""#; - assert_eq!(solution_projects(slnx, true), [PathBuf::from("src/A&B/App.csproj")]); + assert_eq!(solution_projects(slnx, true), [PathBuf::from("src/A&B/App.csproj"), PathBuf::from("other.vbproj")]); + // F# and Visual Basic projects next to C#; other project kinds are left out. + let mixed = "Project(\"{cs}\") = \"A\", \"A\\A.csproj\", \"{1}\"\nEndProject\nProject(\"{fs}\") = \"B\", \"B\\B.FSPROJ\", \"{2}\"\nEndProject\nProject(\"{vb}\") = \"C\", \"C\\C.vbproj\", \"{3}\"\nEndProject\nProject(\"{cpp}\") = \"D\", \"D\\D.vcxproj\", \"{4}\""; + assert_eq!(solution_projects(mixed, false), ["A/A.csproj", "B/B.FSPROJ", "C/C.vbproj"].map(PathBuf::from)); assert!(solution_projects(" [(&'static str, String, bool, bool); 5] { + let exe = r#"Exenet11.0"#; + let winexe = r#"WinExenet11.0;net10.0"#; + let library = r#"net11.0"#; + let web = r#"net11.0"#; + let test = format!( + r#"net11.0false"# + ); + [ + ("Exe", exe.into(), true, false), + ("WinExe", winexe.into(), true, false), + ("Library", library.into(), false, false), + ("Web", web.into(), true, false), + ("Test", test, false, true), + ] +} + +#[test] +fn fsharp_and_vb_projects_follow_the_csharp_rules() { + for ext in ["fsproj", "vbproj"] { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + for (kind, xml, _, _) in templates(ext) { + write(root, &format!("{kind}/{kind}.{ext}"), &xml); + } + // Not a project file. + write(root, &format!("Exe/Exe.{ext}.user"), ""); + let configs = detect(root); + for (kind, _, run, test) in templates(ext) { + let own: Vec<_> = + configs.iter().filter(|c| c.extras.params["project"] == format!("{kind}/{kind}.{ext}")).collect(); + assert_eq!(own.len(), usize::from(run || test), "{ext} {kind}"); + for c in own { + assert_eq!(c.kind, if test { "dotnet-test" } else { "dotnet" }, "{ext} {kind}"); + assert_eq!(c.debug_adapter.is_some(), run, "{ext} {kind}"); + } + } + let multi = configs.iter().find(|c| c.name == "WinExe (.NET Project)").unwrap(); + assert_eq!(multi.extras.params["frameworks"], "net11.0;net10.0"); + assert_eq!(multi.args[3..5], ["--framework", "net11.0"]); + } +} + +#[test] +fn launch_profiles_are_read_where_dotnet_run_reads_them() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let exe = templates("x")[0].1.clone(); + for (project, folder) in [("f/F.fsproj", "f/Properties"), ("v/V.vbproj", "v/My Project")] { + write(root, project, &exe); + write(root, &format!("{folder}/launchSettings.json"), PROFILES); + } + // `dotnet run` ignores a Visual Basic project's `Properties` folder. + write(root, "w/W.vbproj", &exe); + write(root, "w/Properties/launchSettings.json", PROFILES); + let configs = detect(root); + let names: Vec<_> = configs.iter().map(|c| c.name.as_str()).collect(); + assert_eq!(names.iter().filter(|n| !n.starts_with("W")).count(), 6, "the default and two profiles each: {names:?}"); + assert_eq!(names.iter().filter(|n| n.starts_with("W")).count(), 1, "{names:?}"); + for project in ["f/F.fsproj", "v/V.vbproj"] { + let config = configs + .iter() + .find(|c| c.extras.params["project"] == project && c.extras.params["launchProfile"] == "http") + .unwrap(); + let resolved = resolve(root, config.clone()).unwrap(); + assert_eq!(resolved.env["DEMO"], "profile", "{project}"); + } +} + +#[test] +fn mixed_solutions_with_spaces_and_non_ascii_paths() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("open"); + let exe = templates("x")[0].1.clone(); + for project in ["我的 应用/应用.fsproj", "Ünï code/Vb App.vbproj", "cs/Cs.csproj"] { + write(temp.path(), &format!("outside/{project}"), &exe); + } + write( + &root, + "all.slnx", + r#""#, + ); + write(&root, "vb.sln", "Project(\"{vb}\") = \"Vb App\", \"..\\outside\\Ünï code\\Vb App.vbproj\", \"{1}\""); + let configs = detect(&root); + let mut names: Vec<_> = configs.iter().map(|c| c.name.as_str()).collect(); + names.sort_unstable(); + assert_eq!(names, ["Cs (.NET Project)", "Vb App (.NET Project)", "应用 (.NET Project)"]); +} diff --git a/crates/ide-run/tests/dotnet_cli.rs b/crates/ide-run/tests/dotnet_cli.rs new file mode 100644 index 0000000000..d3871a26d3 --- /dev/null +++ b/crates/ide-run/tests/dotnet_cli.rs @@ -0,0 +1,83 @@ +//! Runs the real `dotnet` CLI on F# and Visual Basic projects: the detected configurations +//! build, run with their launch profile and name the assembly the debugger launches. +//! Ignored by default (CI has no .NET SDK): `cargo test -p ide-run --test dotnet_cli -- --ignored`. + +use ide_run::{ + detect, + dotnet::{resolve, target_path}, +}; +use std::{fs, path::Path, process::Command}; + +fn dotnet(dir: &Path, args: &[&str]) -> String { + let out = Command::new("dotnet") + .args(args) + .current_dir(dir) + .envs([("DOTNET_CLI_UI_LANGUAGE", "en"), ("DOTNET_NOLOGO", "1"), ("DOTNET_CLI_TELEMETRY_OPTOUT", "1")]) + .env("MSBUILDDISABLENODEREUSE", "1") + .output() + .unwrap(); + let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)); + assert!(out.status.success(), "dotnet {args:?}: {text}"); + text +} + +#[tokio::test] +#[ignore = "needs the .NET SDK"] +async fn fsharp_and_vb_configurations_build_run_and_resolve_their_assembly() { + if !Command::new("dotnet").arg("--version").output().is_ok_and(|o| o.status.success()) { + eprintln!("skipped: no dotnet SDK"); + return; + } + let temp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(temp.path()).unwrap().join("sp ace é中"); + fs::create_dir(&root).unwrap(); + for (lang, name) in [("F#", "Fs App"), ("VB", "Vb App"), ("C#", "CsApp")] { + dotnet(&root, &["new", "console", "-lang", lang, "-o", name, "--no-restore"]); + } + for (lang, name) in [("F#", "FsLib"), ("VB", "VbLib")] { + dotnet(&root, &["new", "classlib", "-lang", lang, "-o", name, "--no-restore"]); + } + for (project, folder, source, code) in [ + ( + "Fs App/Fs App.fsproj", + "Properties", + "Fs App/Program.fs", + "printfn \"demo=%s\" (System.Environment.GetEnvironmentVariable \"DEMO\")\n", + ), + ( + "Vb App/Vb App.vbproj", + "My Project", + "Vb App/Program.vb", + "Module Program\n Sub Main()\n System.Console.WriteLine(\"demo=\" & System.Environment.GetEnvironmentVariable(\"DEMO\"))\n End Sub\nEnd Module\n", + ), + ] { + fs::write(root.join(source), code).unwrap(); + let dir = root.join(project).parent().unwrap().join(folder); + fs::create_dir_all(&dir).unwrap(); + fs::write( + dir.join("launchSettings.json"), + r#"{"profiles":{"demo":{"commandName":"Project","environmentVariables":{"DEMO":"profile"}}}}"#, + ) + .unwrap(); + } + + let configs = detect(&root); + let mut projects: Vec<_> = configs.iter().map(|c| c.extras.params["project"].as_str()).collect(); + projects.sort_unstable(); + projects.dedup(); + assert_eq!(projects, ["CsApp/CsApp.csproj", "Fs App/Fs App.fsproj", "Vb App/Vb App.vbproj"]); + + for (project, assembly) in [("Fs App/Fs App.fsproj", "Fs App.dll"), ("Vb App/Vb App.vbproj", "Vb App.dll")] { + let config = configs + .iter() + .find(|c| c.extras.params["project"] == project && c.extras.params["launchProfile"] == "demo") + .unwrap_or_else(|| panic!("no profile configuration for {project}")); + let args: Vec<&str> = config.args.iter().map(String::as_str).collect(); + let output = dotnet(&root, &args); + assert!(output.contains("demo=profile"), "{project}: {output}"); + let resolved = resolve(&root, config.clone()).unwrap(); + assert_eq!(resolved.env["DEMO"], "profile"); + let target = target_path(&root, &resolved).await.unwrap(); + assert!(target.ends_with(assembly), "{target}"); + } +} diff --git a/docs/en/languages/csharp.mdx b/docs/en/languages/csharp.mdx index 7fc288b8b8..5e45ade067 100644 --- a/docs/en/languages/csharp.mdx +++ b/docs/en/languages/csharp.mdx @@ -79,10 +79,10 @@ The **NuGet Packages** tool window (bottom) manages the packages of one .NET pro ## Run -OpenIDEA creates run configurations for every `.csproj` it finds (also through `.sln` / `.slnx`) whose output type is `Exe` or `WinExe`, or that uses `Microsoft.NET.Sdk.Web`: +OpenIDEA creates run configurations for every C#, F# and Visual Basic project (`.csproj`, `.fsproj`, `.vbproj`) it finds (also through `.sln` / `.slnx`) whose output type is `Exe` or `WinExe`, or that uses `Microsoft.NET.Sdk.Web`: - **<Project> (.NET Project)**: `dotnet run --project --no-launch-profile`. -- **<Project>: <profile>**: one per profile in `Properties/launchSettings.json`, run with `--launch-profile`. The profile's environment variables, working directory, command-line arguments and `applicationUrl` (as `ASPNETCORE_URLS`) are applied. +- **<Project>: <profile>**: one per profile in `Properties/launchSettings.json` (`My Project/launchSettings.json` for Visual Basic, as `dotnet run` reads it), run with `--launch-profile`. The profile's environment variables, working directory, command-line arguments and `applicationUrl` (as `ASPNETCORE_URLS`) are applied. The **.NET Project** configuration type has fields for the project, **Target framework**, **Launch profile** and **Program arguments**. The project is built before it runs. @@ -109,7 +109,7 @@ See [Debugging](/en/guide/debugging). ## Limitations -- Automatic run configurations are created only for C# projects (`.csproj`). F# and VB projects can be built from the Project view and run or debugged from their project file's context menu, but you create saved run configurations for them yourself. +- Visual Basic has no language support: its projects get run, debug and test configurations, but line breakpoints in `.vb` files need **Allow placing breakpoints in any file**. Gutter icons on individual tests are for C# only. - Builds always use the `Debug` configuration; there is no setting to build `Release` from the Project view. - Test configurations run without a debugger; there is no Debug action for .NET tests. - There is no Visual Basic language server. diff --git a/docs/zh/languages/csharp.mdx b/docs/zh/languages/csharp.mdx index 31f9c49535..3949ac5f77 100644 --- a/docs/zh/languages/csharp.mdx +++ b/docs/zh/languages/csharp.mdx @@ -58,10 +58,10 @@ C# 在装了 Roslyn 语言服务器时用它,否则用 csharp-ls。Roslyn 是 ## 运行 -对找到的每个 `.csproj`(包括通过 `.sln` / `.slnx` 找到的),如果输出类型是 `Exe` 或 `WinExe`,或者使用了 `Microsoft.NET.Sdk.Web`,OpenIDEA 会生成运行配置: +对找到的每个 C#、F# 和 Visual Basic 项目(`.csproj`、`.fsproj`、`.vbproj`,包括通过 `.sln` / `.slnx` 找到的),如果输出类型是 `Exe` 或 `WinExe`,或者使用了 `Microsoft.NET.Sdk.Web`,OpenIDEA 会生成运行配置: - **<项目> (.NET Project)**:`dotnet run --project <路径> --no-launch-profile`。 -- **<项目>: <启动配置>**:`Properties/launchSettings.json` 中每个启动配置各一个,以 `--launch-profile` 运行,并应用该配置中的环境变量、工作目录、命令行参数以及 `applicationUrl`(作为 `ASPNETCORE_URLS`)。 +- **<项目>: <启动配置>**:`Properties/launchSettings.json`(Visual Basic 为 `My Project/launchSettings.json`,与 `dotnet run` 读取的位置一致)中每个启动配置各一个,以 `--launch-profile` 运行,并应用该配置中的环境变量、工作目录、命令行参数以及 `applicationUrl`(作为 `ASPNETCORE_URLS`)。 **.NET 项目** 运行配置类型包含项目、**目标框架**、**启动配置** 和 **程序实参** 等字段,运行前会先构建项目。 @@ -88,7 +88,7 @@ C# 在装了 Roslyn 语言服务器时用它,否则用 csharp-ls。Roslyn 是 ## 已知限制 -- 只有 C# 项目(`.csproj`)会自动生成运行配置。F# 和 VB 项目可以在项目视图中构建,并通过项目文件的右键菜单运行或调试,但保存的运行配置需要自己创建。 +- Visual Basic 没有语言支持:VB 项目有运行、调试和测试配置,但在 `.vb` 文件里打行断点需要开启 **Allow placing breakpoints in any file**。单个测试的行号栏图标只支持 C#。 - 构建始终使用 `Debug` 配置,项目视图中无法选择构建 `Release`。 - 测试配置不带调试器运行,.NET 测试没有调试入口。 - 没有 Visual Basic 语言服务器。 diff --git a/e2e/launchSettingsVb.spec.ts b/e2e/launchSettingsVb.spec.ts new file mode 100644 index 0000000000..622d3dde37 --- /dev/null +++ b/e2e/launchSettingsVb.spec.ts @@ -0,0 +1,49 @@ +/** + * Run icons in a Visual Basic project's `My Project/launchSettings.json`, where `dotnet run` reads + * its profiles. The host is stubbed at the IPC layer; `crates/ide-run/tests/dotnet_cli.rs` runs the + * real CLI. + */ +import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; + +const SHOTS = process.env.E2E_SHOTS; +const content = JSON.stringify({ profiles: { web: { commandName: "Project" } } }, null, 2); + +test("a profile in My Project runs the Visual Basic project's configuration", async ({ workbench: page }) => { + await stubDesktop(page); + await page.evaluate(async (text) => { + const backendPath = "/src/editor/core/backend.ts"; + const servicePath = "/src/workbench/contributions.ts"; + const { docBackend } = await import(/* @vite-ignore */ backendPath); + const { editorService } = await import(/* @vite-ignore */ servicePath); + const path = "/dev/acme-api/Vb App/My Project/launchSettings.json"; + docBackend().files.set(path, text); + const params = { project: "Vb App/Vb App.vbproj", launchProfile: "web" }; + const handlers = window.__ipc.handlers; + handlers.fs_probe = () => ({ size: text.length, binary: false, tooLarge: false }); + handlers.fs_read_text = ({ path }) => docBackend().files.get(String(path)) ?? ""; + handlers.fs_read_dir = () => []; + handlers.run_configs = () => [ + { + id: "dotnet:Vb App/Vb App.vbproj:run:web", + name: "Vb App: web", + kind: "dotnet", + command: "dotnet", + args: ["run", "--project", params.project, "--launch-profile", "web"], + cwd: null, + env: {}, + detected: true, + isTest: false, + debugAdapter: "netcoredbg", + params, + }, + ]; + handlers.run_apply_settings = (args) => args.configs; + await editorService().openFile(path); + }, content); + await page.locator(".cm-editor").getByTitle("Run 'web'", { exact: true }).click(); + const run = page.getByRole("menuitem", { name: /Run 'Vb App: web'/ }); + await expect(run).toBeVisible(); + if (SHOTS) await page.screenshot({ path: `${SHOTS}/vb-launch-settings-gutter.png`, animations: "disabled" }); + await expect(page.getByRole("menuitem", { name: /Debug 'Vb App: web'/ })).toBeVisible(); + expect(await ipcCalls(page, "run_configs")).not.toHaveLength(0); +}); diff --git a/src/features/run/launchSettingsGutter.test.ts b/src/features/run/launchSettingsGutter.test.ts index 43f56feea2..9d240aae09 100644 --- a/src/features/run/launchSettingsGutter.test.ts +++ b/src/features/run/launchSettingsGutter.test.ts @@ -67,4 +67,19 @@ describe("launchSettings.json run icons", () => { ]); expect(profileConfig(configs, "/repo/src/Other/Properties/launchSettings.json", "http")).toBeNull(); }); + + it("read Visual Basic profiles from My Project and the others from Properties", () => { + useProject.setState({ project: { root: "/repo" } as never }); + const of = (project: string) => ({ + ...config(`dotnet:${project}:run:`, "App (.NET Project)", ""), + params: { project, launchProfile: "" }, + }); + const vb = of("src/Vb/Vb.vbproj"); + const fs = of("src/Fs/Fs.fsproj"); + const found = (path: string) => profileConfig([vb, fs], path, "p")?.config.params?.project; + expect(found("/repo/src/Vb/My Project/launchSettings.json")).toBe("src/Vb/Vb.vbproj"); + expect(found("/repo/src/Fs/Properties/launchSettings.json")).toBe("src/Fs/Fs.fsproj"); + expect(found("/repo/src/Vb/Properties/launchSettings.json")).toBeUndefined(); + expect(found("/repo/src/Fs/My Project/launchSettings.json")).toBeUndefined(); + }); }); diff --git a/src/features/run/launchSettingsGutter.ts b/src/features/run/launchSettingsGutter.ts index b936e4a5a8..d8c85b5a73 100644 --- a/src/features/run/launchSettingsGutter.ts +++ b/src/features/run/launchSettingsGutter.ts @@ -1,5 +1,6 @@ /** - * Gutter ▶ icons on the profiles of a .NET project's `Properties/launchSettings.json`: + * Gutter ▶ icons on the profiles of a .NET project's `Properties/launchSettings.json` + * (`My Project/launchSettings.json` in Visual Basic): * Run / Debug launch the project's configuration for that profile. */ import type { Extension } from "@codemirror/state"; @@ -14,7 +15,7 @@ import { dotnetCommand } from "./dotnetTypes"; import { entryGutter, objectEntries, type ScriptEntry } from "./npmGutter"; import { loadConfigs, useRun } from "./store"; -const FILE = /(^|\/)Properties\/launchSettings\.json$/; +const FILE = /(^|\/)(?:Properties|My Project)\/launchSettings\.json$/; /** The project directory of a `launchSettings.json`, relative to the project root when inside it. */ function projectDir(path: string): string { @@ -35,7 +36,14 @@ export function profileConfig( profile: string, ): { config: RunConfig; saved: boolean } | null { const dir = projectDir(path); - const ofProject = configs.filter((c) => c.kind === "dotnet" && dirOf(c.params?.project ?? "") === dir); + // Each project reads one of the two folders, as `dotnet run` does. + const vb = /(^|\/)My Project\/launchSettings\.json$/.test(path); + const ofProject = configs.filter( + (c) => + c.kind === "dotnet" && + dirOf(c.params?.project ?? "") === dir && + /\.vbproj$/i.test(c.params?.project ?? "") === vb, + ); const saved = ofProject.find((c) => c.params?.launchProfile === profile); if (saved) return { config: saved, saved: true }; const base = ofProject.find((c) => !c.params?.launchProfile) ?? ofProject[0];