дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 16:51:16 +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.
372 рядки
16 KiB
TypeScript
372 рядки
16 KiB
TypeScript
/**
|
|
* Java "Application" run configurations, shared by Run and Debug: the command
|
|
* line is `java [vm options] -cp ${classpath} <main class> [program args]`;
|
|
* `${classpath}` (or `${testClasspath}`) and the `java` launcher are resolved
|
|
* through jdtls when the configuration starts.
|
|
*/
|
|
import { Channel } from "@tauri-apps/api/core";
|
|
import {
|
|
call,
|
|
commands,
|
|
IpcError,
|
|
isCancelled,
|
|
type BuildEvent,
|
|
type BuildPolicy,
|
|
type JavaLaunchInfo,
|
|
type JunitLaunch,
|
|
type RunConfig,
|
|
type RequestId,
|
|
} from "@/platform/ipc";
|
|
import { tx } from "@/platform/i18n";
|
|
import { projectFolder, relativePath, useProject } from "@/platform/project";
|
|
import { useBuildPresentation } from "@/platform/projectPresentation";
|
|
import { isRemoteWindow } from "@/platform/remote";
|
|
|
|
export const CLASSPATH = "${classpath}";
|
|
export const TEST_CLASSPATH = "${testClasspath}";
|
|
/** OpenIDEA's JUnit Platform runner (`java/junit-runner`): its jar and the launcher join the test classpath. */
|
|
export const JUNIT_RUNNER_MAIN = "ai.openidea.junit.Runner";
|
|
/** Run configuration kinds launched as a JVM main class. */
|
|
export const JVM_APPLICATION_KINDS = ["application", "spring-boot"];
|
|
|
|
export function isJvmApplication(config: Pick<RunConfig, "kind">): boolean {
|
|
return JVM_APPLICATION_KINDS.includes(config.kind);
|
|
}
|
|
|
|
/** Run configuration kinds whose JVM gets the plugins' Java agents (`[[contributes.javaAgents]]`). */
|
|
const JAVA_AGENT_KINDS = ["application", "spring-boot", "jar-application"];
|
|
|
|
/**
|
|
* The console line of a Java launch in a remote project, when plugins with a granted
|
|
* `java.agent` would have added their agent: the JVM runs on the server, and agents load
|
|
* only into JVMs on this machine. `null` otherwise. Plugins are the desktop's own.
|
|
*/
|
|
export async function remoteJavaAgentNote(config: Pick<RunConfig, "kind">): Promise<string | null> {
|
|
if (!JAVA_AGENT_KINDS.includes(config.kind) || !isRemoteWindow()) return null;
|
|
const snapshot = await call(commands.pluginList()).catch(() => null);
|
|
const names = (snapshot?.plugins ?? [])
|
|
.filter((p) => p.enabled && p.capabilities.some((c) => c.id === "java.agent" && c.granted))
|
|
.map((p) => p.name);
|
|
if (!names.length) return null;
|
|
const list = names.join(", ");
|
|
return tx`Java agents of ${list} were not added: they load only in local projects.` + "\n";
|
|
}
|
|
|
|
/** `java` options whose value is the next argument. */
|
|
const WITH_VALUE = new Set([
|
|
"-cp",
|
|
"-classpath",
|
|
"--class-path",
|
|
"-p",
|
|
"--module-path",
|
|
"--upgrade-module-path",
|
|
"--add-modules",
|
|
"--add-opens",
|
|
"--add-exports",
|
|
"--add-reads",
|
|
"--patch-module",
|
|
"--limit-modules",
|
|
"--enable-native-access",
|
|
]);
|
|
|
|
export interface JavaCommandLine {
|
|
/** VM options, without the classpath. */
|
|
vmArgs: string[];
|
|
mainClass: string | null;
|
|
jarPath?: string;
|
|
programArgs: string[];
|
|
/** Which classpath placeholder the configuration uses (`null`: an explicit classpath or none). */
|
|
classpath: "runtime" | "test" | null;
|
|
/** An explicit `-cp` value other than a placeholder. */
|
|
explicitClasspath: string | null;
|
|
}
|
|
|
|
/** Splits `java` arguments into VM options, main class and program arguments. */
|
|
export function parseJavaArgs(args: readonly string[]): JavaCommandLine {
|
|
const vmArgs: string[] = [];
|
|
let classpath: JavaCommandLine["classpath"] = null;
|
|
let explicitClasspath: string | null = null;
|
|
for (let i = 0; i < args.length; i++) {
|
|
const a = args[i]!;
|
|
if (a === "-jar")
|
|
return {
|
|
vmArgs,
|
|
mainClass: null,
|
|
jarPath: args[i + 1],
|
|
programArgs: args.slice(i + 2),
|
|
classpath,
|
|
explicitClasspath,
|
|
};
|
|
if (a === "-cp" || a === "-classpath" || a === "--class-path") {
|
|
const value = args[++i] ?? "";
|
|
if (value === CLASSPATH) classpath = "runtime";
|
|
else if (value === TEST_CLASSPATH) classpath = "test";
|
|
else explicitClasspath = value;
|
|
continue;
|
|
}
|
|
if (WITH_VALUE.has(a)) {
|
|
vmArgs.push(a, args[++i] ?? "");
|
|
continue;
|
|
}
|
|
if (a.startsWith("-")) {
|
|
vmArgs.push(a);
|
|
continue;
|
|
}
|
|
return { vmArgs, mainClass: a, programArgs: args.slice(i + 1), classpath, explicitClasspath };
|
|
}
|
|
return { vmArgs, mainClass: null, programArgs: [], classpath, explicitClasspath };
|
|
}
|
|
|
|
/**
|
|
* VM options a launch adds for the console, as IDEA's Spring Boot configurations do: the
|
|
* console renders ANSI colours, but Spring only detects a terminal, and the process runs on pipes.
|
|
* Kept out when the configuration sets the property itself.
|
|
*/
|
|
export function consoleVmArgs(config: Pick<RunConfig, "kind" | "args">): string[] {
|
|
if (config.kind !== "spring-boot") return [];
|
|
const own = parseJavaArgs(config.args).vmArgs.some((a) => a.startsWith("-Dspring.output.ansi.enabled="));
|
|
return own ? [] : ["-Dspring.output.ansi.enabled=always"];
|
|
}
|
|
|
|
/** The configuration with its placeholders and launcher resolved. */
|
|
export function resolveJavaCommand(config: RunConfig, info: JavaLaunchInfo): RunConfig {
|
|
const cp = info.classPaths.join(info.pathListSeparator);
|
|
const args: string[] = [...consoleVmArgs(config)];
|
|
if (info.modulePaths.length && !config.args.some((a) => a === "-p" || a === "--module-path"))
|
|
args.push("--module-path", info.modulePaths.join(info.pathListSeparator));
|
|
args.push(...config.args.map((a) => (a === CLASSPATH || a === TEST_CLASSPATH ? cp : a)));
|
|
const command = config.command === "java" && info.javaExec ? info.javaExec : config.command;
|
|
return { ...config, command, args };
|
|
}
|
|
|
|
/** Console report of a launch's compile errors (`path:line:col: error: …`) and their likely causes; "" when none. */
|
|
export function formatCompileErrors(info: JavaLaunchInfo): string {
|
|
const lines = info.errors.map((e) => `${e.path}:${e.line}:${e.column}: error: ${e.message}`);
|
|
const more = info.errorCount - info.errors.length;
|
|
if (more > 0) lines.push(`… and ${more} more error${more === 1 ? "" : "s"} (see the Problems tool window)`);
|
|
lines.push(...info.hints);
|
|
return lines.length ? `${lines.join("\n")}\n` : "";
|
|
}
|
|
|
|
/** Joins arguments into one string for adapters that take `args` / `vmArgs` as text (java-debug). */
|
|
export function joinJavaArgs(args: readonly string[]): string {
|
|
return args.map((a) => (a === "" ? '""' : /[\s"]/.test(a) ? `"${a.replace(/(["\\])/g, "\\$1")}"` : a)).join(" ");
|
|
}
|
|
|
|
/** JDWP agent options: listen on a free local port and wait for the debugger. */
|
|
export const JDWP_AGENT = "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0";
|
|
|
|
/** Makes a HotSpot JVM open its attach socket at start-up; the memory view finds the debuggee through it. */
|
|
export const ATTACH_LISTENER = "-XX:+StartAttachListener";
|
|
|
|
/** True when VM options already decide about the attach mechanism, so the IDE must not override them. */
|
|
export function optsOutOfAttach(text: string): boolean {
|
|
return /StartAttachListener|DisableAttachMechanism/.test(text);
|
|
}
|
|
|
|
/** The port of `Listening for transport dt_socket at address: 5005` (JDWP's start-up line). */
|
|
export function jdwpListeningPort(line: string): number | null {
|
|
const m = /Listening for transport dt_socket at address:\s*(?:[\w.[\]:-]*:)?(\d+)\s*$/.exec(line.trim());
|
|
return m ? Number(m[1]) : null;
|
|
}
|
|
|
|
/**
|
|
* Module directory (relative to the project root, `""` for the root; absolute for a
|
|
* module outside it) of a JVM source file. Like IDEA's `ProjectFileIndex.getModuleForFile`:
|
|
* the innermost Maven / Gradle module folder holding the file, as the build model knows
|
|
* them (`modules`). Before a model knows a deeper one: the part before
|
|
* `src/{main,test}/…`, else the working directory of the closest Maven / Gradle configuration.
|
|
*/
|
|
export function jvmModuleDir(
|
|
relPath: string,
|
|
configs: readonly RunConfig[] = [],
|
|
modules: Iterable<string> = useBuildPresentation.getState().modules.keys(),
|
|
): string {
|
|
const owner = [...modules].filter((d) => d && relPath.startsWith(d + "/")).sort((a, b) => b.length - a.length)[0];
|
|
if (owner) return owner;
|
|
const m = /^(?:(.*)\/)?src\/(?:main|test|[\w-]+)\/(?:java|kotlin|scala|groovy)\//.exec(relPath);
|
|
if (m) return m[1] ?? "";
|
|
const cwds = configs
|
|
.filter((c) => c.kind === "maven" || c.kind === "gradle")
|
|
.map((c) => (c.cwd ?? "").replace(/^\.\/?/, "").replace(/\/+$/, ""))
|
|
.filter((cwd) => !cwd || relPath.startsWith(cwd + "/"))
|
|
.sort((a, b) => b.length - a.length);
|
|
return cwds[0] ?? "";
|
|
}
|
|
|
|
/** Recover the classpath module of configurations saved before it was stored separately. */
|
|
export async function findJavaModule(config: RunConfig): Promise<string | null> {
|
|
if (config.module != null) return config.module;
|
|
const main = parseJavaArgs(config.args).mainClass;
|
|
if (!main) return null;
|
|
const modules = await classModules(main);
|
|
return modules.length === 1 ? modules[0]! : null;
|
|
}
|
|
|
|
/** Module directories (as {@link jvmModuleDir}) of the project's sources declaring the class `binaryName`. */
|
|
export async function classModules(binaryName: string): Promise<string[]> {
|
|
const root = useProject.getState().project?.root;
|
|
const outer = binaryName.split("$")[0]!;
|
|
const simple = outer.slice(outer.lastIndexOf(".") + 1);
|
|
const pkg = outer.slice(0, Math.max(0, outer.lastIndexOf(".")));
|
|
const names = [`${simple}.java`, `${simple}.kt`, ...(simple.endsWith("Kt") ? [`${simple.slice(0, -2)}.kt`] : [])];
|
|
const matches = (await Promise.all(names.map((name) => call(commands.findFiles(name, 1000)))))
|
|
.flat()
|
|
.filter((file) => names.includes(file.relPath.split("/").pop()!));
|
|
const configs = await call(commands.runConfigs());
|
|
const modules = new Set<string>();
|
|
for (const file of matches) {
|
|
// oxlint-disable-next-line no-await-in-loop -- keep read errors in candidate order and hold only one source text at a time
|
|
const text = await call(commands.fsReadText(file.path));
|
|
const sourcePackage = /^\s*package\s+([\w.]+)\s*[;\r\n]/m.exec(text)?.[1] ?? "";
|
|
if (sourcePackage === pkg) modules.add(jvmModuleDir(root ? relativePath(root, file.path) : file.relPath, configs));
|
|
}
|
|
return [...modules];
|
|
}
|
|
|
|
export async function resolveJavaModule(config: RunConfig): Promise<string> {
|
|
const module = await findJavaModule(config);
|
|
if (module === null)
|
|
throw new Error(tx`Cannot determine the module for main class '${parseJavaArgs(config.args).mainClass}'`);
|
|
return module;
|
|
}
|
|
|
|
/** Saves before resolving the module, for direct and delegated Run and Debug. */
|
|
export async function prepareJavaModule(config: RunConfig, saveAll?: () => Promise<void>, signal?: AbortSignal) {
|
|
signal?.throwIfAborted();
|
|
await saveAll?.();
|
|
signal?.throwIfAborted();
|
|
const module = await resolveJavaModule(config);
|
|
signal?.throwIfAborted();
|
|
return module;
|
|
}
|
|
|
|
/** Shared, cancellable build and classpath preparation for Run and Debug. */
|
|
export interface JavaPreparation {
|
|
request: RequestId;
|
|
signal: AbortSignal;
|
|
report?: (text: string, kind?: "system" | "stderr") => void;
|
|
/** Before launch build; unset reads the run configuration (default: automatic/incremental). */
|
|
policy?: BuildPolicy;
|
|
/** Saves open documents first, as IDEA's Before launch does. */
|
|
saveAll?: () => Promise<void>;
|
|
/** Follows the build while it runs (status bar, Build tool window); see `followLaunchBuild`. */
|
|
build?: JavaBuildFollower;
|
|
/**
|
|
* A debug launch: a module the Java language server serves is compiled by it, whose classes
|
|
* java-debug's HotSwap reloads, instead of the IDE's Java build.
|
|
*/
|
|
debug?: boolean;
|
|
}
|
|
|
|
/** Receives the events of a launch's build as it runs, then its outcome. */
|
|
export interface JavaBuildFollower {
|
|
onEvent(e: BuildEvent): void;
|
|
finish(status: "success" | "failed" | "cancelled"): void;
|
|
}
|
|
|
|
/** `javaResolveLaunch`, streaming the build's events to `build`, which then gets the outcome. */
|
|
export async function resolveJavaLaunch(
|
|
module: string,
|
|
test: boolean,
|
|
policy: BuildPolicy,
|
|
request: RequestId,
|
|
build?: JavaBuildFollower,
|
|
debug = false,
|
|
): Promise<JavaLaunchInfo> {
|
|
const channel = new Channel<BuildEvent>();
|
|
channel.onmessage = (e) => build?.onEvent(e);
|
|
try {
|
|
const info = await call(commands.javaResolveLaunch(module, test, debug, policy, request, channel));
|
|
build?.finish(info.build === "failed" ? "failed" : info.build === "cancelled" ? "cancelled" : "success");
|
|
return info;
|
|
} catch (e) {
|
|
build?.finish(isCancelled(e) ? "cancelled" : "failed");
|
|
throw e;
|
|
}
|
|
}
|
|
|
|
/** The build the launch would do: the configuration's policy, else incremental. */
|
|
export function buildPolicyOf(config: RunConfig): BuildPolicy {
|
|
return config.buildPolicy ?? "automatic";
|
|
}
|
|
|
|
/** A build stopped the launch: the message is ready for the console and the notification. */
|
|
export class JavaBuildFailedError extends Error {}
|
|
|
|
export async function prepareJavaLaunch(config: RunConfig, preparation: JavaPreparation) {
|
|
const { signal, report } = preparation;
|
|
const policy = preparation.policy ?? buildPolicyOf(config);
|
|
signal.throwIfAborted();
|
|
const parsed = parseJavaArgs(config.args);
|
|
if (!parsed.mainClass) throw new Error(`No main class in '${config.name}'`);
|
|
const target = parsed.mainClass === JUNIT_RUNNER_MAIN ? config.name : parsed.mainClass;
|
|
report?.(tx`Building and resolving the classpath of ${target}…` + "\n");
|
|
const started = performance.now();
|
|
const module = await prepareJavaModule(config, preparation.saveAll, signal);
|
|
const moduleMs = performance.now() - started;
|
|
const info = await resolveJavaLaunch(
|
|
module,
|
|
parsed.classpath === "test",
|
|
policy,
|
|
preparation.request,
|
|
preparation.build,
|
|
preparation.debug,
|
|
).catch((error: unknown) => {
|
|
if (error instanceof IpcError && error.data?.type === "javaBuildProblems") {
|
|
const problems = error.data.problems.join("; ");
|
|
throw new Error(
|
|
tx`Java module '${module || "."}' could not be imported because its build has errors: ${problems}. Fix them, then reload the Maven or Gradle project.`,
|
|
);
|
|
}
|
|
if (
|
|
error instanceof IpcError &&
|
|
error.kind !== "cancelled" &&
|
|
/^jdtls:.*(?:does not belong to any java project|references non-existing project|not a java project)/i.test(
|
|
error.message,
|
|
)
|
|
)
|
|
throw new Error(
|
|
tx`Java module '${module || "."}' is not imported. Wait for Java project import to finish. If it still fails, check the run configuration's module and whether it is included in the parent Maven or Gradle build, or open its folder as a project.`,
|
|
);
|
|
throw error;
|
|
});
|
|
signal.throwIfAborted();
|
|
console.info("Java launch preparation", { module, moduleMs, resolveMs: performance.now() - started - moduleMs });
|
|
const errors = formatCompileErrors(info);
|
|
if (errors) report?.(errors, "stderr");
|
|
// IDEA's default: a failed build (or one with compile errors) does not start the program;
|
|
// only "Build, no error check" continues with the last compiled classes.
|
|
if ((info.build === "failed" || info.build === "withErrors") && policy !== "makeAndContinueOnErrors") {
|
|
const reason =
|
|
info.build === "failed"
|
|
? tx`Build failed; '${config.name}' was not started.`
|
|
: tx`Build has compile errors; '${config.name}' was not started.`;
|
|
throw new JavaBuildFailedError(reason);
|
|
}
|
|
if (parsed.classpath && !info.classPaths.length)
|
|
throw new Error(tx("The classpath is empty: is the module imported by the Java language server?"));
|
|
let junit: JunitLaunch | null = null;
|
|
if (parsed.mainClass === JUNIT_RUNNER_MAIN) {
|
|
junit = await call(commands.javaJunitRunner(module, info.classPaths));
|
|
signal.throwIfAborted();
|
|
info.classPaths = junit.classPaths;
|
|
const list = junit.surefire.join(", ");
|
|
if (list) report?.(tx`Applying the Surefire configuration: ${list}` + "\n");
|
|
}
|
|
const resolved = resolveJavaCommand({ ...config, module }, info);
|
|
// As IDEA's MavenJUnitPatcher: the JVM gets what Surefire would give its fork; the configuration's own settings win.
|
|
if (junit) {
|
|
resolved.args = [...junit.vmArgs, ...resolved.args];
|
|
resolved.env = { ...junit.env, ...resolved.env };
|
|
if (junit.workingDirectory) resolved.cwd = junit.workingDirectory;
|
|
}
|
|
const project = useProject.getState().project;
|
|
if (resolved.cwd == null && project?.workspace) {
|
|
const path = /^(?:[A-Za-z]:)?\//.test(module) ? module : `${project.root}/${module}`;
|
|
const owner = projectFolder(project, path);
|
|
if (owner && owner.root !== project.root) resolved.cwd = path;
|
|
}
|
|
return { module, info, resolved };
|
|
}
|