diff --git a/src/features/run/applicationUpdate.test.ts b/src/features/run/applicationUpdate.test.ts index 441873e8f..73228cef9 100644 --- a/src/features/run/applicationUpdate.test.ts +++ b/src/features/run/applicationUpdate.test.ts @@ -47,7 +47,10 @@ vi.mock("@/platform/javaLaunch", async (original) => ({ ...(await original()), resolveJavaModule: async () => "app", })); -vi.mock("./buildUpdate", () => ({ runUpdateBuild: mocks.runBuild })); +vi.mock("./buildUpdate", async (original) => ({ + ...(await original()), + runUpdateBuild: mocks.runBuild, +})); vi.mock("./tomcat", () => ({ buildTomcatArtifact: mocks.build, syncTomcatOutputs: mocks.sync })); vi.mock("./store", () => ({ rerunConfig: (s: Pick) => mocks.state.configs.find((c) => c.id === s.config.id) ?? s.config, @@ -157,6 +160,27 @@ describe("Spring Boot application updates", () => { expect.objectContaining({ body: expect.stringContaining("Restart the application") }), ); }); + it("names the compile errors when the update's Java build fails", async () => { + mocks.resolve.mockResolvedValueOnce({ + status: "ok", + data: { + build: "withErrors", + classPaths: [], + pathListSeparator: ":", + errors: [{ path: "/p/app/src/A.java", line: 1, column: 1, message: "illegal character: '\\ufeff'" }], + errorCount: 1, + hints: [], + }, + } as never); + await updateTomcat(boot, "classes"); + expect(mocks.runBuild).not.toHaveBeenCalled(); + expect(mocks.notify).toHaveBeenCalledWith( + expect.objectContaining({ + level: "error", + body: "Application update build failed\n/p/app/src/A.java:1:1: error: illegal character: '\\ufeff'", + }), + ); + }); it("never publishes resources after a failed build", async () => { mocks.runBuild.mockRejectedValueOnce(new Error("failed")); await updateTomcat(boot, "resources"); diff --git a/src/features/run/applicationUpdate.ts b/src/features/run/applicationUpdate.ts index d6c969c2b..0895f81d7 100644 --- a/src/features/run/applicationUpdate.ts +++ b/src/features/run/applicationUpdate.ts @@ -12,7 +12,7 @@ import { } from "@/workbench/contributions"; import { showContextMenu } from "@/ui"; import { buildTomcatArtifact, syncTomcatOutputs } from "./tomcat"; -import { runUpdateBuild } from "./buildUpdate"; +import { runUpdateBuild, updateBuildError } from "./buildUpdate"; import { rerunConfig, startRun, stopSession, useRun, waitForExit, type RunSession } from "./store"; import { isUpdatable, updateAllowed, type UpdateMode } from "./updatePolicies"; @@ -51,7 +51,7 @@ async function updateSpringBoot(config: RunConfig, mode: UpdateMode, debugging: ), ); if (info.build === "failed" || info.build === "withErrors" || info.build === "cancelled") - throw new Error(tx("Application update build failed")); + 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)); @@ -106,7 +106,12 @@ export async function updateApplication(session: UpdateSession, mode: string): P } if (!session.debug) useRun.setState({ activeSession: session.id }); } catch (e) { - notifications().notify({ group: "run", level: "error", title: "Application update failed", body: String(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)) })); diff --git a/src/features/run/buildUpdate.test.ts b/src/features/run/buildUpdate.test.ts new file mode 100644 index 000000000..c3e057111 --- /dev/null +++ b/src/features/run/buildUpdate.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it, vi } from "vitest"; + +vi.mock("./store", () => ({ startRun: vi.fn() })); +import { compileErrorCollector } from "./buildUpdate"; + +describe("compileErrorCollector", () => { + it("keeps the compiler errors of Maven, javac and Kotlin output without colour codes", () => { + const errors = compileErrorCollector(); + errors.add("[INFO] Compiling 3 source files with javac [debug release 17] to target/classes"); + errors.add("\u001b[1;31m[ERROR] /p/src/main/java/a/XxxServiceImpl.java:[1,1] 非法字符: '\\ufeff'\u001b[m"); + errors.add("[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.13.0:compile"); + // Maven's failure summary repeats the error. + errors.add("[ERROR] /p/src/main/java/a/XxxServiceImpl.java:[1,1] 非法字符: '\\ufeff'"); + errors.add("/p/src/main/java/a/B.java:12: error: ';' expected\n int x = 1\n"); + errors.add("e: file:///p/src/main/kotlin/a/C.kt:3:5 Unresolved reference: foo"); + expect(errors.lines()).toEqual([ + "[ERROR] /p/src/main/java/a/XxxServiceImpl.java:[1,1] 非法字符: '\\ufeff'", + "/p/src/main/java/a/B.java:12: error: ';' expected", + "e: file:///p/src/main/kotlin/a/C.kt:3:5 Unresolved reference: foo", + ]); + }); + + it("keeps the first ten and counts the rest", () => { + const errors = compileErrorCollector(); + for (let i = 1; i <= 13; i++) errors.add(`[ERROR] /p/A.java:[${i},1] cannot find symbol`); + const lines = errors.lines(); + expect(lines).toHaveLength(11); + expect(lines[9]).toBe("[ERROR] /p/A.java:[10,1] cannot find symbol"); + expect(lines[10]).toBe("… and 3 more"); + }); +}); diff --git a/src/features/run/buildUpdate.ts b/src/features/run/buildUpdate.ts index 759050d95..e002d9e13 100644 --- a/src/features/run/buildUpdate.ts +++ b/src/features/run/buildUpdate.ts @@ -1,15 +1,59 @@ import { tx } from "@/platform/i18n"; -import type { RunConfig } from "@/platform/ipc"; +import type { JavaLaunchInfo, RunConfig } from "@/platform/ipc"; +import { formatCompileErrors } from "@/platform/javaLaunch"; +import { stripAnsi } from "@/ui/ansi"; import { startRun } from "./store"; +const MAX_ERRORS = 10; + +/** + * A compiler error line of a Maven or Gradle build: Maven's `[ERROR] /p/A.java:[1,1] …`, + * javac's `/p/A.java:1: error: …` and Kotlin's `e: file:///p/A.kt:1:1 …`. + */ +const COMPILE_ERROR = [ + /^\[ERROR\] .+\.(?:java|kt|groovy|scala):\[\d+,\d+\]/, + /^.+\.(?:java|groovy|scala):\d+: error: /, + /^e: .+\.kts?:\d+:\d+ /, +]; + +/** Collects the distinct compiler errors of a build's output, without colour codes; `lines()` keeps the first `MAX_ERRORS`. */ +export function compileErrorCollector() { + const errors: string[] = []; + // Maven repeats each compiler error in its failure summary. + const seen = new Set(); + return { + add(text: string) { + for (const raw of text.split("\n")) { + const line = stripAnsi(raw).trimEnd(); + if (seen.has(line) || !COMPILE_ERROR.some((re) => re.test(line))) continue; + seen.add(line); + if (seen.size <= MAX_ERRORS) errors.push(line); + } + }, + lines: () => (seen.size > MAX_ERRORS ? [...errors, `… and ${seen.size - MAX_ERRORS} more`] : errors), + }; +} + +function failure(details: readonly string[]): Error { + const title = tx("Application update build failed"); + return new Error(details.length ? `${title}\n${details.join("\n")}` : title); +} + export async function runUpdateBuild(build: RunConfig): Promise { let finish!: (ok: boolean) => void; const exited = new Promise((resolve) => { finish = resolve; }); + const errors = compileErrorCollector(); const session = await startRun(build, undefined, undefined, { + onLine: errors.add, onExit: (code, stopped) => finish(code === 0 && !stopped), }); - if (!session || session.status === "failed" || !(await exited)) - throw new Error(tx("Application update build failed")); + if (!session || session.status === "failed" || !(await exited)) throw failure(errors.lines()); +} + +/** The error for an update whose Java build failed, with the compiler's errors so the user sees what to fix. */ +export function updateBuildError(info: JavaLaunchInfo): Error { + const errors = formatCompileErrors(info).trimEnd(); + return failure(errors ? errors.split("\n") : []); } diff --git a/src/features/run/tomcat.ts b/src/features/run/tomcat.ts index fa7f0f592..65556532c 100644 --- a/src/features/run/tomcat.ts +++ b/src/features/run/tomcat.ts @@ -1,8 +1,7 @@ -import { tx } from "@/platform/i18n"; import { call, commands, nextRequestId, type RunConfig } from "@/platform/ipc"; import type { RunConfigTypeContribution } from "@/workbench/contributions"; import { updatePolicyDefaults, updatePolicyFields } from "./updatePolicies"; -import { runUpdateBuild } from "./buildUpdate"; +import { runUpdateBuild, updateBuildError } from "./buildUpdate"; const validatePort = (value: string) => /^\d+$/.test(value) && Number(value) > 0 && Number(value) <= 65535 ? null : "Port must be between 1 and 65535"; @@ -167,7 +166,7 @@ export async function syncTomcatOutputs(config: RunConfig, resourcesOnly: boolea ); if (!info) return false; if (info.build === "failed" || info.build === "withErrors" || info.build === "cancelled") - throw new Error(tx("Application update build failed")); + throw updateBuildError(info); return call(commands.runTomcatSync(config, artifact.module, info.classPaths, resourcesOnly)); } diff --git a/src/ui/Feedback.module.css b/src/ui/Feedback.module.css index 8b10dddd0..6cda28447 100644 --- a/src/ui/Feedback.module.css +++ b/src/ui/Feedback.module.css @@ -158,6 +158,8 @@ .toastBody { color: var(--fg-secondary); overflow-wrap: anywhere; + /* Bodies list one item per line (compile errors, failed paths). */ + white-space: pre-line; /* A huge message (stack trace, build output) scrolls inside the balloon instead of growing past the window and pushing the close button off-screen. */ max-height: 40vh;