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 <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-12-03 16:39:50 +08:00
1 джерело 17a32e0c1f
коміт 62bac6ec8c
9 files changed
+275 -20

No files matched your search

+5 -4
Переглянути файл
@@ -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<RunConfig>) {
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(
+12 -6
Переглянути файл
@@ -165,6 +165,13 @@ pub fn parse_profiles(json: &str) -> BTreeMap<String, Profile> {
.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<PathBuf> {
let paths: Vec<String> = if xml {
elements(src)
@@ -184,17 +191,16 @@ pub fn solution_projects(src: &str, xml: bool) -> Vec<PathBuf> {
})
.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<String, Profile> {
// 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()
}
+94 -1
Переглянути файл
@@ -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#"<Solution><Folder Name="/src/"><Project Path="src\A&amp;B\App.csproj" /></Folder><Project Path="other.vbproj" /></Solution>"#;
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("<Solution><Project", true).is_empty());
}
@@ -191,3 +194,93 @@ fn an_xunit_v3_testing_platform_project_gets_a_test_configuration() {
assert_eq!(configs[0].extras.params["project"], "tests/App.Tests/App.Tests.csproj");
assert_eq!(configs[0].args, ["test", "tests/App.Tests/App.Tests.csproj", "--framework", "net11.0"]);
}
/// The project files `dotnet new` writes for F# and Visual Basic (SDK 11), by kind.
fn templates(lang: &str) -> [(&'static str, String, bool, bool); 5] {
let exe = r#"<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net11.0</TargetFramework></PropertyGroup></Project>"#;
let winexe = r#"<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>WinExe</OutputType><TargetFrameworks>net11.0;net10.0</TargetFrameworks></PropertyGroup></Project>"#;
let library = r#"<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><TargetFramework>net11.0</TargetFramework></PropertyGroup></Project>"#;
let web = r#"<Project Sdk="Microsoft.NET.Sdk.Web"><PropertyGroup><TargetFramework>net11.0</TargetFramework></PropertyGroup></Project>"#;
let test = format!(
r#"<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><TargetFramework>net11.0</TargetFramework><IsPackable>false</IsPackable></PropertyGroup><ItemGroup><Compile Include="{lang}"/></ItemGroup><ItemGroup><PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1"/><PackageReference Include="xunit" Version="2.9.3"/></ItemGroup></Project>"#
);
[
("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"), "<Project/>");
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#"<Solution><Folder Name="/src/"><Project Path="../outside/我的 应用/应用.fsproj"/></Folder><Project Path="..\outside\cs\Cs.csproj"/></Solution>"#,
);
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)"]);
}
+83
Переглянути файл
@@ -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}");
}
}
+3 -3
Переглянути файл
@@ -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`:
- **&lt;Project&gt; (.NET Project)**: `dotnet run --project <path> --no-launch-profile`.
- **&lt;Project&gt;: &lt;profile&gt;**: 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.
- **&lt;Project&gt;: &lt;profile&gt;**: 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.
+3 -3
Переглянути файл
@@ -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 会生成运行配置:
- **&lt;项目&gt; (.NET Project)**:`dotnet run --project <路径> --no-launch-profile`。
- **&lt;项目&gt;: &lt;启动配置&gt;**:`Properties/launchSettings.json` 中每个启动配置各一个,以 `--launch-profile` 运行,并应用该配置中的环境变量、工作目录、命令行参数以及 `applicationUrl`(作为 `ASPNETCORE_URLS`)。
- **&lt;项目&gt;: &lt;启动配置&gt;**:`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 语言服务器。
+49
Переглянути файл
@@ -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);
});
+15
Переглянути файл
@@ -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();
});
});
+11 -3
Переглянути файл
@@ -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];