дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 01:01:17 +02:00
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.
406 рядки
15 KiB
TypeScript
406 рядки
15 KiB
TypeScript
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||
import { IpcError, type RunConfig } from "@/platform/ipc";
|
||
import { useProject } from "@/platform/project";
|
||
import { findJavaModule, prepareJavaLaunch, prepareJavaModule } from "@/platform/javaLaunch";
|
||
import { _resetI18nForTests, setLocale } from "@/platform/i18n";
|
||
import { provideNotificationService } from "@/workbench/contributions";
|
||
import { applicationConfig } from "./application";
|
||
import { resetRuns, runtime, saveUserConfigs, startRun } from "./store";
|
||
import { applicationType } from "./jvmTypes";
|
||
import { withParams } from "./types";
|
||
|
||
const ipc = vi.hoisted(() => {
|
||
const ok = (data: unknown) => Promise.resolve({ status: "ok", data });
|
||
return {
|
||
findFiles: vi.fn((name: string) =>
|
||
ok(
|
||
name === "Main.java"
|
||
? [{ path: "/p/app/src/main/java/a/Main.java", relPath: "app/src/main/java/a/Main.java" }]
|
||
: [],
|
||
),
|
||
),
|
||
fsReadText: vi.fn(() => ok("package a;\npublic class Main {}")),
|
||
runConfigs: vi.fn(() => ok([])),
|
||
runSaveConfigs: vi.fn(() => ok(null)),
|
||
runStart: vi.fn(() => ok({ id: 1, pty: false })),
|
||
javaResolveLaunch: vi.fn(() =>
|
||
ok({
|
||
build: "succeeded",
|
||
projectRoot: "/p",
|
||
classPaths: ["/p/app/target/classes"],
|
||
modulePaths: [],
|
||
pathListSeparator: ":",
|
||
javaHome: null,
|
||
javaExec: "java",
|
||
shortenCommandLine: null,
|
||
errors: [],
|
||
errorCount: 0,
|
||
hints: [],
|
||
}),
|
||
),
|
||
javaJunitRunner: vi.fn(() =>
|
||
ok({
|
||
classPaths: ["/p/app/target/test-classes", "/runner.jar"],
|
||
vmArgs: ["-Xmx1g", "-Dopenidea.fail=true"],
|
||
env: { TZ: "UTC" },
|
||
workingDirectory: "/p/app/work",
|
||
surefire: ["argLine", "systemPropertyVariables"],
|
||
}),
|
||
),
|
||
};
|
||
});
|
||
vi.mock("@/platform/ipc", async (original) => {
|
||
const real = await original<typeof import("@/platform/ipc")>();
|
||
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
|
||
});
|
||
vi.mock("@tauri-apps/api/core", async (original) => ({
|
||
...(await original<typeof import("@tauri-apps/api/core")>()),
|
||
Channel: class {
|
||
onmessage = null;
|
||
},
|
||
}));
|
||
const config: RunConfig = {
|
||
id: "user:main",
|
||
name: "Main",
|
||
kind: "application",
|
||
command: "java",
|
||
args: ["-cp", "${classpath}", "a.Main"],
|
||
cwd: "app",
|
||
env: {},
|
||
detected: false,
|
||
isTest: false,
|
||
debugAdapter: "java-debug",
|
||
};
|
||
beforeEach(() => {
|
||
vi.clearAllMocks();
|
||
provideNotificationService({ notify: vi.fn() });
|
||
});
|
||
afterEach(() => {
|
||
resetRuns();
|
||
_resetI18nForTests();
|
||
useProject.setState({ project: null });
|
||
});
|
||
|
||
it.each(["sibling", "/outside/modules"])("runs from %s using the stored module's classpath", async (cwd) => {
|
||
const session = await startRun({ ...config, module: "app", cwd });
|
||
expect(session?.status).toBe("running");
|
||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
|
||
"app",
|
||
false,
|
||
false,
|
||
"automatic",
|
||
expect.any(Number),
|
||
expect.anything(),
|
||
);
|
||
expect(ipc.runStart).toHaveBeenCalledWith(
|
||
expect.objectContaining({ cwd, args: ["-cp", "/p/app/target/classes", "a.Main"] }),
|
||
expect.anything(),
|
||
expect.any(Number),
|
||
);
|
||
expect(ipc.findFiles).not.toHaveBeenCalled();
|
||
});
|
||
|
||
const launchInfo = (build: "succeeded" | "failed" | "withErrors") => ({
|
||
build,
|
||
projectRoot: "/p",
|
||
classPaths: ["/p/app/target/classes"],
|
||
modulePaths: [],
|
||
javaHome: null,
|
||
javaExec: "java",
|
||
shortenCommandLine: null,
|
||
errors: build === "succeeded" ? [] : [{ path: "/p/app/src/Main.java", line: 1, column: 1, message: "boom" }],
|
||
errorCount: build === "succeeded" ? 0 : 1,
|
||
hints: [],
|
||
});
|
||
|
||
it.each(["noBuild", "rebuild"] as const)("passes the %s build policy to the resolver", async (buildPolicy) => {
|
||
await startRun({ ...config, module: "app", buildPolicy });
|
||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
|
||
"app",
|
||
false,
|
||
false,
|
||
buildPolicy,
|
||
expect.any(Number),
|
||
expect.anything(),
|
||
);
|
||
});
|
||
|
||
it("always applies the launch policy after a Before launch Build Project", async () => {
|
||
useProject.setState({ project: { root: "/p" } as never });
|
||
await startRun({ ...config, module: "app" });
|
||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
|
||
"app",
|
||
false,
|
||
false,
|
||
"automatic",
|
||
expect.any(Number),
|
||
expect.anything(),
|
||
);
|
||
useProject.setState({ project: null });
|
||
});
|
||
|
||
it("does not start a configuration whose build failed", async () => {
|
||
ipc.javaResolveLaunch.mockResolvedValueOnce({ status: "ok", data: launchInfo("failed") });
|
||
const session = await startRun({ ...config, module: "app", buildPolicy: "make" });
|
||
expect(session?.status).toBe("failed");
|
||
expect(ipc.runStart).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it("starts with the last compiled classes for makeAndContinueOnErrors", async () => {
|
||
ipc.javaResolveLaunch.mockResolvedValueOnce({ status: "ok", data: launchInfo("withErrors") });
|
||
const session = await startRun({ ...config, module: "app", buildPolicy: "makeAndContinueOnErrors" });
|
||
expect(session?.status).toBe("running");
|
||
expect(ipc.runStart).toHaveBeenCalled();
|
||
});
|
||
|
||
it.each([undefined, "automatic", "make", "rebuild"] as const)(
|
||
"does not launch scoped compilation-error bytecode under %s",
|
||
async (buildPolicy) => {
|
||
ipc.javaResolveLaunch.mockResolvedValueOnce({ status: "ok", data: launchInfo("withErrors") });
|
||
const session = await startRun({ ...config, module: "app", buildPolicy });
|
||
expect(session?.status).toBe("failed");
|
||
expect(ipc.runStart).not.toHaveBeenCalled();
|
||
},
|
||
);
|
||
|
||
it("finds the source module for an old saved configuration without a module", async () => {
|
||
await startRun({ ...config, cwd: "/outside/modules" });
|
||
expect(ipc.findFiles).toHaveBeenCalledWith("Main.java", 1000);
|
||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
|
||
"app",
|
||
false,
|
||
false,
|
||
"automatic",
|
||
expect.any(Number),
|
||
expect.anything(),
|
||
);
|
||
expect(ipc.runStart).toHaveBeenCalledWith(
|
||
expect.objectContaining({ cwd: "/outside/modules" }),
|
||
expect.anything(),
|
||
expect.any(Number),
|
||
);
|
||
});
|
||
|
||
it.each([null, "/elsewhere"])("recovers an attached module from its indexed path with cwd %s", async (cwd) => {
|
||
const root = "/p";
|
||
const member = "/other/spring";
|
||
const module = `${member}/web`;
|
||
useProject.setState({
|
||
project: { root, workspace: { version: 1, name: "demo", projects: [root, member] } } as never,
|
||
});
|
||
ipc.findFiles.mockResolvedValueOnce({
|
||
status: "ok",
|
||
data: [{ path: `${module}/src/main/java/a/Main.java`, relPath: "spring/web/src/main/java/a/Main.java" }],
|
||
});
|
||
const session = await startRun({ ...config, cwd });
|
||
expect(session?.status).toBe("running");
|
||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
|
||
module,
|
||
false,
|
||
false,
|
||
"automatic",
|
||
expect.any(Number),
|
||
expect.anything(),
|
||
);
|
||
expect(ipc.runStart).toHaveBeenCalledWith(
|
||
expect.objectContaining({ cwd: cwd ?? module, module }),
|
||
expect.anything(),
|
||
expect.any(Number),
|
||
);
|
||
});
|
||
|
||
it.each([["-cp", "lib/*"], []])("colours Spring Boot runs without classpath resolution (%j)", async (...classpath) => {
|
||
const args = ["-Xmx256m", ...classpath, "a.Main", "--spring.profiles.active=dev"];
|
||
const boot = { ...config, kind: "spring-boot", args };
|
||
const session = await startRun(boot);
|
||
expect(session?.status).toBe("running");
|
||
expect(ipc.runStart).toHaveBeenCalledWith(
|
||
expect.objectContaining({ args: ["-Dspring.output.ansi.enabled=always", ...args] }),
|
||
expect.anything(),
|
||
expect.any(Number),
|
||
);
|
||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
|
||
"app",
|
||
false,
|
||
false,
|
||
"automatic",
|
||
expect.any(Number),
|
||
expect.anything(),
|
||
);
|
||
expect(boot.args).toBe(args);
|
||
expect(args).not.toContain("-Dspring.output.ansi.enabled=always");
|
||
});
|
||
|
||
it.each(["never", "detect", "always"])("preserves an explicit Spring Boot console setting (%s)", async (value) => {
|
||
const args = [`-Dspring.output.ansi.enabled=${value}`, "-cp", "lib/*", "a.Main"];
|
||
await startRun({ ...config, kind: "spring-boot", args });
|
||
expect(ipc.runStart).toHaveBeenCalledWith(expect.objectContaining({ args }), expect.anything(), expect.any(Number));
|
||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
|
||
"app",
|
||
false,
|
||
false,
|
||
"automatic",
|
||
expect.any(Number),
|
||
expect.anything(),
|
||
);
|
||
});
|
||
|
||
it("keeps plain Java runs with an explicit classpath free of Spring Boot options", async () => {
|
||
const args = ["-cp", "lib/*", "a.Main"];
|
||
await startRun({ ...config, args });
|
||
expect(ipc.runStart).toHaveBeenCalledWith(expect.objectContaining({ args }), expect.anything(), expect.any(Number));
|
||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
|
||
"app",
|
||
false,
|
||
false,
|
||
"automatic",
|
||
expect.any(Number),
|
||
expect.anything(),
|
||
);
|
||
});
|
||
|
||
it("adds the Spring Boot console option once when resolving the module classpath", async () => {
|
||
await startRun({ ...config, kind: "spring-boot", module: "app" });
|
||
expect(ipc.runStart).toHaveBeenCalledWith(
|
||
expect.objectContaining({
|
||
args: ["-Dspring.output.ansi.enabled=always", "-cp", "/p/app/target/classes", "a.Main"],
|
||
}),
|
||
expect.anything(),
|
||
expect.any(Number),
|
||
);
|
||
});
|
||
|
||
it("keeps an explicitly stored root module", async () => {
|
||
expect(await findJavaModule({ ...config, module: "", cwd: "sibling" })).toBe("");
|
||
expect(ipc.findFiles).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it("stores the source module when a manually created application is saved", async () => {
|
||
await saveUserConfigs([{ ...config, cwd: "sibling" }]);
|
||
expect(ipc.runSaveConfigs).toHaveBeenCalledWith([expect.objectContaining({ module: "app", cwd: "sibling" })], []);
|
||
});
|
||
|
||
it("stores the module at context creation and forgets it when the main class changes", () => {
|
||
const detected = applicationConfig({ className: "a.Main" }, "app/src/main/java/a/Main.java");
|
||
expect(detected.module).toBe("app");
|
||
expect(withParams(detected, { mainClass: "b.Other" }, applicationType).module).toBeUndefined();
|
||
expect(withParams(detected, { mainClass: "a.Main", programArgs: "x" }, applicationType).module).toBe("app");
|
||
});
|
||
|
||
it("does not substitute the working directory when sources are missing or ambiguous", async () => {
|
||
ipc.findFiles.mockResolvedValueOnce({ status: "ok", data: [] });
|
||
expect(await findJavaModule({ ...config, cwd: "sibling" })).toBeNull();
|
||
ipc.findFiles.mockResolvedValueOnce({
|
||
status: "ok",
|
||
data: [
|
||
{ path: "/p/app/src/main/java/a/Main.java", relPath: "app/src/main/java/a/Main.java" },
|
||
{ path: "/p/other/src/main/java/a/Main.java", relPath: "other/src/main/java/a/Main.java" },
|
||
],
|
||
});
|
||
expect(await findJavaModule(config)).toBeNull();
|
||
});
|
||
|
||
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 Run fails with %s", async (message) => {
|
||
ipc.javaResolveLaunch.mockResolvedValueOnce({ status: "error", error: { kind: "protocol", message } } as never);
|
||
const session = await startRun({ ...config, module: "web" });
|
||
expect(session?.status).toBe("failed");
|
||
const output = runtime(session!.id)!
|
||
.console.lines.map((line) => line.text)
|
||
.join("\n");
|
||
expect(output).toContain("Java module 'web' is not imported.");
|
||
expect(output).toContain("parent Maven or Gradle build");
|
||
expect(output).toContain("open its folder as a project");
|
||
expect(ipc.runStart).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it("says which build errors kept a module from being imported", async () => {
|
||
const problems = ["web/pom.xml: Plugin org.apache.maven.plugins:maven-compiler-plugin:9.9.9 could not be resolved"];
|
||
ipc.javaResolveLaunch.mockResolvedValueOnce({
|
||
status: "error",
|
||
error: {
|
||
kind: "invalidInput",
|
||
message: "jdtls: /p/web is not a Java project",
|
||
data: { type: "javaBuildProblems", problems },
|
||
},
|
||
} as never);
|
||
const session = await startRun({ ...config, module: "web" });
|
||
expect(session?.status).toBe("failed");
|
||
const output = runtime(session!.id)!
|
||
.console.lines.map((line) => line.text)
|
||
.join("\n");
|
||
expect(output).toContain(`Java module 'web' could not be imported because its build has errors: ${problems[0]}.`);
|
||
expect(output).not.toContain("Wait for Java project import");
|
||
expect(ipc.runStart).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it.each([
|
||
["unavailable", "jdtls is not installed (Settings › Languages & Frameworks › Language Servers)"],
|
||
["unavailable", "jdtls exited with code 1: wrong Java version"],
|
||
["protocol", "jdtls: workspace/executeCommand timed out after 90 s"],
|
||
["internal", "Build failed"],
|
||
["cancelled", "jdtls: Given URI does not belong to any Java project."],
|
||
] as const)("preserves other launch errors (%s: %s)", async (kind, message) => {
|
||
const error = new IpcError({ kind, message });
|
||
ipc.javaResolveLaunch.mockRejectedValueOnce(error);
|
||
await expect(
|
||
prepareJavaLaunch({ ...config, module: "web" }, { request: 1, signal: new AbortController().signal }),
|
||
).rejects.toBe(error);
|
||
});
|
||
|
||
it("translates import recovery guidance for a root Spring Boot configuration", async () => {
|
||
await setLocale("zh");
|
||
ipc.javaResolveLaunch.mockRejectedValueOnce(
|
||
new IpcError({ kind: "protocol", message: "jdtls: Given URI does not belong to any Java project." }),
|
||
);
|
||
await expect(
|
||
prepareJavaLaunch(
|
||
{ ...config, kind: "spring-boot", module: "" },
|
||
{ request: 1, signal: new AbortController().signal },
|
||
),
|
||
).rejects.toThrow("Java 模块 '.' 尚未导入");
|
||
});
|
||
|
||
it("does not resolve or launch when saving fails", async () => {
|
||
const saveAll = vi.fn().mockRejectedValue(new Error("save failed"));
|
||
await expect(
|
||
prepareJavaLaunch(config, {
|
||
request: 1,
|
||
signal: new AbortController().signal,
|
||
saveAll,
|
||
}),
|
||
).rejects.toThrow("save failed");
|
||
await expect(prepareJavaModule(config, saveAll)).rejects.toThrow("save failed");
|
||
expect(ipc.javaResolveLaunch).not.toHaveBeenCalled();
|
||
expect(ipc.runStart).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it("gives the JUnit runner's JVM the module's Surefire configuration", async () => {
|
||
const report = vi.fn();
|
||
const junit: RunConfig = {
|
||
...config,
|
||
module: "app",
|
||
isTest: true,
|
||
args: ["-ea", "-cp", "${testClasspath}", "ai.openidea.junit.Runner", "a.MainTest#adds"],
|
||
env: { TZ: "Europe/Paris" },
|
||
};
|
||
const { resolved } = await prepareJavaLaunch(junit, { request: 1, signal: new AbortController().signal, report });
|
||
expect(ipc.javaJunitRunner).toHaveBeenCalledWith("app", ["/p/app/target/classes"]);
|
||
expect(resolved).toMatchObject({
|
||
args: [
|
||
"-Xmx1g",
|
||
"-Dopenidea.fail=true",
|
||
"-ea",
|
||
"-cp",
|
||
"/p/app/target/test-classes:/runner.jar",
|
||
"ai.openidea.junit.Runner",
|
||
"a.MainTest#adds",
|
||
],
|
||
env: { TZ: "Europe/Paris" },
|
||
cwd: "/p/app/work",
|
||
});
|
||
expect(report).toHaveBeenCalledWith("Applying the Surefire configuration: argLine, systemPropertyVariables\n");
|
||
});
|