diff --git a/crates/ide-build/src/compile/mod.rs b/crates/ide-build/src/compile/mod.rs index 891f372534..b084163687 100644 --- a/crates/ide-build/src/compile/mod.rs +++ b/crates/ide-build/src/compile/mod.rs @@ -236,10 +236,13 @@ pub fn plan( let project_name = root.file_name().map_or_else(|| "project".to_owned(), |n| n.to_string_lossy().into_owned()); let module_dir = match file { Some(f) => { - let scope = model - .gradle - .iter() - .flat_map(|g| std::iter::once(root.join(&g.dir)).chain(g.projects.iter().map(|p| root.join(&p.dir)))) + let maven_dirs = model.maven.iter().flat_map(|m| m.projects.iter().map(|p| normalize(&root.join(&p.dir)))); + let gradle_dirs = model.gradle.iter().flat_map(|g| { + std::iter::once(normalize(&root.join(&g.dir))) + .chain(g.projects.iter().map(|p| normalize(&root.join(&p.dir)))) + }); + let scope = maven_dirs + .chain(gradle_dirs) .filter(|dir| f.starts_with(dir)) .max_by_key(|dir| dir.components().count()) .unwrap_or_else(|| root.to_path_buf()); @@ -251,10 +254,13 @@ pub fn plan( None => None, }; let dir = module_dir.clone().unwrap_or_else(|| root.to_path_buf()); - // A folder of sibling projects has no build file itself; its Maven projects are built one by one. - let system = detect_dir(&dir, model, root) - .or((!model.gradle.is_empty()).then_some(BuildSystem::Gradle)) - .or_else(|| model.maven.as_ref().filter(|m| !m.projects.is_empty()).map(|_| BuildSystem::Maven)) + let direct_system = detect_dir(&dir, model, root); + let has_gradle = !model.gradle.is_empty(); + let has_maven = model.maven.as_ref().is_some_and(|m| !m.projects.is_empty()); + // A folder of sibling projects has no build file itself; build every linked Gradle and Maven project in it. + let system = direct_system + .or(has_gradle.then_some(BuildSystem::Gradle)) + .or(has_maven.then_some(BuildSystem::Maven)) .ok_or_else(|| { IdeError::not_found("no supported build system (Maven, Gradle, .NET, Cargo, Go, TypeScript, CMake) found") })?; @@ -267,17 +273,26 @@ pub fn plan( ), None => project_name, }; - let steps = match system { - BuildSystem::Maven => maven_steps(root, model, kind, module_dir.as_deref(), cache, cancel)?, - BuildSystem::Gradle => gradle_steps(root, model, kind, module_dir.as_deref())?, - BuildSystem::Cargo => cargo_steps(&dir, kind), - // Go builds the file's package (a module holds many). - BuildSystem::Go => go_steps(file.and_then(Path::parent).unwrap_or(&dir), kind)?, - BuildSystem::TypeScript => ts_steps(&dir, kind), - BuildSystem::CMake => cmake_steps(&dir, kind, cmake.and_then(<[_]>::first)), - BuildSystem::Dotnet => dotnet_steps(&dir, kind)?, - // Never detected from a folder: it comes from the Project Structure (`structure_plan`). - BuildSystem::Javac => return Err(IdeError::invalid("no build tool to run")), + let steps = if module_dir.is_none() && direct_system.is_none() && has_gradle && has_maven { + let mut combined = gradle_steps(root, model, kind, None)?; + combined.extend(maven_steps(root, model, kind, None, cache, cancel)?); + combined + } else { + match system { + BuildSystem::Maven => maven_steps(root, model, kind, module_dir.as_deref(), cache, cancel)?, + BuildSystem::Gradle => gradle_steps(root, model, kind, module_dir.as_deref())?, + BuildSystem::Cargo => cargo_steps(&dir, kind), + // Go builds the file's package (a module holds many); a directory target builds itself. + BuildSystem::Go => { + let pkg = file.map(|f| if f.is_dir() { f } else { f.parent().unwrap_or(f) }).unwrap_or(&dir); + go_steps(pkg, kind)? + } + BuildSystem::TypeScript => ts_steps(&dir, kind), + BuildSystem::CMake => cmake_steps(&dir, kind, cmake.and_then(<[_]>::first)), + BuildSystem::Dotnet => dotnet_steps(&dir, kind)?, + // Never detected from a folder: it comes from the Project Structure (`structure_plan`). + BuildSystem::Javac => return Err(IdeError::invalid("no build tool to run")), + } }; Ok(BuildPlan { system, title, steps }) } @@ -1912,4 +1927,92 @@ mod tests { assert_eq!(launch_class_dirs(BuildSystem::Gradle, m, true)[0], m.join("build/classes/kotlin/test")); assert_eq!(launch_class_dirs(BuildSystem::Maven, m, true), [m.join("target/classes")]); } + + #[test] + fn polyglot_root_targets_selected_subproject_or_combines_sibling_builds() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("polyglot"); + write(&root, "Cargo.toml", "[package]\nname = \"root\"\nversion = \"0.1.0\"\n"); + write( + &root, + "fixtures/java-app/pom.xml", + "4.0.0tapp1", + ); + write(&root, "fixtures/kotlin-gradle/build.gradle.kts", "plugins { kotlin(\"jvm\") }\n"); + let model = crate::load(&root, &tmp.path().join("cache"), None); + + let maven = plan( + &root, + &model, + BuildKind::Build, + Some(&root.join("fixtures/java-app")), + None, + None, + &CancellationToken::new(), + ) + .unwrap(); + assert_eq!(maven.system, BuildSystem::Maven); + assert_eq!(maven.steps.len(), 1); + assert_eq!(maven.steps[0].cwd, root.join("fixtures/java-app")); + + let gradle = plan( + &root, + &model, + BuildKind::Build, + Some(&root.join("fixtures/kotlin-gradle")), + None, + None, + &CancellationToken::new(), + ) + .unwrap(); + assert_eq!(gradle.system, BuildSystem::Gradle); + assert_eq!(gradle.steps.len(), 1); + assert_eq!(gradle.steps[0].cwd, root.join("fixtures/kotlin-gradle")); + + let cargo = plan(&root, &model, BuildKind::Build, Some(&root), None, None, &CancellationToken::new()).unwrap(); + assert_eq!(cargo.system, BuildSystem::Cargo); + assert_eq!(cargo.steps[0].cwd, root); + + // Folder without a root build file builds both linked Gradle and Maven subprojects on Build Project. + let mixed = tmp.path().join("mixed"); + write(&mixed, "gradle-app/build.gradle.kts", "plugins { java }\n"); + write( + &mixed, + "maven-app/pom.xml", + "4.0.0tm1", + ); + let mixed_model = crate::load(&mixed, &tmp.path().join("cache2"), None); + let all = plan(&mixed, &mixed_model, BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap(); + assert_eq!(all.steps.len(), 2); + assert_eq!(all.steps[0].cwd, mixed.join("gradle-app")); + assert_eq!(all.steps[1].cwd, mixed.join("maven-app")); + } + + #[test] + fn go_directory_target_builds_that_package_without_stepping_to_parent() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("go-app"); + write(&root, "go.mod", "module example.com/app\n\ngo 1.22\n"); + write(&root, "cmd/server/main.go", "package main\nfunc main() {}\n"); + + let pkg = plan( + &root, + &BuildModel::default(), + BuildKind::Build, + Some(&root.join("cmd/server")), + None, + None, + &CancellationToken::new(), + ) + .unwrap(); + assert_eq!(pkg.system, BuildSystem::Go); + assert_eq!(pkg.steps[0].cwd, root); + assert_eq!(pkg.steps[0].args, ["build", "./cmd/server/..."]); + + let whole = + plan(&root, &BuildModel::default(), BuildKind::Build, Some(&root), None, None, &CancellationToken::new()) + .unwrap(); + assert_eq!(whole.steps[0].cwd, root); + assert_eq!(whole.steps[0].args, ["build", "./..."]); + } } diff --git a/crates/ide-build/src/jbuild/mod.rs b/crates/ide-build/src/jbuild/mod.rs index d961e1218d..55a9f5b6f5 100644 --- a/crates/ide-build/src/jbuild/mod.rs +++ b/crates/ide-build/src/jbuild/mod.rs @@ -517,7 +517,15 @@ impl JavaBuild<'_> { let Some(project) = project_at(path) else { return Ok(Built::Unsupported(format!("no Java project holds {}", path.display()))); }; - launch_projects(&reactor_model, project, true) + let mut all: Vec<(&ProjectModel, bool)> = Vec::new(); + for member in reactor_model.projects.iter().filter(|p| p.dir.starts_with(&project.dir)) { + for set in launch_projects(&reactor_model, member, true) { + if !all.iter().any(|(p, t)| p.dir == set.0.dir && *t == set.1) { + all.push(set); + } + } + } + all } Target::File(file) => { let Some(project) = project_at(file) else { diff --git a/crates/ide-build/src/jbuild/tests.rs b/crates/ide-build/src/jbuild/tests.rs index 44866822d9..0c3db9f289 100644 --- a/crates/ide-build/src/jbuild/tests.rs +++ b/crates/ide-build/src/jbuild/tests.rs @@ -260,6 +260,12 @@ fn builds_maven_modules_with_javac_and_only_what_changed() { assert_eq!(f.build(Target::Project).failure, None); assert_eq!(f.steps(), ["javac lib (tests, 1 file)"]); assert!(f.out("t.lib/test-classes/l/LTest.class").is_file()); + + // Build Module on the root aggregator compiles every submodule under it. + f.write("app/src/test/java/a/AggTest.java", "package a;\nclass AggTest { String s = l.L.name(); }\n"); + assert_eq!(f.build(Target::Module(&f.root)).failure, None); + assert_eq!(f.steps(), ["javac app (tests, 1 of 2 files)"]); + assert!(f.out("t.app/test-classes/a/AggTest.class").is_file()); } #[test] diff --git a/crates/ide-host/src/ops/build.rs b/crates/ide-host/src/ops/build.rs index b2f61c623a..4c82c51184 100644 --- a/crates/ide-host/src/ops/build.rs +++ b/crates/ide-host/src/ops/build.rs @@ -971,6 +971,7 @@ pub async fn build_run( host.require_trust(window)?; let project = host.project(window)?; let (root, cache, sink) = (project.root.clone(), project.build_cache_dir(), project.sink.clone()); + let file = file.map(|f| ide_core::project_roots::resolve(&root, &f)); let settings = project.settings.effective(); let detected = project.detected_roots.read().clone(); let config_dir = host.config_dir.clone(); diff --git a/e2e/run.spec.ts b/e2e/run.spec.ts index 4ce9d8aeca..5ddd88848d 100644 --- a/e2e/run.spec.ts +++ b/e2e/run.spec.ts @@ -569,7 +569,7 @@ test("CMake builds the selected target in Build before starting only the applica await loadConfigs(); selectConfig(app.id); }); - await page.getByRole("button", { name: "Build Project", exact: true }).click(); + await page.getByRole("button", { name: "Build 'hello [Release, release]'", exact: true }).click(); const build = page.getByRole("region", { name: "Build", exact: true }); await expect(build.getByText("COMPILER_OUTPUT", { exact: true })).toBeVisible(); expect(await ipcCalls(page, "run_start")).toHaveLength(0); diff --git a/src/features/build/BuildTitleItem.tsx b/src/features/build/BuildTitleItem.tsx index 58881bbafe..5926f7f586 100644 --- a/src/features/build/BuildTitleItem.tsx +++ b/src/features/build/BuildTitleItem.tsx @@ -1,32 +1,54 @@ import { IconButton } from "@/ui"; import { executeAction } from "@/platform/actions"; import { useContextKeys } from "@/platform/context"; +import { useTx } from "@/platform/i18n"; import { shortcutLabel } from "@/platform/keymap"; import { BUILD_RUNNING } from "./store"; import styles from "./Build.module.css"; /** Run configuration kinds a project build precedes; scripts (Python, shell, Node…) have nothing to compile. */ -const COMPILED_KINDS = new Set(["", "spring-boot", "application", "maven", "gradle"]); +const COMPILED_KINDS = new Set(["", "spring-boot", "application", "junit", "tomcat", "maven", "gradle"]); -/** Main toolbar hammer, left of the run widget, for compiled project configurations. */ +/** Main toolbar hammer, left of the run widget, targeting the selected run configuration when possible. */ export function BuildTitleItem() { + const tx = useTx(); + const cmake = useContextKeys((c) => (typeof c["run.cmakeBuild"] === "string" ? c["run.cmakeBuild"] : null)); + const target = useContextKeys((c) => (typeof c["run.buildTarget"] === "string" ? c["run.buildTarget"] : null)); + const targetName = useContextKeys((c) => + typeof c["run.buildTargetName"] === "string" ? c["run.buildTargetName"] : null, + ); const shown = useContextKeys( (c) => !!c["run.cmakeBuild"] || + !!c["run.buildTarget"] || ((!!c["build.maven"] || !!c["build.gradle"]) && COMPILED_KINDS.has(String(c["run.selectedKind"] ?? ""))), ); const running = useContextKeys((c) => !!c[BUILD_RUNNING]); if (!shown) return null; + + const title = targetName ? tx`Build '${targetName}'` : tx("Build Project"); + const shortcut = !target ? shortcutLabel("build.buildProject") : undefined; + + const onClick = () => { + if (cmake) { + void executeAction("build.buildProject", { cmake }); + } else if (target) { + void executeAction("build.buildModule", { target }); + } else { + void executeAction("build.buildProject"); + } + }; + return ( void executeAction("build.buildProject")} + onClick={onClick} /> ); } diff --git a/src/features/build/build.test.tsx b/src/features/build/build.test.tsx index d9b91c27b4..ee66a7656c 100644 --- a/src/features/build/build.test.tsx +++ b/src/features/build/build.test.tsx @@ -182,19 +182,34 @@ describe("build feature", () => { useProject.setState({ project: null, settings: null }); setContext("projectOpen", false); setContext("run.cmakeBuild", null); + setContext("run.buildTarget", null); + setContext("run.buildTargetName", null); + setContext("run.selectedKind", ""); + setContext("build.maven", false); + setContext("build.gradle", false); clearContext("editorPath"); }); it("shows the CMake hammer and builds the selected target through the shared action", async () => { setContext("run.cmakeBuild", "cmake:release:hello:build"); + setContext("run.buildTargetName", "hello [Release]"); render(); - expect(screen.getByRole("button", { name: "Build Project" })).toBeVisible(); - fireEvent.click(screen.getByRole("button", { name: "Build Project" })); + const button = screen.getByRole("button", { name: "Build 'hello [Release]'" }); + expect(button).toBeVisible(); + fireEvent.click(button); await act(async () => {}); expect(fake.calls.at(-1)).toMatchObject({ cmake: "cmake:release:hello:build" }); await act(async () => { fake.resolve(result([], true)); }); + // Rerun repeats the same CMake target. + const rerun = rerunBuild(); + await act(async () => {}); + expect(fake.calls.at(-1)).toMatchObject({ cmake: "cmake:release:hello:build" }); + await act(async () => { + fake.resolve(result([], true)); + await rerun; + }); const explicit = executeAction("build.buildProject", { cmake: "cmake:debug:other:build", activate: false }); await act(async () => {}); expect(fake.calls.at(-1)).toMatchObject({ cmake: "cmake:debug:other:build" }); @@ -204,6 +219,44 @@ describe("build feature", () => { }); }); + it("builds the selected run configuration's module from the toolbar hammer while Cmd+F9 builds the project", async () => { + setContext("run.buildTarget", "/p/fixtures/java-app"); + setContext("run.buildTargetName", "App"); + setContext("run.selectedKind", "application"); + render(); + const button = screen.getByRole("button", { name: "Build 'App'" }); + expect(button).toBeVisible(); + fireEvent.click(button); + await act(async () => {}); + expect(fake.calls.at(-1)).toEqual({ kind: "build", file: "/p/fixtures/java-app", clear: [] }); + await act(async () => { + fake.resolve(result([], true)); + }); + + // Build Project action keeps project-wide semantics (`file: null`). + const projectBuild = executeAction("build.buildProject"); + await act(async () => {}); + expect(fake.calls.at(-1)).toEqual({ kind: "build", file: null, clear: [] }); + await act(async () => { + fake.resolve(result([], true)); + await projectBuild; + }); + }); + + it("falls back to Build Project on the hammer when no module target is selected in a Maven project", async () => { + setContext("build.maven", true); + setContext("run.selectedKind", ""); + render(); + const button = screen.getByRole("button", { name: "Build Project" }); + expect(button).toBeVisible(); + fireEvent.click(button); + await act(async () => {}); + expect(fake.calls.at(-1)).toEqual({ kind: "build", file: null, clear: [] }); + await act(async () => { + fake.resolve(result([], true)); + }); + }); + it("registers the Build menu actions, shortcuts and an on-use bottom tool window", () => { for (const id of ["build.buildProject", "build.buildModule", "build.rebuildProject", "build.buildArtifacts"]) { expect(getAction(id), id).toBeDefined(); diff --git a/src/features/build/store.ts b/src/features/build/store.ts index a1f90321f5..e040ffbace 100644 --- a/src/features/build/store.ts +++ b/src/features/build/store.ts @@ -100,6 +100,8 @@ export interface BuildState { kind: BuildKind | null; /** Module file or folder of a Build Module, `null` for the project. */ file: string | null; + /** CMake build configuration ID when building a CMake target. */ + cmake: string | null; title: string; system: BuildSystem | null; status: BuildStatus | null; @@ -119,6 +121,7 @@ const INITIAL: BuildState = { request: null, kind: null, file: null, + cmake: null, title: "", system: null, status: null, @@ -170,7 +173,16 @@ export async function startBuild( const taskTitle = TITLES[kind]; const cancel = () => backend.cancel(request); const previous = useBuildRun.getState().files; - useBuildRun.setState({ ...INITIAL, request, kind, file, title: taskTitle, status: "running", files: previous }); + useBuildRun.setState({ + ...INITIAL, + request, + kind, + file, + cmake, + title: taskTitle, + status: "running", + files: previous, + }); setContext(BUILD_LAST_STATUS, null); setContext(BUILD_RUNNING, true); showBuildWindow("start", activate); @@ -423,9 +435,9 @@ export function stopBuild() { /** Runs the last build again (the tool window's rerun button). */ export function rerunBuild() { - const { kind, file } = useBuildRun.getState(); + const { kind, file, cmake } = useBuildRun.getState(); if (!kind) return file ? startCompileFile(file) : startBuild("build", null); - return startBuild(kind, file); + return startBuild(kind, file, true, cmake); } export function resetBuildRun() { diff --git a/src/features/run/buildTarget.test.ts b/src/features/run/buildTarget.test.ts new file mode 100644 index 0000000000..26c3598afd --- /dev/null +++ b/src/features/run/buildTarget.test.ts @@ -0,0 +1,161 @@ +import { describe, expect, it } from "vitest"; +import type { GradleModel, RunConfig } from "@/platform/ipc"; +import { selectedBuildTarget } from "./buildTarget"; + +const cfg = (overrides: Partial): RunConfig => ({ + id: "id", + name: "App", + kind: "application", + command: "java", + args: [], + cwd: null, + env: {}, + detected: true, + isTest: false, + debugAdapter: null, + ...overrides, +}); + +const GRADLE: GradleModel = { + dir: "", + command: "./gradlew", + env: {}, + javaVersion: null, + projects: [ + { path: ":", name: "root", dir: "", buildFile: "build.gradle.kts", tasks: [] }, + { path: ":services:api", name: "api", dir: "services/api", buildFile: "services/api/build.gradle.kts", tasks: [] }, + ], + syncedAt: null, + syncError: null, + stale: false, +}; + +describe("selectedBuildTarget", () => { + it("resolves Java and Spring Boot application modules against the project root", () => { + const sub = cfg({ name: "App", kind: "application", module: "fixtures/java-app" }); + expect(selectedBuildTarget(sub, [sub], "/repo")).toEqual({ + cmake: null, + target: "/repo/fixtures/java-app", + name: "App", + }); + + const rootApp = cfg({ name: "BootApp", kind: "spring-boot", module: "" }); + expect(selectedBuildTarget(rootApp, [rootApp], "/repo")).toEqual({ + cmake: null, + target: "/repo", + name: "BootApp", + }); + + const external = cfg({ name: "Sibling", kind: "application", module: "/ws/member-a" }); + expect(selectedBuildTarget(external, [external], "/ws")).toEqual({ + cmake: null, + target: "/ws/member-a", + name: "Sibling", + }); + + const legacy = cfg({ name: "Legacy", kind: "application", module: undefined, cwd: null }); + expect(selectedBuildTarget(legacy, [legacy], "/repo")).toEqual({ + cmake: null, + target: null, + name: null, + }); + }); + + it("resolves Maven, Gradle, JUnit, Tomcat, Cargo, Go, and .NET targets", () => { + const mavenPl = cfg({ name: "mvn api", kind: "maven", cwd: null, args: ["-pl", "services/api", "test"] }); + expect(selectedBuildTarget(mavenPl, [mavenPl], "/repo")).toEqual({ + cmake: null, + target: "/repo/services/api", + name: "mvn api", + }); + + const mavenRoot = cfg({ name: "mvn package", kind: "maven", cwd: null, args: ["package"] }); + expect(selectedBuildTarget(mavenRoot, [mavenRoot], "/repo")).toEqual({ + cmake: null, + target: "/repo", + name: "mvn package", + }); + + const gradleTask = cfg({ name: "api tests", kind: "gradle", cwd: null, args: [":services:api:test"] }); + expect(selectedBuildTarget(gradleTask, [gradleTask], "/repo", [GRADLE])).toEqual({ + cmake: null, + target: "/repo/services/api", + name: "api tests", + }); + + const gradleSub = cfg({ name: "gradle run", kind: "gradle", cwd: "fixtures/kotlin-gradle", args: ["run"] }); + expect(selectedBuildTarget(gradleSub, [gradleSub], "/repo")).toEqual({ + cmake: null, + target: "/repo/fixtures/kotlin-gradle", + name: "gradle run", + }); + + const junitRoot = cfg({ name: "AppTest", kind: "junit", params: { module: "." } }); + expect(selectedBuildTarget(junitRoot, [junitRoot], "/repo")).toEqual({ + cmake: null, + target: "/repo", + name: "AppTest", + }); + + const tomcat = cfg({ name: "Tomcat", kind: "tomcat", cwd: "web" }); + expect(selectedBuildTarget(tomcat, [tomcat], "/repo")).toEqual({ + cmake: null, + target: "/repo/web", + name: "Tomcat", + }); + + const dotnet = cfg({ name: "WebApi", kind: "dotnet", params: { project: "src/WebApi/WebApi.csproj" } }); + expect(selectedBuildTarget(dotnet, [dotnet], "/repo")).toEqual({ + cmake: null, + target: "/repo/src/WebApi/WebApi.csproj", + name: "WebApi", + }); + + const cargo = cfg({ name: "cargo run", kind: "cargo", cwd: "crates/cli" }); + expect(selectedBuildTarget(cargo, [cargo], "/repo")).toEqual({ + cmake: null, + target: "/repo/crates/cli", + name: "cargo run", + }); + + const go = cfg({ name: "go run", kind: "go", cwd: "cmd/server" }); + expect(selectedBuildTarget(go, [go], "/repo")).toEqual({ + cmake: null, + target: "/repo/cmd/server", + name: "go run", + }); + }); + + it("keeps CMake target resolution and hides script configurations", () => { + const build = cfg({ + id: "cmake:release:hello:build", + name: "Build hello", + kind: "cmake", + command: "cmake", + args: ["--build", "release", "--target", "hello"], + }); + const app = cfg({ + id: "cmake:release:hello", + name: "hello [Release]", + kind: "cmake-application", + beforeLaunch: [{ kind: "build", target: build.id }], + }); + expect(selectedBuildTarget(app, [build, app], "/repo")).toEqual({ + cmake: build.id, + target: null, + name: "hello [Release]", + }); + expect(selectedBuildTarget(undefined, [build, app], "/repo")).toEqual({ + cmake: build.id, + target: null, + name: null, + }); + + const script = cfg({ name: "dev", kind: "npm", command: "pnpm", args: ["dev"] }); + expect(selectedBuildTarget(script, [script], "/repo")).toEqual({ + cmake: null, + target: null, + name: null, + }); + }); +}); diff --git a/src/features/run/buildTarget.ts b/src/features/run/buildTarget.ts new file mode 100644 index 0000000000..a5fe5598bc --- /dev/null +++ b/src/features/run/buildTarget.ts @@ -0,0 +1,133 @@ +import type { GradleModel, RunConfig } from "@/platform/ipc"; +import { cmakeBuildId } from "./cmake"; +import { joinPath } from "./links"; + +export interface SelectedBuildTarget { + /** CMake build configuration ID when the selected configuration builds through CMake. */ + cmake: string | null; + /** Module directory or project file to build, or `null` for a whole-project build. */ + target: string | null; + /** Selected configuration name for the toolbar hammer tooltip (`Build ''`), or `null` for `Build Project`. */ + name: string | null; +} + +const ROOT_MODULE = "."; + +function resolvePath(raw: string, root: string | null): string | null { + if (/^(?:[A-Za-z]:[\\/]|\/)/.test(raw)) return joinPath("/", raw); + if (!root) return null; + return raw ? joinPath(root, raw) : root; +} + +/** Extracts a single directory selector from Maven `-pl` / `--projects` arguments. */ +function mavenProjectListDir(args: readonly string[]): string | null { + for (let i = 0; i < args.length; i++) { + const arg = args[i]!; + let value: string | null = null; + if (arg === "-pl" || arg === "--projects") { + value = args[i + 1] ?? null; + } else if (arg.startsWith("-pl=")) { + value = arg.slice(4); + } else if (arg.startsWith("--projects=")) { + value = arg.slice(11); + } + if (!value) continue; + const trimmed = value.trim(); + // Skip multi-module lists, exclusions (`!mod`), and artifactId selectors (`:artifact`). + if (!trimmed || trimmed.includes(",") || trimmed.startsWith("!") || trimmed.startsWith(":")) return null; + return trimmed; + } + return null; +} + +/** Resolves a Gradle subproject directory from a qualified task like `:services:api:test`. */ +function gradleTaskProjectDir( + args: readonly string[], + cwd: string | null, + gradleModels: readonly GradleModel[], +): string | null { + const normalizedCwd = (cwd ?? "").replace(/\\/g, "/").replace(/\/+$/, ""); + const scoped = gradleModels.filter((g) => g.dir.replace(/\\/g, "/").replace(/\/+$/, "") === normalizedCwd); + const candidates = scoped.length ? scoped : gradleModels; + for (const arg of args) { + if (arg.startsWith("-")) continue; + const match = /^(:[^:\s]+(?::[^:\s]+)*):[^:\s]+$/.exec(arg); + if (!match) continue; + const path = match[1]!; + for (const model of candidates) { + const project = model.projects.find((p) => p.path === path); + if (project) return project.dir; + } + } + return null; +} + +function targetPathFor(config: RunConfig, root: string | null, gradleModels: readonly GradleModel[]): string | null { + switch (config.kind) { + case "application": + case "spring-boot": { + const raw = config.module ?? config.cwd; + return raw != null ? resolvePath(raw, root) : null; + } + case "junit": { + const paramModule = config.params?.module; + const raw = config.module ?? (paramModule ? (paramModule === ROOT_MODULE ? "" : paramModule) : config.cwd); + return raw != null ? resolvePath(raw, root) : null; + } + case "tomcat": { + const raw = config.module ?? config.cwd; + return raw != null ? resolvePath(raw, root) : null; + } + case "maven": { + if (config.module != null) return resolvePath(config.module, root); + const base = config.cwd ?? ""; + const pl = mavenProjectListDir(config.args); + if (pl) { + const basePath = resolvePath(base, root); + return basePath ? joinPath(basePath, pl) : null; + } + return resolvePath(base, root); + } + case "gradle": { + if (config.module != null) return resolvePath(config.module, root); + const taskDir = gradleTaskProjectDir(config.args, config.cwd, gradleModels); + if (taskDir != null) return resolvePath(taskDir, root); + return resolvePath(config.cwd ?? "", root); + } + case "dotnet": + case "dotnet-test": { + const project = config.params?.project?.trim(); + const raw = project || config.module || config.cwd || ""; + return resolvePath(raw, root); + } + case "cargo": { + return resolvePath(config.module ?? config.cwd ?? "", root); + } + case "go": { + return resolvePath(config.module ?? config.params?.module ?? config.cwd ?? "", root); + } + default: + return null; + } +} + +/** + * Resolves what the main toolbar hammer builds for the currently selected run configuration: + * a CMake target, the selected configuration's module/project directory, or a fallback project build. + */ +export function selectedBuildTarget( + selected: RunConfig | undefined, + configs: readonly RunConfig[], + projectRoot: string | null, + gradleModels: readonly GradleModel[] = [], +): SelectedBuildTarget { + if (!selected) { + const fallbackCmake = configs.find((c) => c.kind === "cmake" && c.args[0] === "--build"); + return { cmake: cmakeBuildId(fallbackCmake, configs), target: null, name: null }; + } + const cmake = cmakeBuildId(selected, configs); + if (cmake) return { cmake, target: null, name: selected.name }; + const target = targetPathFor(selected, projectRoot, gradleModels); + if (target) return { cmake: null, target, name: selected.name }; + return { cmake: null, target: null, name: null }; +} diff --git a/src/features/run/index.ts b/src/features/run/index.ts index 92e4c2bd69..4f5d3f6985 100644 --- a/src/features/run/index.ts +++ b/src/features/run/index.ts @@ -4,6 +4,7 @@ */ import { registerEditorContribution } from "@/editor/api"; import { executeAction, executeActionOrThrow, getAction, registerActions } from "@/platform/actions"; +import { useBuildModel } from "@/platform/buildModel"; import { getContext, setContext, useContextKeys } from "@/platform/context"; import { call, commands, onIdeEvent, type RunConfig } from "@/platform/ipc"; import { projectFolder, useProject } from "@/platform/project"; @@ -63,7 +64,7 @@ import { } from "./services"; import { liveServiceSession, serviceSessions } from "./serviceSessions"; import { ServiceImportHost } from "./serviceImport"; -import { cmakeBuildId } from "./cmake"; +import { selectedBuildTarget } from "./buildTarget"; import { configurationChecks } from "./configurationChecks"; import { runBeforeLaunch } from "./beforeLaunch"; import { compoundChildren } from "./configs"; @@ -937,16 +938,40 @@ export function activate(): () => void { ]), onIdeEvent("runExited", (e) => onRunExited(e.run, e.code)), onIdeEvent("projectRootsChanged", scheduleReload), - // Lets other title items follow the selected configuration (e.g. Build shows only for compiled ones). - useRun.subscribe((s) => { - const selected = s.configs.find((c) => c.id === s.selectedId); - setContext("run.selectedKind", selected?.kind ?? ""); - const cmake = selected ?? s.configs.find((c) => c.kind === "cmake" && c.args[0] === "--build"); - setContext("run.cmakeBuild", cmakeBuildId(cmake, s.configs)); - setContext("run.updatableRunning", updatableSessions().length > 0); - syncFlutterRunApps(s.sessions); - setContext("run.flutterHotReloadable", !!hotReloadSession()); - }), + // Lets other title items follow the selected configuration (e.g. Build targets the selected run configuration). + (() => { + const syncBuildTarget = () => { + const s = useRun.getState(); + const selected = s.configs.find((c) => c.id === s.selectedId); + const projectRoot = useProject.getState().project?.root ?? null; + const gradle = useBuildModel.getState().model?.gradle ?? []; + const build = selectedBuildTarget(selected, s.configs, projectRoot, gradle); + setContext("run.selectedKind", selected?.kind ?? ""); + setContext("run.cmakeBuild", build.cmake); + setContext("run.buildTarget", build.target); + setContext("run.buildTargetName", build.name); + }; + syncBuildTarget(); + const unsubRun = useRun.subscribe((s) => { + syncBuildTarget(); + setContext("run.updatableRunning", updatableSessions().length > 0); + syncFlutterRunApps(s.sessions); + setContext("run.flutterHotReloadable", !!hotReloadSession()); + }); + const unsubModel = useBuildModel.subscribe(syncBuildTarget); + const unsubProject = useProject.subscribe((s, prev) => { + if (s.project?.root !== prev.project?.root) syncBuildTarget(); + }); + return () => { + unsubRun(); + unsubModel(); + unsubProject(); + setContext("run.selectedKind", ""); + setContext("run.cmakeBuild", null); + setContext("run.buildTarget", null); + setContext("run.buildTargetName", null); + }; + })(), useFlutterRunApps.subscribe(() => setContext("run.flutterHotReloadable", !!hotReloadSession())), // Agent tabs (`run_command`): the archive keeps at most Settings' number of them. useRun.subscribe((s, prev) => { diff --git a/src/platform/locales/text/ru.json b/src/platform/locales/text/ru.json index 39973e804d..334955bea3 100644 --- a/src/platform/locales/text/ru.json +++ b/src/platform/locales/text/ru.json @@ -1239,6 +1239,7 @@ "Compile File": "Скомпилировать файл", "Compiles the current Java file with javac, without building its module": "Компилирует текущий файл Java с помощью javac без сборки его модуля", "Build Project": "Собрать проект", + "Build '{targetName}'": "Собрать «{targetName}»", "Build failed": "Ошибка сборки", "Build files changed since the last reload": "Файлы сборки изменились с момента последней перезагрузки", "Build output": "Вывод сборки", diff --git a/src/platform/locales/text/tr.json b/src/platform/locales/text/tr.json index 38bdb9687e..0b3f53c62c 100644 --- a/src/platform/locales/text/tr.json +++ b/src/platform/locales/text/tr.json @@ -3143,6 +3143,7 @@ "Browse…": "Gözat…", "Build": "Derle", "Build Project": "Projeyi Derle", + "Build '{targetName}'": "'{targetName}' Derle", "Build failed": "Derleme başarısız oldu", "Build files changed since the last reload": "Derleme dosyaları son yeniden yüklemeden bu yana değişti", "Build output": "Derleme çıktısı", diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index 36335aea8c..a7a4eeeab9 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -927,6 +927,7 @@ "Compile File": "編譯檔案", "Compiles the current Java file with javac, without building its module": "使用 javac 僅編譯目前 Java 檔案,不建置其模組", "Build Project": "建置專案", + "Build '{targetName}'": "建置 '{targetName}'", "Build failed": "建置失敗", "Build files changed since the last reload": "自上次重新載入以來建置檔案已更改", "Build output": "建置輸出", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index e574b5bdaa..eaf7ddecff 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -1261,6 +1261,7 @@ "Compile File": "编译文件", "Compiles the current Java file with javac, without building its module": "使用 javac 仅编译当前 Java 文件,不构建其模块", "Build Project": "构建项目", + "Build '{targetName}'": "构建 '{targetName}'", "Build failed": "构建失败", "Build files changed since the last reload": "自上次重新加载以来构建文件已更改", "Build output": "构建输出",