feat(run): Tomcat before launch task list with Maven goal and Gradle task steps (#7294)

The Tomcat Server form's Before launch section only toggled one Build item. It now uses the same task list as other run configurations (BeforeLaunchTasks), with Tomcat's artifact Build as a removable, reorderable entry that existing configurations keep. Before launch also gains Run Maven Goal and Run Gradle Task steps that run through the build tools' existing execution and abort the launch on failure; BeforeLaunchTask gets an optional projectDir.

Fixes #7200
Цей коміт міститься в:
l0ng-ai authored and GitHub committed 2026-12-02 04:19:59 +08:00
1 джерело aa596f1125
коміт dc74595bca
24 files changed
+816 -245

No files matched your search

+24 -4
Переглянути файл
@@ -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. */
+3 -1
Переглянути файл
@@ -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,
+32
Переглянути файл
@@ -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([
+31 -11
Переглянути файл
@@ -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;
}
+300
Переглянути файл
@@ -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<Partial<Record<string, string>>> = {
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 (
<Dialog
open
title={TASK_LABELS[kind]}
width={460}
onClose={onClose}
buttons={[
{
role: "default",
label: "OK",
disabled: !line.trim() || !projects.some((project) => project.value === directory),
onClick: save,
},
{ role: "cancel", label: "Cancel" },
]}
>
<div className={styles.taskDialogFields}>
<label htmlFor={projectId}>
{kind === "maven" ? tx("Maven project (working directory)") : tx("Gradle project")}
</label>
<Select id={projectId} value={directory} options={projects} onChange={setDirectory} searchable />
<label htmlFor={lineId}>{tx("Command line")}</label>
<Input id={lineId} mono value={line} onChange={(e) => setLine(e.target.value)} data-autofocus="" />
</div>
</Dialog>
);
}
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<HTMLButtonElement>(null);
const projects: Record<BuildTool, SelectOption[]> = { 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 (
<div className={styles.beforeLaunchTasks} role="list" aria-label={tx("Before launch tasks")}>
{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 && <Icon name={icon} size={14} />}
<span className={styles.taskOrder}>{index + 1}.</span>
</>
);
const actionProps = {
"aria-haspopup": "menu" as const,
"aria-expanded": actions?.index === index,
onClick: (e: MouseEvent<HTMLButtonElement>) => 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
<div key={index} role="listitem" className={styles.taskTag}>
{task.kind === "command" ? (
<>
{prefix}
<Input
mono
className={styles.taskCommand}
aria-label={txTemplate(`Before launch command ${index + 1}`)}
value={task.target ?? ""}
placeholder="Shell command, e.g. make generate"
onChange={(e) => replace(index, { ...task, target: e.target.value })}
/>
<IconButton icon="more" title="Task Actions" size="small" {...actionProps} />
</>
) : (
<button type="button" className={styles.taskName} title={label} {...actionProps}>
{prefix}
<span className={styles.taskLabel}>{label}</span>
</button>
)}
<IconButton
icon="close"
size="small"
iconSize={12}
title="Remove Task"
onClick={() => onChange(tasks.filter((_, i) => i !== index))}
/>
</div>
);
})}
<div role="listitem">
{tasks.length ? (
<IconButton
ref={addRef}
title="Add task"
icon="plus"
size="small"
aria-haspopup="menu"
aria-expanded={menu === "add"}
onClick={() => setMenu("add")}
/>
) : (
<Button
ref={addRef}
size="small"
variant="ghost"
icon="plus"
aria-haspopup="menu"
aria-expanded={menu === "add"}
onClick={() => setMenu("add")}
>
<T>Add task</T>
</Button>
)}
</div>
<Menu open={menu === "add"} anchor={addRef} items={taskItems} onClose={() => setMenu(null)} />
{actions && (
<Menu
open
anchor={actions.anchor}
aria-label={tx("Task Actions")}
items={[
...(actionKind && buildToolKind(actionKind)
? [{ label: "Edit Task", icon: "edit", run: () => 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 && (
<BuildToolTaskDialog
kind={edit.kind}
task={edit.index === undefined ? undefined : tasks[edit.index]}
projects={projects[edit.kind]}
onClose={() => setEdit(null)}
onSave={(task) => {
if (edit.index === undefined) add(task);
else replace(edit.index, task);
setEdit(null);
}}
/>
)}
</div>
);
}
+11 -181
Переглянути файл
@@ -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<Partial<Record<string, string>>> = {
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<HTMLButtonElement>(null);
const taskRef = useRef<HTMLButtonElement>(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
</div>
)}
{config.kind === "tomcat" ? (
<TomcatSettings config={config} onChange={onChange} />
<TomcatSettings config={config} all={all} onChange={onChange} />
) : (
<div className={styles.formSettings}>
{!noProcess && (
@@ -805,105 +728,12 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi
{isShown("beforeLaunch") && (
<Field label="Before launch" error={errors.beforeLaunch} top>
<div className={styles.beforeLaunchTasks} role="list" aria-label={tx("Before launch tasks")}>
{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 && <Icon name={icon} size={14} />}
<span className={styles.taskOrder}>{i + 1}.</span>
</>
);
const actions = {
"aria-haspopup": "menu" as const,
"aria-expanded": taskActions?.index === i,
onClick: (e: MouseEvent<HTMLButtonElement>) => 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
<div key={i} role="listitem" className={styles.taskTag}>
{t.kind === "command" ? (
<>
{prefix}
<Input
mono
className={styles.taskCommand}
aria-label={txTemplate(`Before launch command ${i + 1}`)}
value={t.target ?? ""}
placeholder="Shell command, e.g. make generate"
onChange={(e) =>
setTasks(tasks.map((x, j) => (j === i ? { ...x, target: e.target.value } : x)))
}
/>
<IconButton icon="more" title="Task Actions" size="small" {...actions} />
</>
) : (
<button type="button" className={styles.taskName} title={label} {...actions}>
{prefix}
<span className={styles.taskLabel}>{label}</span>
</button>
)}
<IconButton
icon="close"
size="small"
iconSize={12}
title="Remove Task"
onClick={() => setTasks(tasks.filter((_, j) => j !== i))}
/>
</div>
);
})}
<div role="listitem">
{tasks.length ? (
<IconButton
ref={taskRef}
title="Add task"
icon="plus"
size="small"
aria-haspopup="menu"
aria-expanded={taskMenu === "add"}
onClick={() => setTaskMenu("add")}
/>
) : (
<Button
ref={taskRef}
size="small"
variant="ghost"
icon="plus"
aria-haspopup="menu"
aria-expanded={taskMenu === "add"}
onClick={() => setTaskMenu("add")}
>
<T>Add task</T>
</Button>
)}
</div>
<Menu open={taskMenu === "add"} anchor={taskRef} items={taskItems} onClose={() => setTaskMenu(null)} />
{taskActions && (
<Menu
open
anchor={taskActions.anchor}
aria-label={tx("Task Actions")}
items={[
{
label: "Move Up",
icon: "arrow-up",
disabled: taskActions.index === 0,
run: () => moveTask(taskActions.index, -1),
},
{
label: "Move Down",
icon: "arrow-down",
disabled: taskActions.index === tasks.length - 1,
run: () => moveTask(taskActions.index, 1),
},
]}
onClose={() => setTaskMenu(null)}
/>
)}
</div>
<BeforeLaunchTasks
config={config}
all={all}
tasks={config.beforeLaunch ?? []}
onChange={(beforeLaunch) => update({ beforeLaunch })}
/>
</Field>
)}
+5 -3
Переглянути файл
@@ -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;
+42 -33
Переглянути файл
@@ -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
</div>
{beforeLaunchOpen && (
<>
{buildsArtifacts && (
<div className={clsx(styles.tomcatBoxPanel, styles.tomcatBoxSmall)}>
<div className={styles.appServersToolbar} role="toolbar" aria-label={tx("Before launch tasks")}>
<IconButton
icon="plus"
size="small"
iconSize={14}
title="Add"
onClick={() => setParams({ buildArtifact: "true" })}
/>
<IconButton
icon="minus"
size="small"
iconSize={14}
title="Remove"
disabled={config.params?.buildArtifact !== "true"}
onClick={() => setParams({ buildArtifact: "false" })}
/>
</div>
<div className={styles.appServersList}>
{config.params?.buildArtifact === "true" && (
<div className={styles.editItem}>
<Icon name="build-project" size={13} className={styles.chooserIcon} />
<span className={styles.chooserName}>
<T>Build</T>
</span>
</div>
)}
</div>
</div>
)}
<BeforeLaunchTasks
config={config}
all={all}
tasks={beforeLaunchTasks}
tomcatBuild={buildsArtifacts}
onChange={(beforeLaunch) => {
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,
});
}}
/>
<div className={styles.tomcatBeforeLaunchFooter}>
<Checkbox
checked={config.openToolWindow ?? openByDefault}
+136
Переглянути файл
@@ -0,0 +1,136 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { registerBuildToolLaunch } from "@/platform/buildModel";
import { commands, type BuildTool, type RunConfig } from "@/platform/ipc";
import { runBeforeLaunch } from "./beforeLaunch";
import { prepareLaunch, setBeforeLaunchRunner, startRun } from "./store";
import { TOMCAT_BUILD_TASK, tomcatType } from "./tomcat";
vi.mock("@/platform/ipc", async (original) => {
const ipc = await original<typeof import("@/platform/ipc")>();
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<typeof import("./store")>()),
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);
});
});
+24
Переглянути файл
@@ -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<BeforeLaunchKind, string> = {
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);
+55
Переглянути файл
@@ -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 (
<TomcatSettings
config={config}
onChange={(next) => {
change(next);
setConfig(next);
}}
/>
);
}
render(<Form />);
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({
+7 -1
Переглянути файл
@@ -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;
},
};
+20 -1
Переглянути файл
@@ -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<SharedBuildModel>(() => ({ 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;
}
+7
Переглянути файл
@@ -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.",
+7
Переглянути файл
@@ -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}",
+6
Переглянути файл
@@ -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": "添加配置",