Файли
openidea/src/features/run/applicationUpdate.ts
T
l0ng-ai 536f85b9df feat(java): build Maven and Gradle modules with a resident, incremental javac build service (#5854)
Implements #4078 steps 2–4: an IDE-owned Java build service that compiles Maven and Gradle modules with a resident javac, class by class, for launches and the Build menu.

## What changes

- **Model.** The build tool records each project's source roots, compile/runtime classpaths, resources and the compiler configuration it actually uses (release/source/target, encoding, `-parameters`, debug level, `proc`, compiler args, includes/excludes, resolved annotation processor path):
  - Maven: a core extension (`java/java-build`, `BuildModel`) during `process-resources resources:testResources`.
  - Gradle: an init script (`gradle-build.init.gradle`) with an `openideaBuildModel` task that runs source generators and `processResources`.

  The prepare run happens only when what the model is built from changes: build scripts, settings, toolchains, the launcher, the JDK, generator inputs (`src/*/proto`, `antlr4`…), or a generated root that is gone.
- **Outputs.** Every project writes to `<cache>/java-build/<build>/out/<group>.<name>/classes|test-classes`, and dependencies on other projects of the build resolve to those folders. jdtls and a terminal `mvn`/`gradle` never write the classes a launch runs.
- **Compile.** A resident javac process per JDK (and `.mvn/jvm.config`) compiles source sets in dependency order, without `-am` or the full lifecycle.
- **Class-level incremental compilation.** Each source set records, per class: its source, supertypes, the classes its constant pool references, and fingerprints of its API and compile-time constants (read from the class files, private and synthetic members excluded).
  - A build compiles the changed sources.
  - It then compiles, round after round, the sources of classes that reference a class whose API changed (or one of its subclasses), and the sources a new class could shadow.
  - Downstream sets follow an API change log.
  - A changed constant recompiles the set and everything compiled against it.
  - Sources a failed compile left behind stay dirty.
  - Sets whose annotation processors aggregate compile from scratch.
- **Build menu.**
  - Build Project and Build Module compile with the service.
  - Recompile compiles the file with the service and publishes javac's diagnostics.
- **Events.** Steps, positioned javac diagnostics and progress stream on the `BuildEvent` channel from #5801.
- **When it applies.**
  - Maven modules, unless Settings › Maven › *Delegate IDE build/run actions to Maven* is on.
  - Gradle modules when Settings › Gradle › *Build and run using* is the IDE.
  - Debug launches keep jdtls' build, because java-debug's HotSwap reloads what jdtls compiles.
  - jdtls keeps autobuild on: cross-module diagnostics depend on it (verified with a real jdtls, see the ignored test below).
- **Fallback.** These go to the build tool's own build:
  - modules that need it: another compiler (Kotlin, Groovy, AspectJ…), a non-javac compiler id, multi-release output, Java modules, unresolvable dependencies or processor paths, composite Gradle builds;
  - a failed prepare run.

The javac server and the Maven extension are built reproducibly with `--release 8` against Maven 3.9.11 (`java/java-build/build.py`, dependencies pinned) and embedded by `ide-sdk`.

## Tests

- `ide-build` `jbuild::tests`, run against a real Maven/Gradle and JDK (skipped when missing):
  - first build, no-op build, only changed files recompile;
  - API changes reach dependents, including through subclasses and across modules;
  - constant changes recompile dependents;
  - resource changes run only the resources step;
  - deleted sources, compile errors with positions, the test source set;
  - Recompile and Build Project;
  - Gradle projects;
  - fallback for Gradle projects with other compilers;
  - plus class-file parsing, the API change log, javac options and Ant patterns.
- `ide-host` `tests/java_build.rs`: Maven and Gradle launches through `java_resolve_launch` compile with javac into the IDE's outputs, and Build Project reports javac's errors.
- `tests/workspaces.rs`: a Maven that writes no build model falls back to `mvn -pl app -am`.
- `ide-lsp` (ignored, needs jdtls): jdtls reports cross-module errors in open and closed files with autobuild on.
2026-11-25 20:01:26 +08:00

206 рядки
8.7 KiB
TypeScript

import { tx } from "@/platform/i18n";
import { create } from "zustand";
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
import { executeAction, getAction } from "@/platform/actions";
import { call, commands, isTauri, nextRequestId, type RunConfig } from "@/platform/ipc";
import { parseJavaArgs, resolveJavaLaunch, resolveJavaModule } from "@/platform/javaLaunch";
import { followLaunchBuild } from "@/features/build/store";
import {
maybeEditorService,
notifications,
onBuildCompleted,
useDebugRunSessions,
type BuildCompletedEvent,
type DebugServiceSession,
} from "@/workbench/contributions";
import { showContextMenu } from "@/ui";
import { buildTomcatArtifact, syncTomcatOutputs } from "./tomcat";
import { runUpdateBuild, updateBuildError } from "./buildUpdate";
import { rerunConfig, startRun, stopSession, useRun, waitForExit, type RunSession } from "./store";
import { isUpdatable, updateAllowed, type UpdateMode } from "./updatePolicies";
export type UpdateSession = Pick<RunSession, "id" | "config"> & { debug?: DebugServiceSession };
export const useApplicationUpdates = create<{ ids: ReadonlySet<string> }>(() => ({ ids: new Set() }));
const updatingConfigs = new Set<string>();
const JAVA_BUILD_SYSTEMS = new Set(["maven", "gradle", "javac"]);
export function updatableSessions(): UpdateSession[] {
const runs = useRun.getState().sessions.filter((s) => isUpdatable(s.config) && s.status === "running");
const debug = useDebugRunSessions
.getState()
.serviceSessions.filter(
(s) =>
isUpdatable(s.config) &&
(s.status === "running" || s.status === "paused") &&
!runs.some((r) => r.runId === s.processId && r.config.id === s.config.id),
)
.map((s) => ({ id: `debug:${s.id}`, config: s.config, debug: s }));
return [...runs, ...debug];
}
function params(session: UpdateSession): RunConfig["params"] {
return useRun.getState().configs.find((c) => c.id === session.config.id)?.params ?? session.config.params;
}
async function updateSpringBoot(config: RunConfig, mode: UpdateMode, debugging: boolean) {
const module = await resolveJavaModule(config);
const parsed = parseJavaArgs(config.args);
if (!parsed.mainClass) throw new Error(tx("The Spring Boot configuration has no main class"));
const request = nextRequestId();
const info = await resolveJavaLaunch(
module,
parsed.classpath === "test",
mode === "classes" ? "make" : "noBuild",
request,
followLaunchBuild(request, tx`Build before launch: ${config.name}`),
// HotSwap reloads what the Java language server compiles.
debugging,
);
if (info.build === "failed" || info.build === "withErrors" || info.build === "cancelled")
throw updateBuildError(info);
await runUpdateBuild(await call(commands.runApplicationBuild(config, module)));
const classPaths = parsed.explicitClasspath?.split(info.pathListSeparator) ?? info.classPaths;
await call(commands.runApplicationPublish(config, classPaths, parsed.mainClass));
if (mode === "classes" && debugging && (await executeAction("debug.reloadChangedClasses", { configId: config.id })))
return;
notifications().notify({
group: "run",
level: "info",
title: "Resources updated",
...(mode === "classes"
? {
body: "Classes were compiled. Restart the application to load them, or launch with the debugger to use HotSwap.",
}
: {}),
});
}
export async function updateApplication(session: UpdateSession, mode: string): Promise<void> {
if (!updateAllowed(session.config, mode) || updatingConfigs.has(session.config.id)) return;
updatingConfigs.add(session.config.id);
useApplicationUpdates.setState((s) => ({ ids: new Set([...s.ids, session.id]) }));
try {
const debugging =
!!session.debug || useDebugRunSessions.getState().sessions.some((s) => s.configId === session.config.id);
if (mode === "restart") {
const config = rerunConfig(session);
if (session.debug) {
await session.debug.stop();
await executeAction("run.debugConfig", config);
} else if (debugging) {
await stopSession(session.id);
await waitForExit([session.id], null);
await executeAction("run.debugConfig", config);
} else await startRun(config, session.id);
return;
}
await maybeEditorService()?.saveAll();
if (session.config.kind === "spring-boot") {
await updateSpringBoot(session.config, mode, debugging);
} else {
if (mode === "redeploy" || !(await syncTomcatOutputs(session.config, mode === "resources"))) {
await buildTomcatArtifact(session.config);
await call(commands.runTomcatUpdate(session.config, mode));
}
if (mode === "classes" && debugging) {
const swapped =
getAction("debug.reloadChangedClasses") &&
(await executeAction("debug.reloadChangedClasses", { configId: session.config.id }));
if (!swapped) await call(commands.runTomcatUpdate(session.config, "redeploy"));
}
notifications().notify({ group: "run", level: "info", title: "Application updated" });
}
if (!session.debug) useRun.setState({ activeSession: session.id });
} catch (e) {
notifications().notify({
group: "run",
level: "error",
title: "Application update failed",
body: e instanceof Error ? e.message : String(e),
});
} finally {
updatingConfigs.delete(session.config.id);
useApplicationUpdates.setState((s) => ({ ids: new Set([...s.ids].filter((id) => id !== session.id)) }));
}
}
export function showApplicationUpdate(sessionId?: string): void {
const state = useRun.getState();
const candidates = updatableSessions();
const session = candidates.find((s) => s.id === (sessionId || state.activeSession)) ?? candidates[0];
if (!session) return;
const policy = params(session)?.onUpdate ?? "ask";
if (policy !== "ask" && updateAllowed(session.config, policy)) {
void updateApplication(session, policy);
return;
}
const choices = [
["resources", "Update resources"],
["classes", "Update classes and resources"],
...(session.config.kind === "tomcat" ? [["redeploy", "Redeploy"]] : []),
["restart", session.config.kind === "tomcat" ? "Restart server" : "Restart"],
];
showContextMenu({ x: window.innerWidth / 2 - 140, y: 100 }, [
{ kind: "header", label: "Update Application" },
...choices.map(([mode, label]) => ({
label: label!,
disabled: useApplicationUpdates.getState().ids.has(session.id) || !updateAllowed(session.config, mode!),
run: () => {
void updateApplication(session, mode!);
},
})),
]);
}
export function updateOnDeactivation(): void {
for (const session of updatableSessions()) {
const mode = params(session)?.onDeactivation;
if (mode === "resources" || mode === "classes") void updateApplication(session, mode);
}
}
export function listenForApplicationDeactivation(): () => void {
if (!isTauri()) return () => {};
const listener = getCurrentWebviewWindow().listen("ide://application-deactivated", updateOnDeactivation);
return () => {
void listener.then((unlisten) => unlisten());
};
}
/** Syncs compiled classes and web resources into running exploded-artifact Tomcat deployments after a user Java build. */
export async function syncTomcatOnBuildCompleted(event: BuildCompletedEvent): Promise<void> {
if (!event.userInitiated || !JAVA_BUILD_SYSTEMS.has(event.system)) return;
const sessions = updatableSessions().filter(
(s) =>
s.config.kind === "tomcat" &&
(s.config.params?.deployment ?? "artifact") === "artifact" &&
!updatingConfigs.has(s.config.id),
);
for (const session of sessions) {
updatingConfigs.add(session.config.id);
useApplicationUpdates.setState((st) => ({ ids: new Set([...st.ids, session.id]) }));
try {
// oxlint-disable-next-line no-await-in-loop -- deployments sync in turn; parallel notices would race the shared tomcat-sync key and writes could target the same exploded artifact
const synced = await syncTomcatOutputs(session.config, false, "noBuild");
if (!synced) continue;
const debugging =
!!session.debug || useDebugRunSessions.getState().sessions.some((d) => d.configId === session.config.id);
if (!debugging) {
notifications().notify({ group: "run", level: "info", key: "tomcat-sync", title: "Tomcat classes updated" });
}
} catch {
// Unrelated modules or stopped deployments leave the user's explicit build result undisturbed.
} finally {
updatingConfigs.delete(session.config.id);
useApplicationUpdates.setState((st) => ({ ids: new Set([...st.ids].filter((id) => id !== session.id)) }));
}
}
}
export function installBuildTomcatSync(): () => void {
return onBuildCompleted((event) => {
void syncTomcatOnBuildCompleted(event);
});
}