diff --git a/crates/ide-host/src/ops/build.rs b/crates/ide-host/src/ops/build.rs index 326e970af6..12159473b4 100644 --- a/crates/ide-host/src/ops/build.rs +++ b/crates/ide-host/src/ops/build.rs @@ -1314,7 +1314,11 @@ mod build_tool_settings_tests { let configure = config("configure", &["-S", ".", "-B", "release", "-G", "Ninja"]); let mut build = config("target", &["--build", "release", "--target", "hello", "--config", "Release", "-j", "8"]); - build.extras.before_launch.push(ide_run::BeforeLaunchTask { kind: "build".into(), target: "configure".into() }); + build.extras.before_launch.push(ide_run::BeforeLaunchTask { + kind: "build".into(), + target: "configure".into(), + ..Default::default() + }); let configs = [configure, build]; for kind in [BuildKind::Build, BuildKind::Rebuild] { let plan = cmake_plan(root.path(), kind, &configs, "target").unwrap(); diff --git a/crates/ide-run/src/detect/cmake.rs b/crates/ide-run/src/detect/cmake.rs index c0aa4c4044..0d7ee42747 100644 --- a/crates/ide-run/src/detect/cmake.rs +++ b/crates/ide-run/src/detect/cmake.rs @@ -18,7 +18,11 @@ fn reply_file(reply: &Path, name: &str) -> Option { } fn before(config: &mut RunConfig, id: &str) { - config.extras.before_launch.push(BeforeLaunchTask { kind: "build".into(), target: id.into() }); + config.extras.before_launch.push(BeforeLaunchTask { + kind: "build".into(), + target: id.into(), + ..Default::default() + }); } #[derive(Default)] diff --git a/crates/ide-run/src/detect/dotnet.rs b/crates/ide-run/src/detect/dotnet.rs index fb8025370c..3575b70d32 100644 --- a/crates/ide-run/src/detect/dotnet.rs +++ b/crates/ide-run/src/detect/dotnet.rs @@ -100,7 +100,7 @@ fn detected(project: &str, name: &str, profile: &str, params: BTreeMap) { &["run", "--skip-build", &product], ) .debug("lldb-dap"); - c.extras - .before_launch - .push(BeforeLaunchTask { kind: "command".into(), target: format!("swift build --product {product}") }); + c.extras.before_launch.push(BeforeLaunchTask { + kind: "command".into(), + target: format!("swift build --product {product}"), + ..Default::default() + }); let exe = if cfg!(windows) { ".exe" } else { "" }; c.extras.params.insert("program".into(), format!(".build/debug/{product}{exe}")); c.extras.params.insert("product".into(), product); diff --git a/crates/ide-run/src/detect/zig.rs b/crates/ide-run/src/detect/zig.rs index 41b23c40bc..fba7071908 100644 --- a/crates/ide-run/src/detect/zig.rs +++ b/crates/ide-run/src/detect/zig.rs @@ -41,7 +41,11 @@ pub(super) fn detect(dir: &Path, out: &mut Vec) { }; let mut c = config(format!("zig:exe:{}", exe.name), exe.name.clone(), "zig-application", &binary, &[]) .debug("codelldb"); - c.extras.before_launch.push(BeforeLaunchTask { kind: "run".into(), target: BUILD_ID.into() }); + c.extras.before_launch.push(BeforeLaunchTask { + kind: "run".into(), + target: BUILD_ID.into(), + ..Default::default() + }); if let Some(source) = exe.source { c.extras.params.insert("source".into(), source); } diff --git a/crates/ide-run/src/lib.rs b/crates/ide-run/src/lib.rs index 174556217d..eed744095f 100644 --- a/crates/ide-run/src/lib.rs +++ b/crates/ide-run/src/lib.rs @@ -98,10 +98,16 @@ impl BuildPolicy { pub struct BeforeLaunchTask { /// `run` (another configuration id) | `build` (project, or `target` = CMake build id) | /// `tool` (external tool id) | - /// `command` (a shell command line) | `toolWindow` (tool window id). + /// `command` (a shell command line) | `toolWindow` (tool window id) | + /// `maven` / `gradle` (goals or tasks command line). pub kind: String, + #[specta(optional)] #[serde(default)] pub target: String, + /// Build tool project directory, relative to the opened project when possible. + #[specta(optional)] + #[serde(default, skip_serializing_if = "Option::is_none")] + pub project_dir: Option, } fn yes() -> bool { diff --git a/crates/ide-run/tests/config.rs b/crates/ide-run/tests/config.rs index b9b28eeedf..5b5cccb122 100644 --- a/crates/ide-run/tests/config.rs +++ b/crates/ide-run/tests/config.rs @@ -143,8 +143,10 @@ fn extras_round_trip_and_local_file() { shared.extras.stdin_file = Some("in.txt".into()); shared.extras.output_file = Some("out.log".into()); shared.extras.before_launch = vec![ - BeforeLaunchTask { kind: "build".into(), target: String::new() }, - BeforeLaunchTask { kind: "run".into(), target: "user:migrate".into() }, + BeforeLaunchTask { kind: "build".into(), ..Default::default() }, + BeforeLaunchTask { kind: "run".into(), target: "user:migrate".into(), ..Default::default() }, + BeforeLaunchTask { kind: "maven".into(), target: "clean package".into(), project_dir: Some("web".into()) }, + BeforeLaunchTask { kind: "gradle".into(), target: "assemble".into(), project_dir: Some(".".into()) }, ]; shared.extras.show_on_stderr = true; shared.extras.open_tool_window = Some(false); diff --git a/e2e/runConfigLayout.spec.ts b/e2e/runConfigLayout.spec.ts index 4d3c6fab07..92d7bc175a 100644 --- a/e2e/runConfigLayout.spec.ts +++ b/e2e/runConfigLayout.spec.ts @@ -140,6 +140,80 @@ test("before-launch tasks wrap as ordered tags and keep their edit controls", as await expect(tasks.getByRole("button", { name: "3. Build Project", exact: true })).toBeVisible(); }); +test("Tomcat can add and edit a Gradle task ahead of the default artifact build", async ({ workbench: page }) => { + await page.evaluate(async () => { + const runPath = "/src/features/run/store.ts"; + const projectPath = "/src/platform/project.ts"; + const buildPath = "/src/platform/buildModel.ts"; + const [{ useRun }, { useProject }, { useBuildModel }] = await Promise.all([ + import(/* @vite-ignore */ runPath), + import(/* @vite-ignore */ projectPath), + import(/* @vite-ignore */ buildPath), + ]); + useBuildModel.setState({ + root: useProject.getState().project.root, + model: { + maven: null, + gradle: [ + { + dir: "", + projects: [ + { path: ":", name: "demo", dir: "", buildFile: "build.gradle", tasks: [] }, + { path: ":web", name: "web", dir: "web", buildFile: "web/build.gradle", tasks: [] }, + ], + javaVersion: null, + command: "gradle", + syncedAt: null, + stale: false, + syncError: null, + }, + ], + }, + }); + useRun.setState({ + configs: [ + { + id: "layout:tomcat", + name: "Local Tomcat", + kind: "tomcat", + command: "catalina", + args: ["run"], + cwd: null, + env: {}, + detected: false, + isTest: false, + debugAdapter: "java-debug", + params: { tomcatHome: "/tomcat", deployment: "artifact", buildArtifact: "true" }, + }, + ], + editTarget: "layout:tomcat", + loaded: true, + editorOpen: true, + }); + }); + const dialog = page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true }); + const tasks = dialog.getByRole("list", { name: "Before launch tasks", exact: true }); + await expect(tasks.getByRole("button", { name: "1. Build", exact: true })).toBeVisible(); + await tasks.getByRole("button", { name: "Add task" }).click(); + await expect(page.getByRole("menuitem", { name: "Run Maven Goal" })).toHaveCount(0); + await page.getByRole("menuitem", { name: "Run Gradle Task" }).click(); + const taskDialog = page.getByRole("dialog", { name: "Run Gradle Task", exact: true }); + const line = taskDialog.getByRole("textbox", { name: "Command line" }); + await expect(taskDialog.getByRole("button", { name: "OK", exact: true })).toBeDisabled(); + await taskDialog.getByRole("button", { name: "Gradle project" }).click(); + await page.getByRole("option", { name: "web (web)", exact: true }).click(); + await line.fill("classes"); + await taskDialog.getByRole("button", { name: "OK", exact: true }).click(); + await expect(tasks.getByRole("button", { name: "2. Build", exact: true })).toBeVisible(); + await tasks.getByRole("button", { name: "1. Run Gradle Task: classes" }).click(); + await page.getByRole("menuitem", { name: "Edit Task" }).click(); + await expect(taskDialog.getByRole("button", { name: "Gradle project" })).toContainText("web (web)"); + await expect(line).toHaveValue("classes"); + await line.fill("test --info"); + await taskDialog.getByRole("button", { name: "OK", exact: true }).click(); + await expect(tasks.getByRole("button", { name: "1. Run Gradle Task: test --info" })).toBeVisible(); +}); + test("long run target names leave room for configuration names in the sidebar", async ({ workbench: page }) => { const target = "payments-development-shared-staging-runner-west"; await openConfigurations(page, target); diff --git a/src/bindings.ts b/src/bindings.ts index a675294d8f..45ebdba9b1 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -4685,14 +4685,34 @@ export type BackgroundImageSettings = { }; /** A step run before a configuration launches; a failing step aborts the launch. */ -export type BeforeLaunchTask = { +export type BeforeLaunchTask = BeforeLaunchTask_Serialize | BeforeLaunchTask_Deserialize; + +/** A step run before a configuration launches; a failing step aborts the launch. */ +export type BeforeLaunchTask_Deserialize = { /** * `run` (another configuration id) | `build` (project, or `target` = CMake build id) | * `tool` (external tool id) | - * `command` (a shell command line) | `toolWindow` (tool window id). + * `command` (a shell command line) | `toolWindow` (tool window id) | + * `maven` / `gradle` (goals or tasks command line). */ kind: string, target?: string, + /** Build tool project directory, relative to the opened project when possible. */ + projectDir?: string | null, +}; + +/** A step run before a configuration launches; a failing step aborts the launch. */ +export type BeforeLaunchTask_Serialize = { + /** + * `run` (another configuration id) | `build` (project, or `target` = CMake build id) | + * `tool` (external tool id) | + * `command` (a shell command line) | `toolWindow` (tool window id) | + * `maven` / `gradle` (goals or tasks command line). + */ + kind: string, + target?: string, + /** Build tool project directory, relative to the opened project when possible. */ + projectDir?: string | null, }; export type BlameLine = BlameLine_Serialize | BlameLine_Deserialize; @@ -14379,7 +14399,7 @@ export type RunExtras_Deserialize = { stdinFile?: string | null, /** "Save console output to file" (overwritten on each run). */ outputFile?: string | null, - beforeLaunch?: BeforeLaunchTask[], + beforeLaunch?: BeforeLaunchTask_Deserialize[], /** Before launch build for JVM launches; unset keeps the project's default (incremental). */ buildPolicy?: BuildPolicy | null, /** Compound configurations: ids of the configurations started together. */ @@ -14436,7 +14456,7 @@ export type RunExtras_Serialize = { stdinFile?: string | null, /** "Save console output to file" (overwritten on each run). */ outputFile?: string | null, - beforeLaunch?: BeforeLaunchTask[], + beforeLaunch?: BeforeLaunchTask_Serialize[], /** Before launch build for JVM launches; unset keeps the project's default (incremental). */ buildPolicy?: BuildPolicy | null, /** Compound configurations: ids of the configurations started together. */ diff --git a/src/features/build-tools/index.ts b/src/features/build-tools/index.ts index 5b4b26858c..7ab6487988 100644 --- a/src/features/build-tools/index.ts +++ b/src/features/build-tools/index.ts @@ -7,6 +7,7 @@ import { onEditorEvent, registerEditorContribution } from "@/editor/api"; import { executeAction, registerActions } from "@/platform/actions"; import { setContext } from "@/platform/context"; import { isGradleBuildInput } from "@/platform/buildFiles"; +import { registerBuildToolLaunch } from "@/platform/buildModel"; import { onIdeEvent, type BuildModel, type BuildTool } from "@/platform/ipc"; import { useProject } from "@/platform/project"; import { @@ -23,7 +24,7 @@ import { SbtView, sbtExpandableKeys, useSbtTree } from "./SbtView"; import { ExecutePopupHost } from "./ExecutePopup"; import { pomCompletionExtension } from "./pomCompletion"; import { pomNavigationExtension } from "./pomNavigation"; -import { buildToolsRunAnything } from "./runAnything"; +import { beforeLaunchBuildConfig, buildToolsRunAnything } from "./runAnything"; import { versionCatalogExtension } from "./versionCatalog"; import { registerUnlinkedPom } from "./unlinkedPom"; import { @@ -217,6 +218,7 @@ export function activate(): () => void { registerEditorContribution({ id: "build-tools.pomNavigation", extensions: pomNavigationExtension }), registerEditorContribution({ id: "build-tools.pomCompletion", extensions: pomCompletionExtension }), registerRunAnythingProvider(buildToolsRunAnything), + registerBuildToolLaunch(beforeLaunchBuildConfig), registerUnlinkedPom(), registerEditorKind({ kind: ANALYZER_KIND, diff --git a/src/features/build-tools/model.test.ts b/src/features/build-tools/model.test.ts index 3e36f5cfc8..45dd8559f4 100644 --- a/src/features/build-tools/model.test.ts +++ b/src/features/build-tools/model.test.ts @@ -1,5 +1,8 @@ import { describe, expect, it } from "vitest"; import type { GradleModel, MavenModel, MavenPlugin, MavenProject, RunConfig } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; +import { beforeLaunchBuildConfig } from "./runAnything"; +import { useBuild } from "./store"; import { expandableKeys, goalCompletions, @@ -572,6 +575,35 @@ describe("Gradle tree and runs", () => { expect(taskCompletions("wrapper wr", gradle)).toEqual([]); expect(taskCompletions(":app:run ", gradle).map((c) => c.label)).not.toContain(":app:run"); }); + + it("builds before-launch commands for the exact project directory without falling back", () => { + const project = useProject.getState().project; + const { model, root } = useBuild.getState(); + const absoluteModule = { ...maven.projects[2]!, dir: "/p/app", pom: "/p/app/pom.xml" }; + useProject.setState({ project: { root: "/p", name: "Demo", trusted: true, isGit: false, settings: {} as never } }); + useBuild.setState({ + model: { maven: { ...maven, projects: [...maven.projects.slice(0, 2), absoluteModule] }, gradle: [gradle] }, + root: "/p", + }); + try { + expect(beforeLaunchBuildConfig("maven", 'mvn verify -Dname="demo app"', "app")).toMatchObject({ + cwd: "/p/app", + command: "/p/mvnw", + args: ["verify", "-Dname=demo app"], + }); + expect(beforeLaunchBuildConfig("gradle", "./gradlew build", "app")).toMatchObject({ + command: gradle.command, + args: [":app:build"], + }); + for (const tool of ["maven", "gradle"] as const) { + expect(beforeLaunchBuildConfig(tool, "test", "removed")).toBeNull(); + expect(beforeLaunchBuildConfig(tool, " ", ".")).toBeNull(); + } + } finally { + useBuild.setState({ model, root }); + useProject.setState({ project }); + } + }); }); it.each([ diff --git a/src/features/build-tools/runAnything.ts b/src/features/build-tools/runAnything.ts index ce3aade222..280d24c250 100644 --- a/src/features/build-tools/runAnything.ts +++ b/src/features/build-tools/runAnything.ts @@ -4,6 +4,7 @@ * and task completion in the selected project). */ import type { BuildTool } from "@/platform/ipc"; +import { buildToolProjectDirectory } from "@/platform/buildModel"; import { useProject } from "@/platform/project"; import type { RunAnythingItem, RunAnythingProvider } from "@/workbench/contributions"; import { @@ -68,21 +69,40 @@ export function projectKeyAt(tool: BuildTool, cwd: string): string | null { return (best as { key: string } | null)?.key ?? null; } -/** Runs goals / tasks typed for `tool` in a project; false when there is nothing to run. */ -export function executeBuildLine(tool: BuildTool, text: string, projectKey?: string | null): boolean { - const { model, settings } = useBuild.getState(); +function buildLineConfig(tool: BuildTool, text: string, selection: { key?: string | null; directory?: string }) { + const { model, root, settings } = useBuild.getState(); + const directory = selection.directory; + if (directory !== undefined && (!root || root !== useProject.getState().project?.root)) return null; + const matches = (dir: string) => buildToolProjectDirectory(root ?? "", dir) === directory; if (tool === "maven") { const maven = model?.maven; - const project = mavenProjectFor(projectKey); + const project = + directory === undefined ? mavenProjectFor(selection.key) : maven?.projects.find((p) => matches(p.dir)); const goals = parseGoalLine(text); - if (!maven || !project || !("pom" in project) || !goals.length) return false; - runConfig(mavenGoalConfig(project, goals, maven, settings.maven), "run"); - } else { - const selected = gradleProjectFor(projectKey); - const tasks = parseTaskLine(text); - if (!selected || !tasks.length) return false; - runConfig(gradleTaskConfig(selected.build, selected.project, tasks, settings.gradle), "run"); + return maven && project && goals.length ? mavenGoalConfig(project, goals, maven, settings.maven) : null; } + const tasks = parseTaskLine(text); + if (!tasks.length) return null; + if (directory === undefined) { + const selected = gradleProjectFor(selection.key); + return selected ? gradleTaskConfig(selected.build, selected.project, tasks, settings.gradle) : null; + } + for (const build of model?.gradle ?? []) { + const project = build.projects.find((p) => matches(p.dir)); + if (project) return gradleTaskConfig(build, project, tasks, settings.gradle); + } + return null; +} + +export function beforeLaunchBuildConfig(tool: BuildTool, text: string, directory: string) { + return buildLineConfig(tool, text, { directory }); +} + +/** Runs goals / tasks typed for `tool` in a project; false when there is nothing to run. */ +export function executeBuildLine(tool: BuildTool, text: string, projectKey?: string | null): boolean { + const config = buildLineConfig(tool, text, { key: projectKey }); + if (!config) return false; + runConfig(config, "run"); pushHistory(tool, text.replace(COMMANDS[tool], "").trim()); return true; } diff --git a/src/features/run/BeforeLaunchTasks.tsx b/src/features/run/BeforeLaunchTasks.tsx new file mode 100644 index 0000000000..f229425bb2 --- /dev/null +++ b/src/features/run/BeforeLaunchTasks.tsx @@ -0,0 +1,300 @@ +import { useId, useRef, useState, type MouseEvent } from "react"; +import { buildToolProjectDirectory, useBuildModel } from "@/platform/buildModel"; +import { useTx, useTxTemplate } from "@/platform/i18n"; +import type { BeforeLaunchTask, BuildTool, RunConfig } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; +import { useWorkflowSettings } from "@/platform/workflowSettings"; +import { Button, Dialog, Icon, IconButton, Input, Menu, Select, T, type MenuItem, type SelectOption } from "@/ui"; +import { useContributions } from "@/workbench/contributions"; +import { toolWindowTitle } from "@/workbench/toolwindows/title"; +import { TASK_LABELS, taskLabel, type BeforeLaunchKind } from "./beforeLaunch"; +import { configIcon } from "./configs"; +import { TOMCAT_BUILD_TASK } from "./tomcat"; +import { COMPOUND } from "./types"; +import styles from "./Run.module.css"; + +const BUILD_TOOLS = ["maven", "gradle"] as const; +const TASK_ICONS: Readonly>> = { + build: "build-project", + buildModule: "build-project", + buildArtifacts: "build-rebuild", + dotnetBuild: "build-project", + [TOMCAT_BUILD_TASK]: "build-project", + run: "run", + tool: "settings", + command: "terminal", + maven: "file-maven", + gradle: "file-gradle", +}; + +function buildToolKind(kind: string): kind is BuildTool { + return kind === "maven" || kind === "gradle"; +} + +function BuildToolTaskDialog({ + kind, + task, + projects, + onClose, + onSave, +}: { + kind: BuildTool; + task?: BeforeLaunchTask; + projects: SelectOption[]; + onClose: () => void; + onSave: (task: BeforeLaunchTask) => void; +}) { + const tx = useTx(); + const projectId = useId(); + const lineId = useId(); + const [directory, setDirectory] = useState(task?.projectDir ?? projects[0]?.value ?? null); + const [line, setLine] = useState(task?.target ?? ""); + const save = () => { + if (directory && line.trim()) onSave({ kind, target: line.trim(), projectDir: directory }); + }; + return ( + project.value === directory), + onClick: save, + }, + { role: "cancel", label: "Cancel" }, + ]} + > +
+ + setLine(e.target.value)} data-autofocus="" /> +
+
+ ); +} + +export function BeforeLaunchTasks({ + config, + all, + tasks, + onChange, + tomcatBuild, +}: { + config: RunConfig; + all: readonly RunConfig[]; + tasks: readonly BeforeLaunchTask[]; + onChange: (tasks: BeforeLaunchTask[]) => void; + tomcatBuild?: boolean; +}) { + const tx = useTx(); + const txTemplate = useTxTemplate(); + const externalTools = useWorkflowSettings((s) => s.externalTools); + const toolWindows = useContributions((s) => s.toolWindows); + const root = useProject((s) => s.project?.root); + const model = useBuildModel((s) => (s.root === root ? s.model : null)); + const [menu, setMenu] = useState<"add" | { index: number; anchor: HTMLButtonElement } | null>(null); + const [edit, setEdit] = useState<{ kind: BuildTool; index?: number } | null>(null); + const addRef = useRef(null); + const projects: Record = { maven: [], gradle: [] }; + if (root) { + const option = (name: string, dir: string): SelectOption => { + const value = buildToolProjectDirectory(root, dir); + return { value, label: `${name} (${value})`, verbatim: true }; + }; + projects.maven = (model?.maven?.projects ?? []).map((project) => option(project.displayName, project.dir)); + projects.gradle = (model?.gradle ?? []).flatMap((build) => + build.projects.map((project) => option(project.name, project.dir)), + ); + } + + const add = (task: BeforeLaunchTask) => { + if (tasks.at(-1)?.kind === TOMCAT_BUILD_TASK) onChange([...tasks.slice(0, -1), task, tasks.at(-1)!]); + else onChange([...tasks, task]); + }; + const addTask = (kind: BeforeLaunchKind, target = "") => add({ kind, target }); + const replace = (index: number, task: BeforeLaunchTask) => + onChange(tasks.map((other, i) => (i === index ? task : other))); + const runnable = all.filter((c) => c.id !== config.id && c.kind !== COMPOUND); + const taskItems: MenuItem[] = [ + ...BUILD_TOOLS.filter((tool) => projects[tool].length).map((kind) => ({ + label: TASK_LABELS[kind], + icon: TASK_ICONS[kind], + run: () => setEdit({ kind }), + })), + { + label: TASK_LABELS.run, + disabled: !runnable.length, + submenu: runnable.map((c) => ({ + label: c.name, + verbatim: true, + icon: configIcon(c), + run: () => addTask("run", c.id), + })), + }, + ...(tomcatBuild && !tasks.some((task) => task.kind === TOMCAT_BUILD_TASK) + ? [ + { + label: TASK_LABELS[TOMCAT_BUILD_TASK], + icon: TASK_ICONS[TOMCAT_BUILD_TASK], + run: () => addTask(TOMCAT_BUILD_TASK), + }, + ] + : []), + { label: TASK_LABELS.build, icon: TASK_ICONS.build, run: () => addTask("build") }, + { + label: TASK_LABELS.buildModule, + icon: TASK_ICONS.buildModule, + disabled: config.module == null, + run: () => addTask("buildModule", config.module ?? ""), + }, + { label: TASK_LABELS.buildArtifacts, icon: TASK_ICONS.buildArtifacts, run: () => addTask("buildArtifacts") }, + ...(config.kind === "dotnet" + ? [{ label: TASK_LABELS.dotnetBuild, icon: TASK_ICONS.dotnetBuild, run: () => addTask("dotnetBuild") }] + : []), + { + label: TASK_LABELS.tool, + disabled: !externalTools.length, + submenu: externalTools.map((t) => ({ label: t.name, verbatim: true, run: () => addTask("tool", t.id) })), + }, + { label: TASK_LABELS.command, icon: TASK_ICONS.command, run: () => addTask("command") }, + { + label: TASK_LABELS.toolWindow, + disabled: !toolWindows.size, + submenu: [...toolWindows.values()] + .map((w) => ({ + label: toolWindowTitle(w), + verbatim: true, + icon: w.icon, + run: () => addTask("toolWindow", w.id), + })) + .sort((a, b) => a.label.localeCompare(b.label)), + }, + ]; + + const move = (index: number, delta: -1 | 1) => { + const next = [...tasks]; + const to = index + delta; + [next[index], next[to]] = [next[to]!, next[index]!]; + onChange(next); + }; + const actions = menu === "add" ? null : menu; + const actionKind = actions ? tasks[actions.index]?.kind : undefined; + + return ( +
+ {tasks.map((task, index) => { + const label = txTemplate(taskLabel(task, all)); + const target = task.kind === "run" ? all.find((c) => c.id === task.target) : undefined; + const icon = target ? configIcon(target) : TASK_ICONS[task.kind]; + const prefix = ( + <> + {icon && } + {index + 1}. + + ); + const actionProps = { + "aria-haspopup": "menu" as const, + "aria-expanded": actions?.index === index, + onClick: (e: MouseEvent) => setMenu({ index, anchor: e.currentTarget }), + }; + return ( + // oxlint-disable-next-line react/no-array-index-key -- tasks of one kind can repeat; position is the identity +
+ {task.kind === "command" ? ( + <> + {prefix} + replace(index, { ...task, target: e.target.value })} + /> + + + ) : ( + + )} + onChange(tasks.filter((_, i) => i !== index))} + /> +
+ ); + })} +
+ {tasks.length ? ( + setMenu("add")} + /> + ) : ( + + )} +
+ setMenu(null)} /> + {actions && ( + setEdit({ kind: actionKind, index: actions.index }) }] + : []), + { label: "Move Up", icon: "arrow-up", disabled: actions.index === 0, run: () => move(actions.index, -1) }, + { + label: "Move Down", + icon: "arrow-down", + disabled: actions.index === tasks.length - 1, + run: () => move(actions.index, 1), + }, + ]} + onClose={() => setMenu(null)} + /> + )} + {edit && ( + setEdit(null)} + onSave={(task) => { + if (edit.index === undefined) add(task); + else replace(edit.index, task); + setEdit(null); + }} + /> + )} +
+ ); +} diff --git a/src/features/run/ConfigForm.tsx b/src/features/run/ConfigForm.tsx index 9fe61a9533..55f739fafa 100644 --- a/src/features/run/ConfigForm.tsx +++ b/src/features/run/ConfigForm.tsx @@ -6,18 +6,9 @@ import { writeClipboardText } from "@/platform/clipboard"; import { isJvmApplication, parseJavaArgs } from "@/platform/javaLaunch"; import { useRunTargets } from "@/platform/pluginRunTargets"; -import { - useEffect, - useMemo, - useRef, - useState, - type KeyboardEvent, - type MouseEvent, - type ReactNode, - type RefObject, -} from "react"; +import { useEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode, type RefObject } from "react"; import clsx from "clsx"; -import { isTauri, type BeforeLaunchTask, type BuildPolicy, type RunConfig } from "@/platform/ipc"; +import { isTauri, type BuildPolicy, type RunConfig } from "@/platform/ipc"; import { useWorkflowSettings } from "@/platform/workflowSettings"; import { relativePath, useProject } from "@/platform/project"; import { isRemoteWindow } from "@/platform/remote"; @@ -40,8 +31,8 @@ import { type MenuItem, type SelectOption, } from "@/ui"; -import { useContributions, type RunConfigTypeContribution } from "@/workbench/contributions"; -import { TASK_LABELS, taskLabel, type BeforeLaunchKind } from "./beforeLaunch"; +import type { RunConfigTypeContribution } from "@/workbench/contributions"; +import { BeforeLaunchTasks } from "./BeforeLaunchTasks"; import { ExpandableTextarea } from "./ExpandableTextarea"; import { CWD_MACROS } from "./cwdMacros"; import { @@ -63,19 +54,8 @@ import { useBuildModel } from "@/platform/buildModel"; import { COMPOUND, formParams, terminalApplies, withParams } from "./types"; import { frameworkFor } from "./testing"; import { TomcatSettings } from "./TomcatSettings"; -import { toolWindowTitle } from "@/workbench/toolwindows/title"; import styles from "./Run.module.css"; -const TASK_ICONS: Readonly>> = { - build: "build-project", - buildModule: "build-project", - buildArtifacts: "build-rebuild", - dotnetBuild: "build-project", - run: "run", - tool: "settings", - command: "terminal", -}; - /** * Debug adapters with a real launch template (`debugger/launch.ts`, `debugger/java.ts`), * verified against small programs. Others (dart, …) only got @@ -335,9 +315,7 @@ function CwdMacroButton({ export function ConfigForm({ config, all, type, errors, template, onChange, modifyRequest }: ConfigFormProps) { const openByDefault = useWorkflowSettings((s) => s.run.showOnStart); - const externalTools = useWorkflowSettings((s) => s.externalTools); const runTargets = useRunTargets(); - const toolWindows = useContributions((s) => s.toolWindows); const tx = useTx(); const txTemplate = useTxTemplate(); const root = useProject((s) => s.project?.root ?? null); @@ -366,9 +344,7 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi const [envOpen, setEnvOpen] = useState(false); const [modifyOpen, setModifyOpen] = useState(false); const [lastRequest, setLastRequest] = useState(modifyRequest); - const [taskMenu, setTaskMenu] = useState<"add" | { index: number; anchor: HTMLButtonElement } | null>(null); const modifyRef = useRef(null); - const taskRef = useRef(null); if (modifyRequest !== lastRequest) { setLastRequest(modifyRequest); @@ -427,59 +403,6 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi })), ]); - const tasks = config.beforeLaunch ?? []; - const setTasks = (next: BeforeLaunchTask[]) => update({ beforeLaunch: next }); - const addTask = (kind: BeforeLaunchKind, target = "") => setTasks([...tasks, { kind, target }]); - const runnable = all.filter((c) => c.id !== config.id && c.kind !== COMPOUND); - const taskItems: MenuItem[] = [ - { - label: TASK_LABELS.run, - disabled: !runnable.length, - submenu: runnable.map((c) => ({ - label: c.name, - verbatim: true, - icon: configIcon(c), - run: () => addTask("run", c.id), - })), - }, - { label: TASK_LABELS.build, icon: TASK_ICONS.build, run: () => addTask("build") }, - { - label: TASK_LABELS.buildModule, - icon: TASK_ICONS.buildModule, - disabled: config.module == null, - run: () => addTask("buildModule", config.module ?? ""), - }, - { label: TASK_LABELS.buildArtifacts, icon: TASK_ICONS.buildArtifacts, run: () => addTask("buildArtifacts") }, - ...(config.kind === "dotnet" - ? [{ label: TASK_LABELS.dotnetBuild, icon: TASK_ICONS.dotnetBuild, run: () => addTask("dotnetBuild") }] - : []), - { - label: TASK_LABELS.tool, - disabled: !externalTools.length, - submenu: externalTools.map((t) => ({ label: t.name, verbatim: true, run: () => addTask("tool", t.id) })), - }, - { label: TASK_LABELS.command, icon: TASK_ICONS.command, run: () => addTask("command") }, - { - label: TASK_LABELS.toolWindow, - submenu: [...toolWindows.values()] - .map((w) => ({ - label: toolWindowTitle(w), - verbatim: true, - icon: w.icon, - run: () => addTask("toolWindow", w.id), - })) - .sort((a, b) => a.label.localeCompare(b.label)), - }, - ]; - const moveTask = (i: number, d: -1 | 1) => { - const j = i + d; - if (j < 0 || j >= tasks.length) return; - const next = [...tasks]; - [next[i], next[j]] = [next[j]!, next[i]!]; - setTasks(next); - }; - const taskActions = taskMenu === "add" ? null : taskMenu; - const adapterOptions: SelectOption[] = [ { value: "", label: "None" }, ...ADAPTERS.map((a) => ({ value: a.id, label: tx(a.label) })), @@ -543,7 +466,7 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi )} {config.kind === "tomcat" ? ( - + ) : (
{!noProcess && ( @@ -805,105 +728,12 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi {isShown("beforeLaunch") && ( -
- {tasks.map((t, i) => { - const label = txTemplate(taskLabel(t, all)); - const target = t.kind === "run" ? all.find((c) => c.id === t.target) : undefined; - const icon = target ? configIcon(target) : TASK_ICONS[t.kind]; - const prefix = ( - <> - {icon && } - {i + 1}. - - ); - const actions = { - "aria-haspopup": "menu" as const, - "aria-expanded": taskActions?.index === i, - onClick: (e: MouseEvent) => setTaskMenu({ index: i, anchor: e.currentTarget }), - }; - return ( - // oxlint-disable-next-line react/no-array-index-key -- tasks of one kind can repeat; position is the identity -
- {t.kind === "command" ? ( - <> - {prefix} - - setTasks(tasks.map((x, j) => (j === i ? { ...x, target: e.target.value } : x))) - } - /> - - - ) : ( - - )} - setTasks(tasks.filter((_, j) => j !== i))} - /> -
- ); - })} -
- {tasks.length ? ( - setTaskMenu("add")} - /> - ) : ( - - )} -
- setTaskMenu(null)} /> - {taskActions && ( - moveTask(taskActions.index, -1), - }, - { - label: "Move Down", - icon: "arrow-down", - disabled: taskActions.index === tasks.length - 1, - run: () => moveTask(taskActions.index, 1), - }, - ]} - onClose={() => setTaskMenu(null)} - /> - )} -
+ update({ beforeLaunch })} + />
)} diff --git a/src/features/run/Run.module.css b/src/features/run/Run.module.css index 5bbcb46220..da4cd4ea43 100644 --- a/src/features/run/Run.module.css +++ b/src/features/run/Run.module.css @@ -988,6 +988,11 @@ align-items: center; gap: var(--space-1); } +.taskDialogFields { + display: grid; + gap: var(--space-2); + padding: var(--space-4); +} .taskTag { display: inline-flex; align-items: center; @@ -1627,9 +1632,6 @@ .tomcatEnvPanel { min-height: 130px; } -.tomcatBoxSmall { - min-height: 76px; -} .tomcatBoxEmpty { flex: 1; display: flex; diff --git a/src/features/run/TomcatSettings.tsx b/src/features/run/TomcatSettings.tsx index f021e78b05..a61ed175ed 100644 --- a/src/features/run/TomcatSettings.tsx +++ b/src/features/run/TomcatSettings.tsx @@ -9,9 +9,18 @@ import { useWorkflowSettings } from "@/platform/workflowSettings"; import { isRemoteWindow } from "@/platform/remote"; import { Button, Checkbox, Dialog, Icon, IconButton, Input, Menu, Select, Tabs, T, type MenuItem } from "@/ui"; import { useTx } from "@/platform/i18n"; -import { tomcatBrowserUrl, tomcatDeployments, withTomcatDeployments, type TomcatDeployment } from "./tomcat"; +import { BeforeLaunchTasks } from "./BeforeLaunchTasks"; +import { + TOMCAT_BUILD_TASK, + tomcatBrowserUrl, + tomcatDeployments, + withTomcatDeployments, + type TomcatDeployment, +} from "./tomcat"; import styles from "./Run.module.css"; +const NO_CONFIGS: readonly RunConfig[] = []; + type TomcatTab = "server" | "deployment" | "logs" | "startup"; type StartupRunnerId = "run" | "debug"; @@ -80,7 +89,15 @@ async function pickLocalPath(directory: boolean, defaultPath?: string): Promise< } /** Local installation validation, server profiles, and WAR artifact discovery. */ -export function TomcatSettings({ config, onChange }: { config: RunConfig; onChange: (config: RunConfig) => void }) { +export function TomcatSettings({ + config, + all = NO_CONFIGS, + onChange, +}: { + config: RunConfig; + all?: readonly RunConfig[]; + onChange: (config: RunConfig) => void; +}) { const tx = useTx(); const windows = usePlatform((state) => state.os === "windows"); const openByDefault = useWorkflowSettings((settings) => settings.run.showOnStart); @@ -270,6 +287,11 @@ export function TomcatSettings({ config, onChange }: { config: RunConfig; onChan const deploymentLabel = (d: TomcatDeployment) => d.deployment === "artifact" ? `${d.artifactName || d.artifact}:war exploded` : (d.deploymentPath ?? ""); const buildsArtifacts = noArtifactConfigured || deployments.some((d) => d.deployment === "artifact"); + const tasks = config.beforeLaunch ?? []; + const beforeLaunchTasks = + buildsArtifacts && config.params?.buildArtifact === "true" && !tasks.some((task) => task.kind === TOMCAT_BUILD_TASK) + ? [...tasks, { kind: TOMCAT_BUILD_TASK, target: "" }] + : tasks; const useDefaultStartup = config.params?.useDefaultStartup !== "false"; const useDefaultShutdown = config.params?.useDefaultShutdown !== "false"; @@ -1047,37 +1069,24 @@ export function TomcatSettings({ config, onChange }: { config: RunConfig; onChan
{beforeLaunchOpen && ( <> - {buildsArtifacts && ( -
-
- setParams({ buildArtifact: "true" })} - /> - setParams({ buildArtifact: "false" })} - /> -
-
- {config.params?.buildArtifact === "true" && ( -
- - - Build - -
- )} -
-
- )} + { + const current = latest.current.config; + const hasBuild = beforeLaunch.some((task) => task.kind === TOMCAT_BUILD_TASK); + publish({ + ...current, + beforeLaunch, + params: + buildsArtifacts || beforeLaunchTasks.some((task) => task.kind === TOMCAT_BUILD_TASK) + ? { ...current.params, buildArtifact: String(hasBuild) } + : current.params, + }); + }} + />
{ + const ipc = await original(); + return { + ...ipc, + commands: { + ...ipc.commands, + runTomcatHome: vi.fn(async () => ({ status: "ok", data: { version: "Tomcat", libraries: [] } })), + runTomcatBuild: vi.fn(async () => ({ status: "ok", data: null })), + }, + }; +}); +vi.mock("./store", async (original) => ({ + ...(await original()), + startRun: vi.fn(), +})); + +const config: RunConfig = { + id: "app", + name: "Application", + kind: "shell", + command: "start", + args: [], + env: {}, + cwd: null, + detected: false, + isTest: false, + debugAdapter: null, +}; + +function buildProvider(tool: BuildTool) { + return vi.fn(() => ({ ...config, id: tool, kind: tool, command: tool, cwd: "web" })); +} + +const start = vi.mocked(startRun); +const build = vi.mocked(commands.runTomcatBuild); +afterEach(() => { + setBeforeLaunchRunner(null); + start.mockReset(); + build.mockClear(); +}); + +describe("before-launch build tool tasks", () => { + it.each(["maven", "gradle"] as const)("waits for %s to exit before starting the next task", async (tool) => { + const provider = buildProvider(tool); + const dispose = registerBuildToolLaunch(provider); + try { + start.mockResolvedValue({ status: "running" } as never); + const done = runBeforeLaunch( + { + ...config, + beforeLaunch: [ + { kind: tool, target: "clean test", projectDir: "web" }, + { kind: "command", target: "echo next" }, + ], + }, + [config.id], + false, + ); + expect(provider).toHaveBeenCalledWith(tool, "clean test", "web"); + expect(start).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ kind: tool, command: tool, cwd: "web", id: `${tool}:before:app` }), + undefined, + undefined, + expect.objectContaining({ chain: [config.id], show: false }), + ); + start.mock.calls[0]![3]!.onExit!(0, false); + await vi.waitFor(() => expect(start).toHaveBeenCalledTimes(2)); + expect(start.mock.calls[1]![0].command).toBe("echo next"); + start.mock.calls[1]![3]!.onExit!(0, false); + await expect(done).resolves.toBe(true); + } finally { + dispose(); + } + }); + + it.each(["maven", "gradle"] as const)("aborts the launch after a non-zero exit from %s", async (tool) => { + const dispose = registerBuildToolLaunch(buildProvider(tool)); + try { + start.mockResolvedValue({ status: "running" } as never); + const done = runBeforeLaunch( + { + ...config, + beforeLaunch: [ + { kind: tool, target: "test", projectDir: "web" }, + { kind: "command", target: "echo next" }, + ], + }, + [config.id], + ); + start.mock.calls[0]![3]!.onExit!(1, false); + await expect(done).resolves.toBe(false); + expect(start).toHaveBeenCalledTimes(1); + } finally { + dispose(); + } + }); + + it("aborts when the selected build project is no longer available", async () => { + const dispose = registerBuildToolLaunch(() => null); + try { + await expect( + runBeforeLaunch({ ...config, beforeLaunch: [{ kind: "maven", target: "verify", projectDir: "removed" }] }, []), + ).resolves.toBe(false); + expect(start).not.toHaveBeenCalled(); + } finally { + dispose(); + } + }); +}); + +describe("Tomcat artifact build", () => { + it.each([false, true])("runs other tasks before the artifact build, only once (ordered: %s)", async (ordered) => { + setBeforeLaunchRunner(runBeforeLaunch); + start.mockResolvedValue({ status: "running" } as never); + const tomcat: RunConfig = { + ...config, + kind: "tomcat", + params: { deployment: "artifact", artifact: "maven:app/pom.xml", buildArtifact: "true" }, + beforeLaunch: [{ kind: "command", target: "echo prepare" }, ...(ordered ? [{ kind: TOMCAT_BUILD_TASK }] : [])], + }; + const ready = prepareLaunch(tomcat); + expect(build).not.toHaveBeenCalled(); + start.mock.calls[0]![3]!.onExit!(0, false); + await expect(ready).resolves.toBe(true); + expect(build).toHaveBeenCalledTimes(ordered ? 1 : 0); + await tomcatType.prepareLaunch!(tomcat); + expect(build).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/features/run/beforeLaunch.ts b/src/features/run/beforeLaunch.ts index 10569ec259..744528ec12 100644 --- a/src/features/run/beforeLaunch.ts +++ b/src/features/run/beforeLaunch.ts @@ -3,6 +3,7 @@ * configuration starts; the first failure aborts the launch. */ import { useProject } from "@/platform/project"; +import { buildToolLaunchConfig } from "@/platform/buildModel"; import { buildCMake, isCMakeBuild } from "./cmake"; import { dotnetProjectFile } from "./dotnetTypes"; import { useBuildPresentation } from "@/platform/projectPresentation"; @@ -16,6 +17,7 @@ import { externalToolConfig } from "./externalTools"; import { toolWindowTitle } from "@/workbench/toolwindows/title"; import { runConfigurationToCompletion } from "./configurationChecks"; import { startRun, useRun } from "./store"; +import { buildTomcatArtifact, TOMCAT_BUILD_TASK } from "./tomcat"; export const BUILD_ACTION = "build.buildProject"; @@ -24,6 +26,9 @@ export type BeforeLaunchKind = | "build" | "buildModule" | "buildArtifacts" + | typeof TOMCAT_BUILD_TASK + | "maven" + | "gradle" | "tool" | "command" | "toolWindow" @@ -34,6 +39,9 @@ export const TASK_LABELS: Record = { build: "Build Project", buildModule: "Build Module", buildArtifacts: "Build Artifacts", + [TOMCAT_BUILD_TASK]: "Build", + maven: "Run Maven Goal", + gradle: "Run Gradle Task", dotnetBuild: "Build .NET project", tool: "Run External Tool", command: "Run Shell Command", @@ -52,6 +60,11 @@ export function taskLabel(task: BeforeLaunchTask, configs: readonly RunConfig[] return target ? `Build Module '${target}'` : "Build Module"; case "buildArtifacts": return "Build Artifacts"; + case TOMCAT_BUILD_TASK: + return TASK_LABELS[TOMCAT_BUILD_TASK]; + case "maven": + case "gradle": + return target ? `${tx(TASK_LABELS[task.kind])}: ${target}` : tx(TASK_LABELS[task.kind]); case "dotnetBuild": return "Build .NET project"; case "tool": @@ -122,6 +135,17 @@ async function runTask( } case "buildArtifacts": return buildTask("build.buildArtifacts", { activate: false, wait: true }); + case TOMCAT_BUILD_TASK: + await buildTomcatArtifact(config); + return null; + case "maven": + case "gradle": { + const run = task.projectDir ? buildToolLaunchConfig(task.kind, target, task.projectDir) : null; + if (!run) return tx("The build tool project is unavailable or the command line is empty"); + return (await runToEnd({ ...run, id: `${run.id}:before:${config.id}` }, chain, show, signal)) + ? null + : tx`Build tool task '${target}' failed`; + } case "run": { if (chain.includes(target)) return "The before launch tasks run in a cycle"; const other = useRun.getState().configs.find((c) => c.id === target); diff --git a/src/features/run/tomcat.test.tsx b/src/features/run/tomcat.test.tsx index 420579e680..96012d0c72 100644 --- a/src/features/run/tomcat.test.tsx +++ b/src/features/run/tomcat.test.tsx @@ -1,7 +1,9 @@ import { describe, expect, it, vi, afterEach } from "vitest"; +import { useState } from "react"; import { render, screen, waitFor, cleanup, fireEvent, within } from "@testing-library/react"; import { newConfigOfType, missingParams } from "./types"; import { + TOMCAT_BUILD_TASK, syncTomcatOutputs, tomcatBrowserUrl, tomcatDeploymentConfigs, @@ -66,6 +68,59 @@ vi.mock("@/platform/ipc", async (importOriginal) => ({ afterEach(cleanup); describe("Tomcat Local", () => { + it("uses the shared list and keeps the default artifact build removable and reorderable", async () => { + const initial = newConfigOfType(tomcatType, []); + initial.params = { ...initial.params, tomcatHome: "/tomcat" }; + const change = vi.fn(); + function Form() { + const [config, setConfig] = useState(initial); + return ( + { + change(next); + setConfig(next); + }} + /> + ); + } + render(
); + await screen.findByText(/Apache Tomcat\/10\.1\.61/); + const list = within(screen.getByRole("list", { name: "Before launch tasks" })); + expect(list.getByRole("button", { name: /^1\.\s?Build$/ })).toBeTruthy(); + fireEvent.click(list.getByRole("button", { name: "Add task" })); + expect(screen.queryByRole("menuitem", { name: "Run Maven Goal" })).toBeNull(); + expect(screen.queryByRole("menuitem", { name: "Run Gradle Task" })).toBeNull(); + fireEvent.click(screen.getByRole("menuitem", { name: "Run Shell Command" })); + fireEvent.change(list.getByRole("textbox", { name: "Before launch command 1" }), { + target: { value: "make prep" }, + }); + expect(change).toHaveBeenLastCalledWith( + expect.objectContaining({ + beforeLaunch: [ + { kind: "command", target: "make prep" }, + { kind: TOMCAT_BUILD_TASK, target: "" }, + ], + params: expect.objectContaining({ buildArtifact: "true" }), + }), + ); + fireEvent.click(list.getByRole("button", { name: /^2\.\s?Build$/ })); + fireEvent.click(screen.getByRole("menuitem", { name: "Move Up" })); + const build = list.getByRole("button", { name: /^1\.\s?Build$/ }); + fireEvent.click( + within(build.closest('[role="listitem"]') as HTMLElement).getByRole("button", { name: "Remove Task" }), + ); + expect(change).toHaveBeenLastCalledWith( + expect.objectContaining({ + beforeLaunch: [{ kind: "command", target: "make prep" }], + params: expect.objectContaining({ buildArtifact: "false" }), + }), + ); + fireEvent.click(list.getByRole("button", { name: "Add task" })); + fireEvent.click(screen.getByRole("menuitem", { name: "Build" })); + expect(list.getByRole("button", { name: /^2\.\s?Build$/ })).toBeTruthy(); + expect(screen.getByRole("checkbox", { name: "Focus tool window" })).toBeTruthy(); + }); it("offers a Tomcat Server configuration grouped under Servers with build and browser defaults", () => { const config = newConfigOfType(tomcatType, []); expect(config.params).toMatchObject({ diff --git a/src/features/run/tomcat.ts b/src/features/run/tomcat.ts index 10e59c6f7d..304e398b75 100644 --- a/src/features/run/tomcat.ts +++ b/src/features/run/tomcat.ts @@ -11,6 +11,8 @@ const validatePort = (value: string) => const validateOptionalPort = (value: string) => (!value.trim() ? null : validatePort(value.trim())); +export const TOMCAT_BUILD_TASK = "tomcatBuild"; + export const tomcatType: RunConfigTypeContribution = { id: "tomcat", group: "Servers", @@ -141,7 +143,11 @@ export const tomcatType: RunConfigTypeContribution = { async prepareLaunch(config) { if (config.target) throw new Error("Tomcat Local requires the local machine"); await call(commands.runTomcatHome(config.params?.tomcatHome ?? "")); - if (config.params?.buildArtifact === "true") await buildTomcatArtifact(config); + if ( + config.params?.buildArtifact === "true" && + !config.beforeLaunch?.some((task) => task.kind === TOMCAT_BUILD_TASK) + ) + await buildTomcatArtifact(config); return config; }, }; diff --git a/src/platform/buildModel.ts b/src/platform/buildModel.ts index 2e2d992b50..de01a5701a 100644 --- a/src/platform/buildModel.ts +++ b/src/platform/buildModel.ts @@ -3,7 +3,7 @@ * features that follow the build (run, Project view) without loading it again. */ import { create } from "zustand"; -import type { BuildModel } from "./ipc"; +import type { BuildModel, BuildTool, RunConfig } from "./ipc"; export interface SharedBuildModel { /** Project the model belongs to. */ @@ -14,3 +14,22 @@ export interface SharedBuildModel { } export const useBuildModel = create(() => ({ root: null, model: null, gradleOffline: false })); + +export function buildToolProjectDirectory(root: string, dir: string): string { + const prefix = root.endsWith("/") ? root : `${root}/`; + return (dir === root || dir.startsWith(prefix) ? dir.slice(prefix.length) : dir) || "."; +} + +type BuildToolLaunch = (tool: BuildTool, line: string, directory: string) => RunConfig | null; +let buildToolLaunch: BuildToolLaunch | undefined; + +export function registerBuildToolLaunch(provider: BuildToolLaunch): () => void { + buildToolLaunch = provider; + return () => { + if (buildToolLaunch === provider) buildToolLaunch = undefined; + }; +} + +export function buildToolLaunchConfig(tool: BuildTool, line: string, directory: string): RunConfig | null { + return buildToolLaunch?.(tool, line, directory) ?? null; +} diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index d22e03b192..ffad8f409d 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -80,6 +80,13 @@ "Select Methods to Override": "Select Methods to Override", "No methods to override": "No methods to override", "Task Actions": "Task Actions", + "Edit Task": "Edit Task", + "Run Maven Goal": "Run Maven Goal", + "Run Gradle Task": "Run Gradle Task", + "Maven project (working directory)": "Maven project (working directory)", + "Gradle project": "Gradle project", + "The build tool project is unavailable or the command line is empty": "The build tool project is unavailable or the command line is empty", + "Build tool task '{target}' failed": "Build tool task '{target}' failed", "Search commits": "Search commits", "Amend commit failed": "Amend commit failed", "Amending this commit would cause a conflict. You can keep the prepared changes as a separate amend commit.": "Amending this commit would cause a conflict. You can keep the prepared changes as a separate amend commit.", diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index 55ef6cb3ea..cf92cdc622 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -3932,6 +3932,13 @@ "Before Launch": "啟動前", "Before launch": "啟動前", "Before launch tasks": "啟動前任務", + "Task Actions": "任務操作", + "Edit Task": "編輯任務", + "Run Maven Goal": "執行 Maven 目標", + "Maven project (working directory)": "Maven 專案(工作目錄)", + "Gradle project": "Gradle 專案", + "The build tool project is unavailable or the command line is empty": "建置工具專案無法使用或命令列為空白", + "Build tool task '{target}' failed": "建置工具任務「{target}」失敗", "Store as project file": "儲存為專案檔案", "Modify options": "修改選項", "Rebase {head}": "重定基底 {head}", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 21a86bd979..33480e5ca9 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -4662,6 +4662,12 @@ "Shell command, e.g. make generate": "Shell 命令,例如 make generate", "Remove Task": "移除任务", "Task Actions": "任务操作", + "Edit Task": "编辑任务", + "Run Maven Goal": "运行 Maven 目标", + "Maven project (working directory)": "Maven 项目(工作目录)", + "Gradle project": "Gradle 项目", + "The build tool project is unavailable or the command line is empty": "构建工具项目不可用或命令行为空", + "Build tool task '{target}' failed": "构建工具任务“{target}”失败", "Add task": "添加任务", "Add configuration…": "添加配置…", "Add configuration": "添加配置",