Файли
openidea/src/features/debugger/__tests__/javaCancel.test.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

213 рядки
7.5 KiB
TypeScript

import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { executeAction } from "@/platform/actions";
import { useProject } from "@/platform/project";
import { provideNotificationService, useDebugRunSessions } from "@/workbench/contributions";
import type { RunConfig } from "@/platform/ipc";
import { registerDebugActions } from "../actions";
import { useDebug } from "../state";
const ipc = vi.hoisted(() => ({
javaResolveLaunch: vi.fn(),
cancelRequest: vi.fn(async () => undefined),
javaDebugAdapter: vi.fn(async () => ({ status: "ok", data: "java-debug" })),
javaDebugServer: vi.fn(async () => ({ status: "ok", data: 5005 })),
debugStart: vi.fn(async () => ({ status: "ok", data: 42 })),
debugStop: vi.fn(async () => ({ status: "ok", data: null })),
fsReadDir: vi.fn(async () => ({ status: "ok", data: [] })),
}));
vi.mock("@tauri-apps/api/core", async (original) => ({
...(await original<typeof import("@tauri-apps/api/core")>()),
Channel: class {
onmessage = null;
},
}));
vi.mock("@/platform/ipc", async (original) => {
const real = await original<typeof import("@/platform/ipc")>();
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
});
const notify = vi.fn();
const expire = vi.fn();
const config: RunConfig = {
id: "application:Main",
name: "Main",
kind: "application",
command: "java",
args: ["-cp", "${classpath}", "Main"],
cwd: null,
module: "",
env: {},
detected: true,
isTest: false,
debugAdapter: "java-debug",
};
let dispose: () => void;
let respond: (result: unknown) => void;
beforeEach(() => {
vi.clearAllMocks();
useDebug.setState({ sessions: {}, active: null, console: {} });
useProject.setState({ project: { root: "/p" } as never });
provideNotificationService({ notify, expire });
ipc.javaResolveLaunch.mockImplementation(
() =>
new Promise((resolve) => {
respond = resolve;
}),
);
dispose = registerDebugActions();
});
afterEach(() => dispose());
async function startAndStop() {
const starting = executeAction("debug.startConfig", config);
await vi.waitFor(() => expect(ipc.javaResolveLaunch).toHaveBeenCalledOnce());
const session = Object.values(useDebug.getState().sessions)[0]!;
expect(session).toMatchObject({ name: "Main", status: "starting", runConfig: config });
expect(
useDebug
.getState()
.console[session.id]?.map((l) => l.text)
.join("\n"),
).toContain("Building and resolving the classpath of Main…");
expect(useDebugRunSessions.getState().sessions[0]?.configId).toBe(config.id);
await executeAction("debug.stop");
expect(ipc.cancelRequest).toHaveBeenCalledWith(ipc.javaResolveLaunch.mock.calls[0]![4]);
expect(useDebug.getState().sessions[session.id]?.status).toBe("terminated");
expect(useDebugRunSessions.getState().sessions).toEqual([]);
return { starting };
}
function expectNoLaunch() {
expect(ipc.javaDebugServer).not.toHaveBeenCalled();
expect(ipc.debugStart).not.toHaveBeenCalled();
expect(Object.values(useDebug.getState().sessions).every((s) => s.status === "terminated")).toBe(true);
expect(notify).not.toHaveBeenCalled();
}
it("Stop cancels the resolve request and ends the preparation session without starting DAP", async () => {
const { starting } = await startAndStop();
respond({ status: "error", error: { kind: "cancelled", message: "Cancelled" } });
await starting;
expectNoLaunch();
});
it("ignores a successful resolve arriving after Stop, including compile warnings", async () => {
const { starting } = await startAndStop();
respond({ status: "ok", data: { errorCount: 1 } });
await starting;
expectNoLaunch();
});
it("ignores a failed resolve arriving after Stop", async () => {
const { starting } = await startAndStop();
respond({ status: "error", error: { kind: "internal", message: "Build failed" } });
await starting;
expectNoLaunch();
});
it("still reports a real resolve failure in the preparation console", async () => {
const starting = executeAction("debug.startConfig", config);
await vi.waitFor(() => expect(ipc.javaResolveLaunch).toHaveBeenCalledOnce());
respond({ status: "error", error: { kind: "internal", message: "Build failed" } });
await starting;
expect(notify).toHaveBeenLastCalledWith(
expect.objectContaining({
level: "error",
title: "Cannot start debugging",
body: "Build failed",
}),
);
expect(
Object.values(useDebug.getState().console)
.flat()
.map((line) => line.text)
.join("\n"),
).toContain("Build failed");
expect(ipc.debugStart).not.toHaveBeenCalled();
});
it.each([
"jdtls: Given URI does not belong to any Java project.",
"jdtls: Launch configuration 1793460461218 references non-existing project parent.",
])("explains how to import a module when Debug fails with %s", async (message) => {
const starting = executeAction("debug.startConfig", { ...config, module: "web" });
await vi.waitFor(() => expect(ipc.javaResolveLaunch).toHaveBeenCalledOnce());
respond({ status: "error", error: { kind: "protocol", message } });
await starting;
expect(notify).toHaveBeenLastCalledWith(
expect.objectContaining({
title: "Cannot start debugging",
body: expect.stringContaining("Java module 'web' is not imported."),
}),
);
expect(
Object.values(useDebug.getState().console)
.flat()
.map((line) => line.text)
.join("\n"),
).toContain("open its folder as a project");
expect(ipc.javaDebugServer).not.toHaveBeenCalled();
expect(ipc.debugStart).not.toHaveBeenCalled();
});
it("keeps progress and the originating configuration when DAP takes over", async () => {
const starting = executeAction("debug.startConfig", config);
await vi.waitFor(() => expect(ipc.javaResolveLaunch).toHaveBeenCalledOnce());
respond({
status: "ok",
data: {
build: "succeeded",
errorCount: 0,
errors: [],
hints: [],
classPaths: ["/p/target/classes"],
modulePaths: [],
pathListSeparator: ":",
javaExec: "java",
},
});
await starting;
expect(Object.keys(useDebug.getState().sessions)).toEqual(["42"]);
expect(useDebug.getState().sessions[42]).toMatchObject({ status: "running", runConfig: config });
expect(
useDebug
.getState()
.console[42]?.map((line) => line.text)
.join("\n"),
).toContain("Building and resolving the classpath of Main…");
});
it.each(["success", "failure"])("handles a late DAP %s after preparation was cancelled", async (outcome) => {
let fail!: (error: Error) => void;
let finish!: (value: { status: "ok"; data: number }) => void;
ipc.debugStart.mockImplementationOnce(
() =>
new Promise((resolve, reject) => {
finish = resolve;
fail = reject;
}),
);
const starting = executeAction("debug.startConfig", config);
await vi.waitFor(() => expect(ipc.javaResolveLaunch).toHaveBeenCalledOnce());
respond({
status: "ok",
data: {
build: "succeeded",
errorCount: 0,
errors: [],
hints: [],
classPaths: ["/p/target/classes"],
modulePaths: [],
pathListSeparator: ":",
javaExec: "java",
},
});
await vi.waitFor(() => expect(ipc.debugStart).toHaveBeenCalledOnce());
await executeAction("debug.stop");
if (outcome === "success") finish({ status: "ok", data: 42 });
else fail(new Error("Adapter start failed"));
await starting;
if (outcome === "success") expect(ipc.debugStop).toHaveBeenCalledWith(42);
expect(notify).not.toHaveBeenCalled();
expect(useDebugRunSessions.getState().sessions).toEqual([]);
});