From 0d6ce5b01665021db928d057108cbfb7bb0bf1a2 Mon Sep 17 00:00:00 2001 From: Alex Abashev Date: Mon, 23 Nov 2026 00:29:26 +0300 Subject: [PATCH 1/5] Find the java of the IDE's runtime, the project SDK and the IDE's JDKs The IntelliJ plugin starts the formatter's JVM on the IDE's own runtime and nothing else. FormatterJdk is a JDK that a project can name for it instead: the IDE's runtime, whichever SDK the project has, or a JDK registered in the IDE, by name. FormatterJdks finds the java executable and the Java version each stands for, and says why one cannot run the formatter: it is older than Java 21, which the formatter is compiled for, the IDE has no JDK of that name, the project has no SDK, or there is no java to start in it, as for a JDK in WSL. Nothing asks for them yet. The settings page lists them and FormatterSelection resolves the chosen one once the formatter can run in more ways than a JVM on the IDE's runtime (#223). --- .../javaformat/intellij/FormatterJdk.java | 69 ++++++++ .../javaformat/intellij/FormatterJdks.java | 158 ++++++++++++++++++ .../intellij/FormatterJdksTest.java | 152 +++++++++++++++++ .../javaformat/intellij/TestJdks.java | 59 +++++++ 4 files changed, 438 insertions(+) create mode 100644 open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterJdk.java create mode 100644 open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterJdks.java create mode 100644 open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterJdksTest.java create mode 100644 open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/TestJdks.java diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterJdk.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterJdk.java new file mode 100644 index 000000000..2ccef3319 --- /dev/null +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterJdk.java @@ -0,0 +1,69 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.palantir.javaformat.intellij; + +import java.nio.file.Path; +import org.jspecify.annotations.Nullable; + +/** The JDK a project names for the formatter's own JVM. {@link FormatterJdks} finds the java it stands for. */ +sealed interface FormatterJdk { + + /** What a JDK comes to on this machine, in this project. */ + sealed interface Resolved {} + + /** java: the executable. javaVersion: the version of Java it runs, such as 21. */ + record Usable(Path java, int javaVersion) implements Resolved {} + + /** reason: a clause that says why, such as "the project has no SDK". */ + record Unusable(String reason) implements Resolved {} + + /** The runtime the IDE itself runs on: always there, and always recent enough for the formatter. */ + record IdeRuntime() implements FormatterJdk { + @Override + public @Nullable String stored() { + return null; + } + } + + /** Whichever SDK the project has, as it changes. */ + record ProjectSdk() implements FormatterJdk { + @Override + public String stored() { + return PROJECT_SDK; + } + } + + /** A JDK registered in the IDE, by the name it has there. */ + record Named(String name) implements FormatterJdk { + @Override + public String stored() { + return name; + } + } + + // Not a name a JDK can have by accident: the IDE's own settings mark their special values with '#' too. + String PROJECT_SDK = "#PROJECT_SDK"; + + /** What .idea/open-java-format.xml holds for this JDK; nothing for the IDE's runtime, which is the default. */ + @Nullable + String stored(); + + static FormatterJdk parse(@Nullable String stored) { + if (stored == null || stored.isBlank()) { + return new IdeRuntime(); + } + return stored.equals(PROJECT_SDK) ? new ProjectSdk() : new Named(stored); + } +} diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterJdks.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterJdks.java new file mode 100644 index 000000000..794859738 --- /dev/null +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterJdks.java @@ -0,0 +1,158 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.palantir.javaformat.intellij; + +import com.intellij.openapi.project.Project; +import com.intellij.openapi.projectRoots.JavaSdk; +import com.intellij.openapi.projectRoots.ProjectJdkTable; +import com.intellij.openapi.projectRoots.Sdk; +import com.intellij.openapi.roots.ProjectRootManager; +import com.intellij.openapi.util.SystemInfo; +import com.intellij.util.lang.JavaVersion; +import com.palantir.javaformat.intellij.FormatterJdk.IdeRuntime; +import com.palantir.javaformat.intellij.FormatterJdk.Named; +import com.palantir.javaformat.intellij.FormatterJdk.ProjectSdk; +import com.palantir.javaformat.intellij.FormatterJdk.Resolved; +import com.palantir.javaformat.intellij.FormatterJdk.Unusable; +import com.palantir.javaformat.intellij.FormatterJdk.Usable; +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.Path; +import java.util.List; +import java.util.OptionalInt; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.jspecify.annotations.Nullable; + +/** The JDKs the formatter's own JVM can run on: the IDE's runtime, the project SDK and the JDKs the IDE knows. */ +final class FormatterJdks { + + /** The formatter is compiled for Java 21. */ + static final int MINIMUM_JAVA = 21; + + private FormatterJdks() {} + + /** The runtime the IDE runs on. Every IDE this plugin supports runs on Java 21 or later. */ + static Usable ideRuntime() { + return new Usable( + javaIn(Path.of(System.getProperty("java.home"))), + Runtime.version().feature()); + } + + /** What the settings page lists: the IDE's runtime, the project SDK, and the JDKs by name. */ + static List choices() { + return Stream.concat( + Stream.of(new IdeRuntime(), new ProjectSdk()), + ProjectJdkTable.getInstance().getSdksOfType(JavaSdk.getInstance()).stream() + .map(Sdk::getName) + .sorted(String.CASE_INSENSITIVE_ORDER) + .map(Named::new)) + .toList(); + } + + /** A line of that list. detail: what the name stands for, shown beside it in grey. */ + record Label(String name, String detail) {} + + static Label label(Project project, FormatterJdk jdk) { + return switch (jdk) { + case IdeRuntime ideRuntime -> new Label("IDE runtime", "Java " + System.getProperty("java.version")); + case ProjectSdk projectSdk -> { + var sdk = projectSdk(project); + yield new Label( + "Project SDK", + sdk == null + ? "none" + : Stream.of(sdk.getName(), java(sdk)) + .filter(part -> !part.isEmpty()) + .collect(Collectors.joining(", "))); + } + case Named named -> { + var sdk = ProjectJdkTable.getInstance().findJdk(named.name()); + yield new Label(named.name(), sdk == null ? "not found" : java(sdk)); + } + }; + } + + /** + * The java a JDK stands for. It is looked up for every file formatted in a JVM of its own, so that a project SDK + * that changes, or a JDK that is removed, shows at once. + */ + static Resolved resolve(Project project, FormatterJdk jdk) { + return switch (jdk) { + case IdeRuntime ideRuntime -> ideRuntime(); + case ProjectSdk projectSdk -> { + var sdk = projectSdk(project); + yield sdk == null ? new Unusable("the project has no SDK") : resolve(sdk); + } + case Named named -> { + var sdk = ProjectJdkTable.getInstance().findJdk(named.name()); + yield sdk == null ? new Unusable("there is no JDK named " + named.name()) : resolve(sdk); + } + }; + } + + private static Resolved resolve(Sdk sdk) { + // A project SDK can be one for another language. + if (!(sdk.getSdkType() instanceof JavaSdk)) { + return new Unusable(sdk.getName() + " is not a JDK"); + } + var javaVersion = javaVersion(sdk); + if (javaVersion.isEmpty()) { + return new Unusable("the Java version of " + sdk.getName() + " is not known"); + } + if (javaVersion.getAsInt() < MINIMUM_JAVA) { + return new Unusable(sdk.getName() + " is Java " + javaVersion.getAsInt() + ", and the formatter needs Java " + + MINIMUM_JAVA + " or later"); + } + var java = executable(sdk); + // Not on this machine, for one: a JDK in WSL or in a container has no java that the IDE can start. + if (java == null || !Files.isExecutable(java)) { + return new Unusable(sdk.getName() + " has no java to run in " + sdk.getHomePath()); + } + return new Usable(java, javaVersion.getAsInt()); + } + + private static @Nullable Sdk projectSdk(Project project) { + return ProjectRootManager.getInstance(project).getProjectSdk(); + } + + private static OptionalInt javaVersion(Sdk sdk) { + var versionString = sdk.getVersionString(); + var version = versionString == null ? null : JavaVersion.tryParse(versionString); + return version == null ? OptionalInt.empty() : OptionalInt.of(version.feature); + } + + /** "Java 21", or nothing for a JDK whose version is not known. */ + private static String java(Sdk sdk) { + var javaVersion = javaVersion(sdk); + return javaVersion.isPresent() ? "Java " + javaVersion.getAsInt() : ""; + } + + private static @Nullable Path executable(Sdk sdk) { + var home = sdk.getHomePath(); + if (home == null) { + return null; + } + try { + return javaIn(Path.of(home)); + } catch (InvalidPathException e) { + return null; + } + } + + private static Path javaIn(Path home) { + return home.resolve("bin").resolve(SystemInfo.isWindows ? "java.exe" : "java"); + } +} diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterJdksTest.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterJdksTest.java new file mode 100644 index 000000000..71cee6972 --- /dev/null +++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterJdksTest.java @@ -0,0 +1,152 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.palantir.javaformat.intellij; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.intellij.openapi.Disposable; +import com.intellij.testFramework.fixtures.DefaultLightProjectDescriptor; +import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory; +import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture; +import com.intellij.testFramework.fixtures.JavaTestFixtureFactory; +import com.palantir.javaformat.intellij.FormatterJdk.IdeRuntime; +import com.palantir.javaformat.intellij.FormatterJdk.Named; +import com.palantir.javaformat.intellij.FormatterJdk.ProjectSdk; +import com.palantir.javaformat.intellij.FormatterJdk.Unusable; +import com.palantir.javaformat.intellij.FormatterJdk.Usable; +import com.palantir.javaformat.intellij.FormatterJdks.Label; +import java.nio.file.Path; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +final class FormatterJdksTest { + + private static final Path RUNNING_JAVA = Path.of(System.getProperty("java.home"), "bin", "java"); + private static final int RUNNING_VERSION = Runtime.version().feature(); + + @TempDir + private Path dir; + + private JavaCodeInsightTestFixture fixture; + private Disposable untilTheTestEnds; + + @BeforeEach + void setUp() throws Exception { + var projectBuilder = IdeaTestFixtureFactory.getFixtureFactory() + .createLightFixtureBuilder( + new DefaultLightProjectDescriptor(), getClass().getName()); + fixture = JavaTestFixtureFactory.getFixtureFactory().createCodeInsightFixture(projectBuilder.getFixture()); + fixture.setUp(); + untilTheTestEnds = fixture.getTestRootDisposable(); + } + + @AfterEach + void tearDown() throws Exception { + fixture.tearDown(); + } + + @Test + void runsOnTheIdesRuntime() { + assertThat(FormatterJdks.resolve(fixture.getProject(), new IdeRuntime())) + .isEqualTo(new Usable(RUNNING_JAVA, RUNNING_VERSION)); + assertThat(FormatterJdks.label(fixture.getProject(), new IdeRuntime())) + .isEqualTo(new Label("IDE runtime", "Java " + System.getProperty("java.version"))); + } + + @Test + void runsOnAJdkOfTheIde() { + TestJdks.running("this-jdk", untilTheTestEnds); + + assertThat(FormatterJdks.resolve(fixture.getProject(), new Named("this-jdk"))) + .isEqualTo(new Usable(RUNNING_JAVA, RUNNING_VERSION)); + assertThat(FormatterJdks.label(fixture.getProject(), new Named("this-jdk"))) + .isEqualTo(new Label("this-jdk", "Java " + RUNNING_VERSION)); + } + + @Test + void runsOnTheProjectSdk() { + TestJdks.setProjectSdk(fixture.getProject(), TestJdks.running("this-jdk", untilTheTestEnds), untilTheTestEnds); + + assertThat(FormatterJdks.resolve(fixture.getProject(), new ProjectSdk())) + .isEqualTo(new Usable(RUNNING_JAVA, RUNNING_VERSION)); + assertThat(FormatterJdks.label(fixture.getProject(), new ProjectSdk())) + .isEqualTo(new Label("Project SDK", "this-jdk, Java " + RUNNING_VERSION)); + } + + @Test + void doesNotRunOnTheSdkOfAProjectWithoutOne() { + TestJdks.setProjectSdk(fixture.getProject(), null, untilTheTestEnds); + + assertThat(FormatterJdks.resolve(fixture.getProject(), new ProjectSdk())) + .isEqualTo(new Unusable("the project has no SDK")); + assertThat(FormatterJdks.label(fixture.getProject(), new ProjectSdk())) + .isEqualTo(new Label("Project SDK", "none")); + } + + @Test + void doesNotRunOnAJdkOlderThanTheFormatterNeeds() { + // The formatter is compiled for Java 21, and a project SDK can be any version. + TestJdks.setProjectSdk( + fixture.getProject(), + TestJdks.register("temurin-17", dir, "Eclipse Temurin 17.0.9", untilTheTestEnds), + untilTheTestEnds); + var tooOld = new Unusable("temurin-17 is Java 17, and the formatter needs Java 21 or later"); + + assertThat(FormatterJdks.resolve(fixture.getProject(), new Named("temurin-17"))) + .isEqualTo(tooOld); + assertThat(FormatterJdks.resolve(fixture.getProject(), new ProjectSdk())) + .isEqualTo(tooOld); + assertThat(FormatterJdks.label(fixture.getProject(), new Named("temurin-17"))) + .isEqualTo(new Label("temurin-17", "Java 17")); + } + + @Test + void doesNotRunOnAJdkTheIdeDoesNotHave() { + assertThat(FormatterJdks.resolve(fixture.getProject(), new Named("gone"))) + .isEqualTo(new Unusable("there is no JDK named gone")); + assertThat(FormatterJdks.label(fixture.getProject(), new Named("gone"))) + .isEqualTo(new Label("gone", "not found")); + } + + @Test + void doesNotRunOnAJdkWithoutAJavaToStart() { + // A JDK whose directory is gone, or one in WSL or a container. + TestJdks.register("moved", dir, "Eclipse Temurin 25", untilTheTestEnds); + + assertThat(FormatterJdks.resolve(fixture.getProject(), new Named("moved"))) + .isEqualTo(new Unusable("moved has no java to run in " + dir)); + } + + @Test + void doesNotRunOnAJdkOfAnUnknownVersion() { + TestJdks.register("odd", dir, "a JDK", untilTheTestEnds); + + assertThat(FormatterJdks.resolve(fixture.getProject(), new Named("odd"))) + .isEqualTo(new Unusable("the Java version of odd is not known")); + assertThat(FormatterJdks.label(fixture.getProject(), new Named("odd"))).isEqualTo(new Label("odd", "")); + } + + @Test + void listsTheIdesRuntimeTheProjectSdkAndTheJdksByName() { + TestJdks.register("temurin-25", dir, "Eclipse Temurin 25", untilTheTestEnds); + TestJdks.register("Corretto 21", dir, "Amazon Corretto 21.0.3", untilTheTestEnds); + + assertThat(FormatterJdks.choices()) + .startsWith(new IdeRuntime(), new ProjectSdk()) + .containsSubsequence(new Named("Corretto 21"), new Named("temurin-25")); + } +} diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/TestJdks.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/TestJdks.java new file mode 100644 index 000000000..b94a27917 --- /dev/null +++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/TestJdks.java @@ -0,0 +1,59 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.palantir.javaformat.intellij; + +import com.intellij.openapi.Disposable; +import com.intellij.openapi.application.WriteAction; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.projectRoots.JavaSdk; +import com.intellij.openapi.projectRoots.ProjectJdkTable; +import com.intellij.openapi.projectRoots.Sdk; +import com.intellij.openapi.roots.ProjectRootManager; +import com.intellij.openapi.util.Disposer; +import java.nio.file.Path; +import org.jspecify.annotations.Nullable; + +/** JDKs for a test to give the IDE, which lose them again when the test ends. */ +final class TestJdks { + + private TestJdks() {} + + /** The JDK the tests run on, under a name of the test's own. */ + static Sdk running(String name, Disposable untilDisposed) { + return register( + name, Path.of(System.getProperty("java.home")), System.getProperty("java.version"), untilDisposed); + } + + /** A JDK as the IDE lists it, which need not be on disk: versionString is what the IDE read from it. */ + static Sdk register(String name, Path home, String versionString, Disposable untilDisposed) { + return WriteAction.computeAndWait(() -> { + var sdk = ProjectJdkTable.getInstance().createSdk(name, JavaSdk.getInstance()); + var modificator = sdk.getSdkModificator(); + modificator.setHomePath(home.toString()); + modificator.setVersionString(versionString); + modificator.commitChanges(); + ProjectJdkTable.getInstance().addJdk(sdk, untilDisposed); + return sdk; + }); + } + + /** Light projects outlive a test, so the SDK the project had comes back with the test's end. */ + static void setProjectSdk(Project project, @Nullable Sdk sdk, Disposable untilDisposed) { + var roots = ProjectRootManager.getInstance(project); + var before = roots.getProjectSdk(); + WriteAction.runAndWait(() -> roots.setProjectSdk(sdk)); + Disposer.register(untilDisposed, () -> WriteAction.runAndWait(() -> roots.setProjectSdk(before))); + } +} From 0c4624acdc9aa1be6293cc52b0daa2190848e8f2 Mon Sep 17 00:00:00 2001 From: Alex Abashev Date: Mon, 23 Nov 2026 00:29:44 +0300 Subject: [PATCH 2/5] Load the formatter into the IDE's own JVM, apart from the IDE The IntelliJ plugin starts a process for every Reformat and every Optimize imports: 0.3 s to 1 s for a JVM, where the formatter, once loaded and warm, takes 124 ms on a file of 4,026 lines and 9 ms to fix its imports (#223). This is what loads it into the IDE's JVM. Nothing calls it yet. The formatter parses with javac's own classes, in packages that jdk.compiler exports to nobody, and the IDE's JVM is already running. IntelliJ IDEA starts it with --add-opens=java.base/java.lang=ALL-UNNAMED, in 2024.2.6, the oldest IDE the plugin supports, and in 2026.3. With java.lang open JavacAccess can call Module.implAddExports, the method --add-exports ends in: for the formatter's class loader alone, so that nothing else in the IDE reaches javac through it, and nobody edits VM options. The method is not public API, so JavacAccess first says whether it is there to call, and why not if it is not. FormatterClassLoader keeps the formatter apart from the IDE. Its parent is the JDK's platform class loader, which finds javac and nothing of the IDE: the formatter's jars are everything it runs with in a JVM of its own, and the IDE has other versions of the same libraries. Only the types the plugin and the formatter exchange come from the plugin, the classes of open-java-format-spi and Guava, which their signatures name. InProcessFormatters keeps a formatter loaded for as long as its jars stay the same, and is asked for every file, so that a jar rebuilt in place formats the next one, as in a JVM started for it. InProcessFormatterService leaves a file with a syntax error alone, as the formatters that run the command line do: the formatter itself throws, and "Optimize imports on the fly" would show that on every highlighting pass. What it cannot format in this JVM it hands to the service it is given for that: a file the formatter fails on with an Error, a stack overflow for one, and every file once the formatter turns out not to load or link here. The IDE process is the faster way, never the only one. The JVM of the tests has javac exported to everything, as the build compiles the formatter, so JavacAccessTest starts JVMs of its own: one with the IDE's flag alone, where the formatter gives the command line's file and javac stays unexported to the plugin; one with the exports a user of google-java-format adds by hand; and one with neither, which says why it cannot format. --- .../intellij/FormatterClassLoader.java | 68 +++++ .../intellij/FormatterProvider.java | 4 +- .../intellij/InProcessFormatterService.java | 128 +++++++++ .../intellij/InProcessFormatters.java | 132 +++++++++ .../javaformat/intellij/JavacAccess.java | 122 ++++++++ .../intellij/SuppressForbidden.java | 27 ++ .../intellij/FormatterClassLoaderTest.java | 74 +++++ .../intellij/InProcessFormatterProbe.java | 88 ++++++ .../intellij/InProcessFormattersTest.java | 260 ++++++++++++++++++ .../javaformat/intellij/JavacAccessTest.java | 147 ++++++++++ .../intellij/RecordingFormatterService.java | 53 ++++ .../javaformat/intellij/TestClassPath.java | 39 +++ 12 files changed, 1140 insertions(+), 2 deletions(-) create mode 100644 open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterClassLoader.java create mode 100644 open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/InProcessFormatterService.java create mode 100644 open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/InProcessFormatters.java create mode 100644 open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/JavacAccess.java create mode 100644 open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/SuppressForbidden.java create mode 100644 open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterClassLoaderTest.java create mode 100644 open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/InProcessFormatterProbe.java create mode 100644 open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/InProcessFormattersTest.java create mode 100644 open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/JavacAccessTest.java create mode 100644 open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/RecordingFormatterService.java create mode 100644 open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/TestClassPath.java diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterClassLoader.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterClassLoader.java new file mode 100644 index 000000000..77ab6839e --- /dev/null +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterClassLoader.java @@ -0,0 +1,68 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.palantir.javaformat.intellij; + +import com.palantir.javaformat.java.FormatterDiagnostic; +import com.palantir.javaformat.java.FormatterException; +import com.palantir.javaformat.java.FormatterService; +import com.palantir.javaformat.java.JavaFormatterOptions; +import com.palantir.javaformat.java.Replacement; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.Set; + +/** + * Loads the formatter from its jars into the IDE's JVM, apart from the IDE. + * + *

Its parent is the JDK's platform class loader, which finds the JDK, javac included, and nothing of the IDE: the + * formatter's jars are everything it runs with in a JVM of its own, and the IDE has other versions of the same + * libraries. Only the types the plugin and the formatter exchange come from the plugin: the service interface with + * the types it names, and Guava, whose {@code ImmutableList} and {@code Range} are in its signatures. The copies of + * those in the formatter's jars are never loaded. + */ +final class FormatterClassLoader extends URLClassLoader { + + static { + registerAsParallelCapable(); + } + + /** The classes of open-java-format-spi. They share a package with the formatter's own, so they go by name. */ + private static final Set SPI = Set.of( + FormatterDiagnostic.class.getName(), + FormatterException.class.getName(), + FormatterService.class.getName(), + JavaFormatterOptions.class.getName(), + Replacement.class.getName()); + + private final ClassLoader plugin; + + FormatterClassLoader(URL[] formatterJars, ClassLoader plugin) { + super("open-java-format", formatterJars, ClassLoader.getPlatformClassLoader()); + this.plugin = plugin; + } + + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + return isShared(name) ? plugin.loadClass(name) : super.loadClass(name, resolve); + } + + static boolean isShared(String className) { + if (className.startsWith("com.google.common.")) { + return true; + } + var nested = className.indexOf('$'); + return SPI.contains(nested < 0 ? className : className.substring(0, nested)); + } +} diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterProvider.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterProvider.java index bca69fe16..f21e9b47d 100644 --- a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterProvider.java +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterProvider.java @@ -94,8 +94,8 @@ private static List getProvidedImplementationUrls(List implementation return implementationClasspath.stream().map(Path::of).toList(); } - private static List getBundledImplementationUrls() { - // Load from the jars bundled with the plugin. + /** The jars of the formatter bundled with the plugin, in the directory impl next to the plugin's own lib. */ + static List getBundledImplementationUrls() { Path implDir = ofNullable(FormattingService.EP_NAME.findExtension(PalantirJavaFormatFormattingService.class)) .flatMap(PalantirJavaFormatFormattingService::getPluginDescriptor) .map(PluginDescriptor::getPluginPath) diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/InProcessFormatterService.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/InProcessFormatterService.java new file mode 100644 index 000000000..41f261f6d --- /dev/null +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/InProcessFormatterService.java @@ -0,0 +1,128 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.palantir.javaformat.intellij; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Range; +import com.palantir.javaformat.java.FormatterException; +import com.palantir.javaformat.java.FormatterService; +import com.palantir.javaformat.java.Replacement; +import java.nio.file.Path; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; + +/** + * The formatter in the IDE's own JVM, for a project that formats with these jars. + * + *

It leaves a file with a syntax error alone, as the formatters that run in a process of their own do. And what it + * cannot format here it formats in a JVM of its own: a file that the formatter fails on with an {@code Error}, and + * every file once the formatter turns out not to load or link in this JVM. The IDE process is the faster way, never + * the only one. + */ +final class InProcessFormatterService implements FormatterService { + + private final InProcessFormatters formatters; + private final List jars; + private final FormatterService separateJvm; + private final Consumer onFailure; + + /** + * separateJvm: formats what this JVM cannot. onFailure: told why, each time a file goes there for a reason that + * {@link InProcessFormatters#unavailable} did not give beforehand. + */ + InProcessFormatterService( + InProcessFormatters formatters, + List jars, + FormatterService separateJvm, + Consumer onFailure) { + this.formatters = formatters; + this.jars = jars; + this.separateJvm = separateJvm; + this.onFailure = onFailure; + } + + @Override + @SuppressForbidden(reason = "FormatterService, kept in the SPI for compatibility, returns ImmutableList") + public ImmutableList getFormatReplacements(String input, Collection> ranges) + throws FormatterException { + return run(formatter -> formatter.getFormatReplacements(input, ranges), ImmutableList.of()); + } + + @Override + public String formatSourceReflowStringsAndFixImports(String input) throws FormatterException { + return run(formatter -> formatter.formatSourceReflowStringsAndFixImports(input), input); + } + + @Override + public String fixImports(String input) throws FormatterException { + return run(formatter -> formatter.fixImports(input), input); + } + + private interface Call { + T with(FormatterService formatter) throws FormatterException; + } + + /** unparsed: the answer for a file with a syntax error, which is to change nothing. */ + private T run(Call call, T unparsed) throws FormatterException { + // A project can still hold this service after the formatter failed for another, or in another thread. + if (formatters.unavailable().isPresent()) { + return call.with(separateJvm); + } + FormatterService formatter; + try { + // For every file, so that a jar rebuilt in place formats the next one, as in a JVM started for it. + formatter = formatters.load(jars); + } catch (IllegalStateException e) { + onFailure.accept(e); + return call.with(separateJvm); + } + var thread = Thread.currentThread(); + var contextClassLoader = thread.getContextClassLoader(); + // The IDE's, on its threads: a library that looks its services up there would find the IDE's. + thread.setContextClassLoader(formatter.getClass().getClassLoader()); + try { + return call.with(formatter); + } catch (FormatterException e) { + if (isSyntaxError(e)) { + return unparsed; + } + throw e; + } catch (Error e) { + // Out of memory, or a JVM that is breaking down, is the IDE's to deal with. + if (e instanceof VirtualMachineError && !(e instanceof StackOverflowError)) { + throw e; + } + // A process of the formatter's own exits with any other, where here it would pass every catch of the + // plugin: javac's Abort and its assertions are Errors too. And the file may well format there: the main + // thread of a JVM has a deeper stack than the IDE's threads. + if (e instanceof LinkageError linkageError) { + formatters.failedToLink(linkageError); + } + onFailure.accept(e); + } finally { + thread.setContextClassLoader(contextClassLoader); + } + return call.with(separateJvm); + } + + /** + * What the command line prints as {@code ::: error:}, which the formatters that run it take + * for a syntax error and answer by leaving the file alone: a file is rarely free of them while it is typed in. + */ + private static boolean isSyntaxError(FormatterException e) { + return e.diagnostics().stream().anyMatch(diagnostic -> diagnostic.line() >= 0 && diagnostic.column() >= 0); + } +} diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/InProcessFormatters.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/InProcessFormatters.java new file mode 100644 index 000000000..d79f1d3eb --- /dev/null +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/InProcessFormatters.java @@ -0,0 +1,132 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.palantir.javaformat.intellij; + +import com.palantir.javaformat.java.FormatterService; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.ServiceConfigurationError; +import java.util.ServiceLoader; +import java.util.concurrent.atomic.AtomicReference; +import org.jspecify.annotations.Nullable; + +/** + * The formatters loaded into a JVM, which in the IDE is the IDE's own: each from its jars, by a + * {@link FormatterClassLoader}. + * + *

A formatter stays loaded for as long as its jars stay the same, for every project that formats with them: the + * first file pays for loading it and for the JIT compiler, and the files after it for neither. + */ +final class InProcessFormatters { + + /** The formatters of the IDE. */ + static final InProcessFormatters IDE = new InProcessFormatters(); + + // The formatter versions of the projects open at once. One that falls out is left to the garbage collector rather + // than closed: a file can still be formatting in it. + private static final int KEPT = 4; + + private final Map, FormatterService> loaded = new LinkedHashMap<>(KEPT, 0.75f, true) { + @Override + protected boolean removeEldestEntry(Map.Entry, FormatterService> eldest) { + return size() > KEPT; + } + }; + + // Why this JVM gave up on running the formatter, which it does for as long as it runs. A formatter that does not + // load or link here would fail on every file, and a JVM of its own formats them all. + private final AtomicReference<@Nullable String> failure = new AtomicReference<>(); + + /** + * Why the formatter cannot run in this JVM, if it cannot: javac is out of reach, or a formatter failed to load or + * to link here. A clause to put after "Not available:". + */ + Optional unavailable() { + var failed = failure.get(); + return failed != null ? Optional.of(failed) : JavacAccess.unavailable(); + } + + /** + * The formatter in these jars: the one loaded before if they have not changed since, a new one otherwise. Cheap + * enough to ask for every file, which is how a jar rebuilt in place is noticed. + * + * @throws IllegalStateException when the formatter cannot be loaded; {@link #unavailable} says so from then on + */ + synchronized FormatterService load(List jars) { + var key = jars.stream().map(Jar::of).toList(); + var formatter = loaded.get(key); + if (formatter == null) { + formatter = loadUncached(jars); + loaded.put(key, formatter); + } + return formatter; + } + + /** A formatter that was loaded met a class it cannot link with: its own missing, or the plugin's of another kind. */ + void failedToLink(LinkageError error) { + failure.compareAndSet(null, "the formatter does not link inside the IDE (" + error + ")"); + } + + private FormatterService loadUncached(List jars) { + var classLoader = new FormatterClassLoader( + jars.stream().map(InProcessFormatters::toUrl).toArray(URL[]::new), + FormatterService.class.getClassLoader()); + try { + JavacAccess.exportTo(classLoader); + var formatters = ServiceLoader.load(FormatterService.class, classLoader).stream() + .toList(); + if (formatters.size() != 1) { + throw new IllegalStateException("Expected one formatter, found " + formatters.size() + " in " + jars); + } + return formatters.get(0).get(); + } catch (RuntimeException | ServiceConfigurationError | LinkageError e) { + failure.compareAndSet( + null, + e instanceof JavacAccess.Refused + ? e.getMessage() + : "the formatter does not load inside the IDE (" + e + ")"); + try { + // Nothing runs in it yet, and a jar left open is one that Windows lets nobody replace. + classLoader.close(); + } catch (IOException closing) { + e.addSuppressed(closing); + } + throw new IllegalStateException("Cannot load the formatter from " + jars, e); + } + } + + private static URL toUrl(Path jar) { + try { + return jar.toUri().toURL(); + } catch (MalformedURLException e) { + throw new UncheckedIOException("Cannot turn " + jar + " into a URL", e); + } + } + + /** A jar as it was when the formatter was loaded from it: rebuilt in place, it changes size or time. */ + private record Jar(Path path, long length, long lastModified) { + static Jar of(Path path) { + var file = path.toFile(); + return new Jar(path, file.length(), file.lastModified()); + } + } +} diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/JavacAccess.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/JavacAccess.java new file mode 100644 index 000000000..4f9603f60 --- /dev/null +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/JavacAccess.java @@ -0,0 +1,122 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.palantir.javaformat.intellij; + +import java.lang.reflect.Method; +import java.util.List; +import java.util.Optional; +import org.jspecify.annotations.Nullable; + +/** + * Whether the formatter can read javac's internals from the IDE's own JVM, and the way to let it. + * + *

The formatter parses with javac's own classes, which module jdk.compiler exports to nobody. A JVM started for + * the formatter gets {@code --add-exports} flags; the IDE's JVM is already running, and its users should not have to + * edit its VM options. But the IDE starts with {@code --add-opens=java.base/java.lang=ALL-UNNAMED}, and with java.lang + * open a plugin can call {@code Module.implAddExports}, which is what {@code --add-exports} calls at startup: here + * for the formatter's class loader alone, so that nothing else in the IDE reaches javac through it. + * + *

{@code implAddExports} is not public API. An IDE that stops opening java.lang, or a JDK without the method, makes + * {@link #unavailable} say so, and the formatter then runs in a JVM of its own. + */ +final class JavacAccess { + + /** The javac packages the formatter reads: the ones its own JVM is started with the exports of. */ + static final List PACKAGES = List.of( + "com.sun.tools.javac.api", + "com.sun.tools.javac.file", + "com.sun.tools.javac.parser", + "com.sun.tools.javac.tree", + "com.sun.tools.javac.util"); + + private static final String NO_JDK_COMPILER = "the IDE's runtime has no jdk.compiler module"; + private static final String JAVA_LANG_NOT_OPEN = + "this IDE does not open java.lang to plugins, so javac cannot be reached"; + + private JavacAccess() {} + + /** The JVM would not export javac to the formatter. Its message is a clause, as {@link #unavailable} gives. */ + static final class Refused extends RuntimeException { + Refused(String message, @Nullable Throwable cause) { + super(message, cause); + } + } + + /** + * Why the formatter cannot reach javac in this JVM, if it cannot: a clause to put after "Not available:". It + * depends on how the JVM was started alone, so it is decided once, though asked for every file formatted. + */ + static Optional unavailable() { + return AsStarted.UNAVAILABLE; + } + + /** + * Exports javac's packages to the formatter's class loader, unless the JVM was started with them exported. + * + * @throws Refused when the JVM does not let it + */ + static void exportTo(ClassLoader formatter) { + var formatterModule = formatter.getUnnamedModule(); + var jdkCompiler = jdkCompiler().orElseThrow(() -> new Refused(NO_JDK_COMPILER, null)); + var notExported = PACKAGES.stream() + .filter(javacPackage -> !jdkCompiler.isExported(javacPackage, formatterModule)) + .toList(); + if (notExported.isEmpty()) { + return; + } + var implAddExports = implAddExports().orElseThrow(() -> new Refused(JAVA_LANG_NOT_OPEN, null)); + try { + for (var javacPackage : notExported) { + implAddExports.invoke(jdkCompiler, javacPackage, formatterModule); + } + } catch (ReflectiveOperationException e) { + // What the method threw says more than that calling it failed. + var cause = e.getCause() != null ? e.getCause() : e; + throw new Refused("javac could not be exported to the formatter: " + cause, cause); + } + } + + private static Optional jdkCompiler() { + return ModuleLayer.boot().findModule("jdk.compiler"); + } + + private static Optional implAddExports() { + try { + var method = Module.class.getDeclaredMethod("implAddExports", String.class, Module.class); + return method.trySetAccessible() ? Optional.of(method) : Optional.empty(); + } catch (NoSuchMethodException e) { + return Optional.empty(); + } + } + + /** What the way the JVM was started allows. A class of its own, to be worked out on first use and once. */ + private static final class AsStarted { + static final Optional UNAVAILABLE = check(); + + private static Optional check() { + var jdkCompiler = jdkCompiler(); + if (jdkCompiler.isEmpty()) { + return Optional.of(NO_JDK_COMPILER); + } + // --add-exports …=ALL-UNNAMED in the IDE's VM options exports to every class loader, this one included. + var anyClassLoader = JavacAccess.class.getModule(); + if (PACKAGES.stream() + .allMatch(javacPackage -> jdkCompiler.get().isExported(javacPackage, anyClassLoader))) { + return Optional.empty(); + } + return implAddExports().isPresent() ? Optional.empty() : Optional.of(JAVA_LANG_NOT_OPEN); + } + } +} diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/SuppressForbidden.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/SuppressForbidden.java new file mode 100644 index 000000000..8f4391595 --- /dev/null +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/SuppressForbidden.java @@ -0,0 +1,27 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.palantir.javaformat.intellij; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** Lets forbidden-apis accept a use of an API that config/forbidden-apis bans, for the reason given. */ +@Retention(RetentionPolicy.CLASS) +@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD}) +@interface SuppressForbidden { + String reason(); +} diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterClassLoaderTest.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterClassLoaderTest.java new file mode 100644 index 000000000..c52eaa13a --- /dev/null +++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterClassLoaderTest.java @@ -0,0 +1,74 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.palantir.javaformat.intellij; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.palantir.javaformat.java.FormatterService; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import org.junit.jupiter.api.Test; + +final class FormatterClassLoaderTest { + + @Test + void takesEveryClassOfTheSpiFromThePlugin() throws Exception { + // The formatter's jars have the SPI too. A class of it that the formatter loaded for itself would not be the + // one the plugin calls, and the SPI shares its package with the formatter, so its classes are listed by name. + assertThat(spiClasses()).isNotEmpty().allMatch(FormatterClassLoader::isShared); + } + + @Test + void leavesTheFormattersOwnClassesToTheFormatter() { + assertThat(FormatterClassLoader.isShared("com.palantir.javaformat.java.FormatterServiceImpl")) + .isFalse(); + assertThat(FormatterClassLoader.isShared("com.palantir.javaformat.java.Formatter")) + .isFalse(); + assertThat(FormatterClassLoader.isShared("com.fasterxml.jackson.databind.ObjectMapper")) + .isFalse(); + } + + @Test + void takesGuavaFromThePlugin() { + // The SPI's signatures name ImmutableList and Range. + assertThat(FormatterClassLoader.isShared("com.google.common.collect.ImmutableList")) + .isTrue(); + assertThat(FormatterClassLoader.isShared("com.google.common.collect.Range$RangeLexOrdering")) + .isTrue(); + } + + /** The names of the classes in the jar, or the directory, that FormatterService comes from. */ + private static List spiClasses() throws Exception { + var spi = TestClassPath.entryOf(FormatterService.class); + if (Files.isDirectory(spi)) { + return classesUnder(spi); + } + try (var jar = FileSystems.newFileSystem(spi)) { + return classesUnder(jar.getPath("/")); + } + } + + private static List classesUnder(Path root) throws Exception { + try (var files = Files.walk(root)) { + return files.map(file -> root.relativize(file).toString()) + .filter(file -> file.endsWith(".class") && !file.endsWith("module-info.class")) + .map(file -> file.substring(0, file.length() - ".class".length()) + .replace(root.getFileSystem().getSeparator(), ".")) + .toList(); + } + } +} diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/InProcessFormatterProbe.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/InProcessFormatterProbe.java new file mode 100644 index 000000000..dbb330c67 --- /dev/null +++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/InProcessFormatterProbe.java @@ -0,0 +1,88 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.palantir.javaformat.intellij; + +import static java.nio.charset.StandardCharsets.UTF_8; + +import com.google.common.collect.Range; +import com.palantir.javaformat.java.Replacement; +import java.io.PrintStream; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.List; + +/** + * What {@link JavacAccessTest} runs in a JVM started as the IDE's is, to see what the formatter can do there: the + * JVM of the tests has javac exported to everything, as the build compiles the formatter. The arguments are the + * formatter's jars, and the file to format comes on the standard input. + */ +final class InProcessFormatterProbe { + + /** Between the answers of a JVM that can format: no file has one. */ + static final String BETWEEN_ANSWERS = "\u0000"; + + static final String SYNTAX_ERROR = "class {"; + + private InProcessFormatterProbe() {} + + public static void main(String[] args) throws Exception { + var out = new PrintStream(System.out, false, UTF_8); + var jars = Arrays.stream(args).map(Path::of).toList(); + var formatters = InProcessFormatters.IDE; + var unavailable = formatters.unavailable(); + if (unavailable.isPresent()) { + out.println("unavailable: " + unavailable.get()); + try { + formatters.load(jars); + out.println("loaded"); + } catch (IllegalStateException e) { + out.println( + "refused: " + (e.getCause() == null ? e : e.getCause().getMessage())); + } + } else { + var input = new String(System.in.readAllBytes(), UTF_8); + var anotherJvm = new RecordingFormatterService(); + var formatter = new InProcessFormatterService(formatters, jars, anotherJvm, failure -> { + throw new AssertionError("could not format in this JVM", failure); + }); + // From the last one, so that the offsets of the others still hold. + List replacements = + formatter.getFormatReplacements(input, List.of(Range.closedOpen(0, input.length()))); + var replaced = new StringBuilder(input); + for (var index = replacements.size() - 1; index >= 0; index--) { + var replacement = replacements.get(index); + replaced.replace( + replacement.getReplaceRange().lowerEndpoint(), + replacement.getReplaceRange().upperEndpoint(), + replacement.getReplacementString()); + } + var jdkCompiler = ModuleLayer.boot().findModule("jdk.compiler").orElseThrow(); + out.print(String.join( + BETWEEN_ANSWERS, + formatter.formatSourceReflowStringsAndFixImports(input), + replaced, + formatter.fixImports(input), + formatter.fixImports(SYNTAX_ERROR), + // What this class can reach of javac, which in the IDE is what every plugin can. + JavacAccess.PACKAGES.stream() + .filter(javacPackage -> + jdkCompiler.isExported(javacPackage, InProcessFormatterProbe.class.getModule())) + .toList() + .toString(), + "formatted in another JVM: " + anotherJvm.calls())); + } + out.flush(); + } +} diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/InProcessFormattersTest.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/InProcessFormattersTest.java new file mode 100644 index 000000000..a216e00a6 --- /dev/null +++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/InProcessFormattersTest.java @@ -0,0 +1,260 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.palantir.javaformat.intellij; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.common.collect.Range; +import com.intellij.testFramework.fixtures.DefaultLightProjectDescriptor; +import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory; +import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture; +import com.intellij.testFramework.fixtures.JavaTestFixtureFactory; +import com.palantir.javaformat.bootstrap.BootstrappingFormatterService; +import com.palantir.javaformat.java.FormatterService; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.FileTime; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +final class InProcessFormattersTest { + + private static final String SYNTAX_ERROR = "class {"; + private static final String A_CLASS = "class A {}\n"; + + @TempDir + private Path dir; + + private JavaCodeInsightTestFixture fixture; + private List formatterJars; + + private final RecordingFormatterService anotherJvm = new RecordingFormatterService(); + private final List failures = new ArrayList<>(); + + @BeforeEach + void setUp() throws Exception { + // The formatter's jars are in the plugin, which only an IDE finds. + var projectBuilder = IdeaTestFixtureFactory.getFixtureFactory() + .createLightFixtureBuilder( + new DefaultLightProjectDescriptor(), getClass().getName()); + fixture = JavaTestFixtureFactory.getFixtureFactory().createCodeInsightFixture(projectBuilder.getFixture()); + fixture.setUp(); + formatterJars = FormatterProvider.getBundledImplementationUrls(); + } + + @AfterEach + void tearDown() throws Exception { + fixture.tearDown(); + } + + @Test + void formatsAsAJvmOfItsOwnDoes() throws Exception { + var input = Files.readString(Path.of("src/test/resources/A.input")); + var wholeFile = List.of(Range.closedOpen(0, input.length())); + var inProcess = inProcess(InProcessFormatters.IDE, formatterJars); + var separateJvm = separateJvm(); + + assertThat(inProcess.formatSourceReflowStringsAndFixImports(input)) + .isEqualTo(Files.readString(Path.of("src/test/resources/A.output"))) + .isEqualTo(separateJvm.formatSourceReflowStringsAndFixImports(input)); + assertThat(inProcess.getFormatReplacements(input, wholeFile)) + .isNotEmpty() + .isEqualTo(separateJvm.getFormatReplacements(input, wholeFile)); + assertThat(inProcess.fixImports(input)).isEqualTo(separateJvm.fixImports(input)); + assertThat(anotherJvm.calls()).isZero(); + } + + @Test + void leavesAFileWithASyntaxErrorAloneAsAJvmOfItsOwnDoes() throws Exception { + // The formatter itself throws; on the command line that is an exit code, which the formatters that run it + // answer by changing nothing. A file is rarely free of syntax errors while it is typed in. + var wholeFile = List.of(Range.closedOpen(0, SYNTAX_ERROR.length())); + var inProcess = inProcess(InProcessFormatters.IDE, formatterJars); + var separateJvm = separateJvm(); + + assertThat(inProcess.getFormatReplacements(SYNTAX_ERROR, wholeFile)) + .isEqualTo(separateJvm.getFormatReplacements(SYNTAX_ERROR, wholeFile)) + .isEmpty(); + assertThat(inProcess.fixImports(SYNTAX_ERROR)) + .isEqualTo(SYNTAX_ERROR) + .isEqualTo(separateJvm.fixImports(SYNTAX_ERROR)); + assertThat(inProcess.formatSourceReflowStringsAndFixImports(SYNTAX_ERROR)) + .isEqualTo(SYNTAX_ERROR) + .isEqualTo(separateJvm.formatSourceReflowStringsAndFixImports(SYNTAX_ERROR)); + assertThat(anotherJvm.calls()).isZero(); + assertThat(failures).isEmpty(); + } + + @Test + void keepsAFormatterLoadedForAsLongAsItsJarsStayTheSame() throws Exception { + var formatters = new InProcessFormatters(); + var jars = copiesOfTheFormatterJars(); + var loaded = formatters.load(jars); + + assertThat(formatters.load(jars)).isSameAs(loaded); + // In another order they are another class path. + assertThat(formatters.load(jars.reversed())).isNotSameAs(loaded); + + // A jar rebuilt in place: a JVM started for the next file would run the new one. + Files.setLastModifiedTime(jars.get(0), FileTime.from(Instant.now().plusSeconds(60))); + + assertThat(formatters.load(jars)).isNotSameAs(loaded); + } + + @Test + void loadsTheFormatterApartFromTheIde() throws Exception { + try (var classLoader = new FormatterClassLoader(urls(), FormatterService.class.getClassLoader())) { + // The formatter and what it runs with are its own, whatever versions of them the IDE has. + assertThat(classLoader + .loadClass("com.palantir.javaformat.java.FormatterServiceImpl") + .getClassLoader()) + .isSameAs(classLoader); + assertThat(classLoader + .loadClass("com.fasterxml.jackson.databind.ObjectMapper") + .getClassLoader()) + .isSameAs(classLoader); + // What the plugin and the formatter hand each other is the plugin's. + assertThat(classLoader.loadClass(FormatterService.class.getName())).isSameAs(FormatterService.class); + assertThat(classLoader.loadClass(Range.class.getName())).isSameAs(Range.class); + assertThat(classLoader.loadClass("com.sun.tools.javac.parser.JavacParser")) + .isNotNull(); + assertThatThrownBy(() -> classLoader.loadClass("com.intellij.openapi.project.Project")) + .isInstanceOf(ClassNotFoundException.class); + } + } + + @Test + void formatsInAJvmOfItsOwnOnceTheFormatterDoesNotLoad() throws Exception { + var formatters = new InProcessFormatters(); + var noFormatter = List.of(dir.resolve("no-formatter-here.jar")); + var inProcess = inProcess(formatters, noFormatter); + + assertThat(inProcess.fixImports(A_CLASS)).isEqualTo(RecordingFormatterService.FORMATTED); + + assertThat(failures) + .singleElement() + .satisfies(failure -> assertThat(failure) + .hasMessage("Cannot load the formatter from %s", noFormatter) + .hasRootCauseMessage("Expected one formatter, found 0 in %s", noFormatter)); + // The settings page says so, and every project formats in a JVM of its own until the IDE restarts. + assertThat(formatters.unavailable()) + .hasValueSatisfying( + reason -> assertThat(reason).startsWith("the formatter does not load inside the IDE (")); + + // Without trying again, or saying so again, for every file. + assertThat(inProcess.formatSourceReflowStringsAndFixImports(A_CLASS)) + .isEqualTo(RecordingFormatterService.FORMATTED); + assertThat(failures).hasSize(1); + assertThat(anotherJvm.calls()).isEqualTo(2); + } + + @Test + void formatsInAJvmOfItsOwnOnceTheFormatterDoesNotLink() throws Exception { + // A formatter from a build can need a class that neither its jars nor the plugin has in the version it needs. + var formatters = new InProcessFormatters(); + var withoutADependency = formatterJars.stream() + .filter(jar -> !jar.getFileName().toString().startsWith("functionaljava")) + .toList(); + assertThat(withoutADependency).hasSize(formatterJars.size() - 1); + var inProcess = inProcess(formatters, withoutADependency); + + assertThat(inProcess.formatSourceReflowStringsAndFixImports(A_CLASS)) + .isEqualTo(RecordingFormatterService.FORMATTED); + + assertThat(failures).singleElement().isInstanceOf(NoClassDefFoundError.class); + assertThat(formatters.unavailable()) + .hasValueSatisfying( + reason -> assertThat(reason).startsWith("the formatter does not link inside the IDE (")); + } + + @Test + void formatsInAJvmOfItsOwnAFileThatOverflowsTheStack() throws Exception { + // javac parses by recursion, and the IDE formats on threads with less stack than a JVM's main thread has. + var formatters = new InProcessFormatters(); + var inProcess = inProcess(formatters, formatterJars); + assertThat(inProcess.formatSourceReflowStringsAndFixImports(A_CLASS)).isEqualTo(A_CLASS); + var nested = "class A { int x = " + "(".repeat(20_000) + "1" + ")".repeat(20_000) + "; }"; + + assertThat(onAThreadOfTheIde(() -> inProcess.formatSourceReflowStringsAndFixImports(nested))) + .isEqualTo(RecordingFormatterService.FORMATTED); + + assertThat(failures).singleElement().isInstanceOf(StackOverflowError.class); + // That file alone: the next one is formatted inside the IDE again. + assertThat(formatters.unavailable()).isEmpty(); + assertThat(inProcess.formatSourceReflowStringsAndFixImports(A_CLASS)).isEqualTo(A_CLASS); + assertThat(anotherJvm.calls()).isEqualTo(1); + } + + private interface Formatting { + String format() throws Exception; + } + + private static String onAThreadOfTheIde(Formatting formatting) throws Exception { + var result = new AtomicReference(); + var failure = new AtomicReference(); + var thread = new Thread( + null, + () -> { + try { + result.set(formatting.format()); + } catch (Throwable e) { + failure.set(e); + } + }, + "formatting", + 512 * 1024); + thread.start(); + thread.join(); + if (failure.get() != null) { + throw new AssertionError(failure.get()); + } + return result.get(); + } + + /** The formatter in this JVM, with a stand-in for the JVM that formats what this one cannot. */ + private FormatterService inProcess(InProcessFormatters formatters, List jars) { + return new InProcessFormatterService(formatters, jars, anotherJvm, failures::add); + } + + private FormatterService separateJvm() { + var ideRuntime = FormatterJdks.ideRuntime(); + return new BootstrappingFormatterService(ideRuntime.java(), ideRuntime.javaVersion(), formatterJars); + } + + /** In a directory of the test's own, where a jar can be touched. */ + private List copiesOfTheFormatterJars() throws Exception { + var copies = new ArrayList(); + for (var jar : formatterJars) { + copies.add(Files.copy(jar, dir.resolve(jar.getFileName()))); + } + return copies; + } + + private URL[] urls() throws Exception { + var urls = new URL[formatterJars.size()]; + for (var index = 0; index < urls.length; index++) { + urls[index] = formatterJars.get(index).toUri().toURL(); + } + return urls; + } +} diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/JavacAccessTest.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/JavacAccessTest.java new file mode 100644 index 000000000..66a839df7 --- /dev/null +++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/JavacAccessTest.java @@ -0,0 +1,147 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.palantir.javaformat.intellij; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.common.collect.Range; +import com.google.common.util.concurrent.internal.InternalFutureFailureAccess; +import com.intellij.testFramework.fixtures.DefaultLightProjectDescriptor; +import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory; +import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture; +import com.intellij.testFramework.fixtures.JavaTestFixtureFactory; +import com.palantir.javaformat.bootstrap.BootstrappingFormatterService; +import com.palantir.javaformat.java.FormatterService; +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * The formatter inside a JVM started as the IDE's is. The JVM of the tests would not do: the build starts it with + * javac exported to everything, so nothing there has to be exported. + */ +final class JavacAccessTest { + + // Among the additionalJvmArguments in the product-info.json of IntelliJ IDEA 2024.2.6 and of 2026.3. + private static final String AS_THE_IDE_STARTS = "--add-opens=java.base/java.lang=ALL-UNNAMED"; + + private JavaCodeInsightTestFixture fixture; + private List formatterJars; + + @BeforeEach + void setUp() throws Exception { + // The formatter's jars are in the plugin, which only an IDE finds. + var projectBuilder = IdeaTestFixtureFactory.getFixtureFactory() + .createLightFixtureBuilder( + new DefaultLightProjectDescriptor(), getClass().getName()); + fixture = JavaTestFixtureFactory.getFixtureFactory().createCodeInsightFixture(projectBuilder.getFixture()); + fixture.setUp(); + formatterJars = FormatterProvider.getBundledImplementationUrls(); + } + + @AfterEach + void tearDown() throws Exception { + fixture.tearDown(); + } + + @Test + void reachesJavacInTheJvmOfTheTests() { + // Which proves nothing about the IDE: the build exports javac to every class loader of this JVM. + assertThat(JavacAccess.unavailable()).isEmpty(); + } + + @Test + void formatsInAJvmStartedAsTheIdeIs() throws Exception { + var input = Files.readString(Path.of("src/test/resources/A.input")); + var formatted = Files.readString(Path.of("src/test/resources/A.output")); + + assertThat(inAJvmWith(List.of(AS_THE_IDE_STARTS), input).split(InProcessFormatterProbe.BETWEEN_ANSWERS)) + .containsExactly( + formatted, + // The replacements of the whole file, applied: A.input has no imports to fix. + formatted, + separateJvm().fixImports(input), + InProcessFormatterProbe.SYNTAX_ERROR, + // javac is exported to the formatter alone, not to the plugin or to anything else of the IDE. + "[]", + "formatted in another JVM: 0"); + } + + @Test + void formatsInAJvmWhoseUserExportedJavac() throws Exception { + // As google-java-format asks of its users: the IDE's VM options edited by hand. + var exports = JavacAccess.PACKAGES.stream() + .map(javacPackage -> "--add-exports=jdk.compiler/" + javacPackage + "=ALL-UNNAMED") + .toList(); + var input = Files.readString(Path.of("src/test/resources/A.input")); + + assertThat(inAJvmWith(exports, input).split(InProcessFormatterProbe.BETWEEN_ANSWERS)) + .startsWith(Files.readString(Path.of("src/test/resources/A.output"))) + .endsWith(JavacAccess.PACKAGES.toString(), "formatted in another JVM: 0"); + } + + @Test + void saysWhyItCannotFormatInAJvmThatOpensNothing() throws Exception { + var reason = "this IDE does not open java.lang to plugins, so javac cannot be reached"; + + assertThat(inAJvmWith(List.of(), "").lines()) + // Asked to load the formatter all the same, it refuses rather than fail on the first file. + .containsExactly("unavailable: " + reason, "refused: " + reason); + } + + private FormatterService separateJvm() { + var ideRuntime = FormatterJdks.ideRuntime(); + return new BootstrappingFormatterService(ideRuntime.java(), ideRuntime.javaVersion(), formatterJars); + } + + /** What InProcessFormatterProbe prints in a JVM with these arguments and nothing else of the IDE's. */ + private String inAJvmWith(List jvmArguments, String input) throws Exception { + var command = new ArrayList(); + command.add(Path.of(System.getProperty("java.home"), "bin", "java").toString()); + command.addAll(jvmArguments); + command.add("-cp"); + // What the plugin's class loader has of them in the IDE: the plugin, the SPI and Guava. + command.add(Stream.of( + InProcessFormatterProbe.class, + JavacAccess.class, + FormatterService.class, + Range.class, + InternalFutureFailureAccess.class) + .map(type -> TestClassPath.entryOf(type).toString()) + .distinct() + .collect(Collectors.joining(File.pathSeparator))); + command.add(InProcessFormatterProbe.class.getName()); + formatterJars.forEach(jar -> command.add(jar.toString())); + + var builder = new ProcessBuilder(command).redirectError(ProcessBuilder.Redirect.INHERIT); + // Options a JVM takes from its environment would be the test's, not the IDE's. + builder.environment().keySet().removeAll(List.of("JAVA_TOOL_OPTIONS", "JDK_JAVA_OPTIONS", "_JAVA_OPTIONS")); + var process = builder.start(); + try (var stdin = process.getOutputStream()) { + stdin.write(input.getBytes(UTF_8)); + } + var output = new String(process.getInputStream().readAllBytes(), UTF_8); + assertThat(process.waitFor()).as("exit code, after printing %s", output).isZero(); + return output; + } +} diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/RecordingFormatterService.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/RecordingFormatterService.java new file mode 100644 index 000000000..c60dbbb26 --- /dev/null +++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/RecordingFormatterService.java @@ -0,0 +1,53 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.palantir.javaformat.intellij; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Range; +import com.palantir.javaformat.java.FormatterService; +import com.palantir.javaformat.java.Replacement; +import java.util.Collection; +import java.util.concurrent.atomic.AtomicInteger; + +/** Stands for the JVM that formats what the IDE's own cannot: it formats nothing, and counts what it was asked. */ +final class RecordingFormatterService implements FormatterService { + + static final String FORMATTED = "formatted in another JVM"; + + private final AtomicInteger calls = new AtomicInteger(); + + int calls() { + return calls.get(); + } + + @Override + @SuppressForbidden(reason = "FormatterService, kept in the SPI for compatibility, returns ImmutableList") + public ImmutableList getFormatReplacements(String input, Collection> ranges) { + calls.incrementAndGet(); + return ImmutableList.of(Replacement.create(0, input.length(), FORMATTED)); + } + + @Override + public String formatSourceReflowStringsAndFixImports(String input) { + calls.incrementAndGet(); + return FORMATTED; + } + + @Override + public String fixImports(String input) { + calls.incrementAndGet(); + return FORMATTED; + } +} diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/TestClassPath.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/TestClassPath.java new file mode 100644 index 000000000..7641c8404 --- /dev/null +++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/TestClassPath.java @@ -0,0 +1,39 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.palantir.javaformat.intellij; + +import static java.util.Objects.requireNonNull; + +import java.net.URI; +import java.nio.file.Path; + +/** Where the classes of the tests come from. */ +final class TestClassPath { + + private TestClassPath() {} + + /** + * The jar or the directory a class was loaded from. Asked of the class file rather than of the class's code + * source, which the class loader of the IDE's tests leaves empty. + */ + static Path entryOf(Class type) { + var classFile = type.getName().replace('.', '/') + ".class"; + var url = requireNonNull(type.getClassLoader().getResource(classFile)).toString(); + return Path.of(URI.create( + url.startsWith("jar:") + ? url.substring("jar:".length(), url.indexOf("!/")) + : url.substring(0, url.length() - classFile.length()))); + } +} From ae6a4bf7d295ec5f85f482d072d10a3e61ae5456 Mon Sep 17 00:00:00 2001 From: Alex Abashev Date: Mon, 23 Nov 2026 00:30:21 +0300 Subject: [PATCH 3/5] Format inside the IDE, in a separate JVM or with the native binary The settings page of the IntelliJ plugin had one box, Use native binary, and without it the plugin started a JVM on the IDE's runtime for every file. It now has three ways to run the formatter, one of them chosen for a project: - In the IDE process: the formatter loaded into the IDE's own JVM, with nothing to start for a file. It is greyed out, with the reason under it, where the formatter cannot reach javac there. - In a separate JVM, as before, on a JDK from a list: the IDE's runtime, which is the default and what the plugin ran on, the project SDK, or a JDK registered in the IDE. One that cannot run the formatter, older than Java 21 for one, is listed in grey and cannot be chosen. - Native binary, as before. The options of the ways not chosen stay on the page, greyed: hidden, they would move the page about with every choice. A project whose settings switch the native binary on keeps it. Every other project moves into the IDE process: a file written before there were modes says only useNativeImage, and formatterMode is new beside it. useNativeImage goes on being written with the mode, for a plugin from before the modes that reads the same .idea/open-java-format.xml. What cannot run falls back, with a warning in idea.log and a line under Active formatter, and no balloon: the IDE process to a separate JVM, a JDK that cannot run the formatter to the IDE's runtime. A missing native binary falls back to a separate JVM with its notification, as before. Inside the IDE, a file the formatter fails on with an Error is formatted in a JVM on the IDE's runtime, and a formatter that does not load or link there switches the IDE process off until the IDE restarts, with one error in idea.log for the plugin's error reports. Apply no longer checks the binary and the JDK while Enable open-java-format is unticked: the page shows neither then, so there was nothing on it to put right. Closes #223. --- .../javaformat/intellij/FormatterMode.java | 25 ++ .../intellij/FormatterProvider.java | 102 +++++-- .../intellij/FormatterSelection.java | 116 ++++++- .../NativeImageNoticeStartupActivity.java | 2 +- .../PalantirJavaFormatConfigurable.java | 213 +++++++++++-- .../PalantirJavaFormatFormattingService.java | 4 +- .../intellij/PalantirJavaFormatSettings.java | 39 ++- .../src/main/resources/META-INF/plugin.xml | 4 +- .../intellij/FormatterProviderTest.java | 48 ++- .../intellij/FormatterSelectionTest.java | 150 +++++++-- .../NativeImageNoticeStartupActivityTest.java | 12 +- .../PalantirJavaFormatConfigurableTest.java | 289 ++++++++++++++++-- .../PalantirJavaFormatSettingsTest.java | 102 ++++++- 13 files changed, 969 insertions(+), 137 deletions(-) create mode 100644 open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterMode.java diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterMode.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterMode.java new file mode 100644 index 000000000..d89c9e5d7 --- /dev/null +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterMode.java @@ -0,0 +1,25 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.palantir.javaformat.intellij; + +/** How a project asks for the formatter to run. The names are what .idea/open-java-format.xml holds. */ +enum FormatterMode { + /** Loaded into the IDE's own JVM: nothing to start for a file. */ + IN_PROCESS, + /** In a JVM started for each call, on the JDK the settings name. */ + JVM, + /** As the native binary, started for each call. */ + NATIVE +} diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterProvider.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterProvider.java index f21e9b47d..5e3f5f931 100644 --- a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterProvider.java +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterProvider.java @@ -22,7 +22,6 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.PluginDescriptor; import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.SystemInfo; import com.palantir.javaformat.bootstrap.BootstrappingFormatterService; import com.palantir.javaformat.bootstrap.NativeImageFormatterService; import com.palantir.javaformat.java.FormatterService; @@ -48,46 +47,101 @@ final class FormatterProvider { Caffeine.newBuilder().maximumSize(1).build(FormatterProvider::createFormatter); private final Supplier> embeddedNativeImage; + private final Supplier> inProcessUnavailable; - /** embeddedNativeImage: the downloaded native binary, asked again on every format since a download can add it. */ - FormatterProvider(Supplier> embeddedNativeImage) { + /** + * embeddedNativeImage: the downloaded native binary, asked again on every format since a download can add it. + * inProcessUnavailable: why the formatter cannot run in the IDE's own JVM, if it cannot. + */ + FormatterProvider(Supplier> embeddedNativeImage, Supplier> inProcessUnavailable) { this.embeddedNativeImage = embeddedNativeImage; + this.inProcessUnavailable = inProcessUnavailable; } Optional get(Project project, PalantirJavaFormatSettings settings) { - // The selection, not the settings, is in the key: the formatter has to change when the binary appears. + // The selection, not the settings, is in the key: the formatter has to change when the binary appears, or + // the project SDK changes. return implementationCache.get(new FormatterCacheKey( project, settings.getImplementationClassPath(), settings.injectedVersionIsOutdated(), - FormatterSelection.of(settings, embeddedNativeImage))); + FormatterSelection.of( + settings, FormatterSelection.in(project, inProcessUnavailable, embeddedNativeImage)))); } private static Optional createFormatter(FormatterCacheKey cacheKey) { - if (cacheKey.selection() instanceof FormatterSelection.NativeImage nativeImage) { - log.info("open-java-format: using native binary, " + (nativeImage.embedded() ? "embedded: " : "custom: ") - + nativeImage.path()); - return Optional.of(new NativeImageFormatterService(nativeImage.path())); - } - if (cacheKey.selection() instanceof FormatterSelection.JavaBased javaBased && javaBased.nativeImageMissing()) { - log.warn("open-java-format: the native binary is switched on but not downloaded, formatting with the" - + " Java-based formatter"); + return Optional.of( + switch (cacheKey.selection()) { + case FormatterSelection.NativeImage nativeImage -> { + log.info("open-java-format: using native binary, " + + (nativeImage.embedded() ? "embedded: " : "custom: ") + nativeImage.path()); + yield new NativeImageFormatterService(nativeImage.path()); + } + case FormatterSelection.InProcess inProcess -> inProcess(cacheKey); + case FormatterSelection.SeparateJvm separateJvm -> { + separateJvm.fallbacks().forEach(fallback -> log.warn(fallbackMessage(fallback))); + yield separateJvm(separateJvm.java(), separateJvm.javaVersion(), cacheKey); + } + }); + } + + private static FormatterService inProcess(FormatterCacheKey cacheKey) { + log.info("open-java-format: using in-process formatter (Java " + System.getProperty("java.version") + ") with " + + classpathName(cacheKey) + " classpath"); + // Loaded with the first file, in the background, and not here: this can be the UI thread. What cannot be + // formatted inside the IDE goes to the JVM that always runs. + var ideRuntime = FormatterJdks.ideRuntime(); + var classpath = implementationClasspath(cacheKey); + return new InProcessFormatterService( + InProcessFormatters.IDE, + classpath, + new BootstrappingFormatterService(ideRuntime.java(), ideRuntime.javaVersion(), classpath), + FormatterProvider::couldNotFormatInProcess); + } + + private static void couldNotFormatInProcess(Throwable failure) { + var message = "open-java-format: cannot format inside the IDE, formatting in a JVM of its own"; + if (InProcessFormatters.IDE.unavailable().isPresent()) { + // The formatter does not load or link in this IDE, which it should: an error, so that it goes to the + // plugin's error reports. Once, since from now on every file goes to a JVM of its own. + log.error(message, failure); + } else { + log.warn(message, failure); } + } + + // The JVM gets the "--add-exports" it needs to reach javac. By default it is the IDE's own runtime rather than + // the project SDK: every IDE this plugin supports runs on Java 21 or later, which the formatter needs, while a + // project SDK can be any version. + private static FormatterService separateJvm(Path java, int javaVersion, FormatterCacheKey cacheKey) { + log.info("open-java-format: using Java-based formatter on " + java + " (Java " + javaVersion + ") with " + + classpathName(cacheKey) + " classpath"); + return new BootstrappingFormatterService(java, javaVersion, implementationClasspath(cacheKey)); + } + + private static String fallbackMessage(FormatterSelection.Fallback fallback) { + return "open-java-format: " + + switch (fallback) { + case FormatterSelection.Fallback.InProcessUnavailable unavailable -> + "cannot format inside the IDE (" + unavailable.reason() + "), formatting in a JVM of its own"; + case FormatterSelection.Fallback.NativeImageMissing missing -> + "the native binary is switched on but not downloaded, formatting with the Java-based" + + " formatter"; + case FormatterSelection.Fallback.JdkUnusable unusable -> + "cannot run the formatter on the JDK of the settings (" + unusable.reason() + + "), formatting on the IDE's runtime"; + }; + } + + private static List implementationClasspath(FormatterCacheKey cacheKey) { + return getImplementationUrls(cacheKey.implementationClassPath(), cacheKey.useBundledImplementation()); + } - // The formatter runs in a JVM of its own, started with the "--add-exports" it needs to reach javac. - // That JVM is the IDE's own runtime, never the project SDK: every IDE this plugin supports runs on Java 21 - // or later, which the formatter needs, while a project SDK can be any version. - int jdkMajorVersion = Runtime.version().feature(); - Path jdkPath = Path.of(System.getProperty("java.home"), "bin", SystemInfo.isWindows ? "java.exe" : "java"); - List implementationClasspath = - getImplementationUrls(cacheKey.implementationClassPath(), cacheKey.useBundledImplementation()); - var classpath = cacheKey.useBundledImplementation() + private static String classpathName(FormatterCacheKey cacheKey) { + return cacheKey.useBundledImplementation() || cacheKey.implementationClassPath().isEmpty() ? "bundled" : "build"; - log.info("open-java-format: using Java-based formatter on " + jdkPath + " (Java " + jdkMajorVersion + ") with " - + classpath + " classpath"); - return Optional.of(new BootstrappingFormatterService(jdkPath, jdkMajorVersion, implementationClasspath)); } private static List getProvidedImplementationUrls(List implementationClasspath) { diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterSelection.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterSelection.java index 1b5a52bcd..0b6c42965 100644 --- a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterSelection.java +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterSelection.java @@ -14,7 +14,13 @@ package com.palantir.javaformat.intellij; +import com.intellij.openapi.project.Project; +import com.palantir.javaformat.intellij.FormatterJdk.Resolved; +import com.palantir.javaformat.intellij.FormatterJdk.Unusable; +import com.palantir.javaformat.intellij.FormatterJdk.Usable; import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; import java.util.Optional; import java.util.function.Supplier; @@ -25,22 +31,106 @@ sealed interface FormatterSelection { /** - * A path of the user's own wins over the embedded binary. Without either, the Java-based formatter runs even with - * the native one switched on: the embedded binary may not be downloaded yet. The embedded binary is looked for - * only when it would run, since that lists a directory and this runs for every file formatted. + * What the selection depends on besides the settings: the IDE and the machine. Each is looked at only when the + * formatter it is for would run, since this runs for every file formatted: the embedded binary lists a directory, + * and a JDK is looked up among the IDE's. */ - static FormatterSelection of(PalantirJavaFormatSettings settings, Supplier> embeddedNativeImage) { - if (!settings.useNativeImage()) { - return new JavaBased(false); - } - return settings.getNativeImagePath() - .map(path -> new NativeImage(path, false)) - .or(() -> embeddedNativeImage.get().map(path -> new NativeImage(path, true))) - .orElseGet(() -> new JavaBased(true)); + interface Environment { + /** Why the formatter cannot run in the IDE's own JVM, if it cannot. */ + Optional inProcessUnavailable(); + + Resolved resolve(FormatterJdk jdk); + + Usable ideRuntime(); + + /** The native binary the plugin downloaded. */ + Optional embeddedNativeImage(); } + /** + * The settings name a way to run the formatter, and each way has what it needs or it does not: the IDE's JVM + * access to javac, the JVM a JDK, the native formatter a binary, where a path of the user's own wins over the + * embedded one. Without it the formatter runs in a JVM of its own, which always can: on the IDE's runtime if the + * JDK is the one missing. + */ + static FormatterSelection of(PalantirJavaFormatSettings settings, Environment environment) { + return switch (settings.getFormatterMode()) { + case IN_PROCESS -> + environment + .inProcessUnavailable() + .map( + reason -> separateJvm(settings, environment, new Fallback.InProcessUnavailable(reason))) + .orElseGet(InProcess::new); + case JVM -> separateJvm(settings, environment); + case NATIVE -> + settings.getNativeImagePath() + .map(path -> new NativeImage(path, false)) + .or(() -> environment.embeddedNativeImage().map(path -> new NativeImage(path, true))) + .orElseGet(() -> separateJvm(settings, environment, new Fallback.NativeImageMissing())); + }; + } + + private static SeparateJvm separateJvm( + PalantirJavaFormatSettings settings, Environment environment, Fallback... fromAnotherMode) { + var fallbacks = new ArrayList<>(List.of(fromAnotherMode)); + var jvm = switch (environment.resolve(settings.getFormatterJdk())) { + case Usable usable -> usable; + case Unusable unusable -> { + fallbacks.add(new Fallback.JdkUnusable(unusable.reason())); + yield environment.ideRuntime(); + } + }; + return new SeparateJvm(jvm.java(), jvm.javaVersion(), List.copyOf(fallbacks)); + } + + /** The IDE and a project of it. */ + static Environment in( + Project project, + Supplier> inProcessUnavailable, + Supplier> embeddedNativeImage) { + return new Environment() { + @Override + public Optional inProcessUnavailable() { + return inProcessUnavailable.get(); + } + + @Override + public Resolved resolve(FormatterJdk jdk) { + return FormatterJdks.resolve(project, jdk); + } + + @Override + public Usable ideRuntime() { + return FormatterJdks.ideRuntime(); + } + + @Override + public Optional embeddedNativeImage() { + return embeddedNativeImage.get(); + } + }; + } + + /** The formatter loaded into the IDE's own JVM: nothing to start, and the IDE's javac parses the file. */ + record InProcess() implements FormatterSelection {} + + /** + * A JVM started for each call. fallbacks: what the settings asked for and cannot have, when this is not it: none + * when they ask for this JVM. + */ + record SeparateJvm(Path java, int javaVersion, List fallbacks) implements FormatterSelection {} + record NativeImage(Path path, boolean embedded) implements FormatterSelection {} - /** nativeImageMissing: the native formatter is switched on, but there is no binary to run. */ - record JavaBased(boolean nativeImageMissing) implements FormatterSelection {} + /** Why something else runs than what the settings name. */ + sealed interface Fallback { + /** reason: as {@link InProcessFormatters#unavailable} gives it. */ + record InProcessUnavailable(String reason) implements Fallback {} + + /** The native formatter is on, but there is no binary to run: the embedded one may not be downloaded yet. */ + record NativeImageMissing() implements Fallback {} + + /** The JDK the settings name cannot run the formatter, so the IDE's runtime does. */ + record JdkUnusable(String reason) implements Fallback {} + } } diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/NativeImageNoticeStartupActivity.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/NativeImageNoticeStartupActivity.java index cf44f4495..eea375d30 100644 --- a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/NativeImageNoticeStartupActivity.java +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/NativeImageNoticeStartupActivity.java @@ -78,7 +78,7 @@ public void runActivity(Project project) { static Optional notice( PalantirJavaFormatSettings settings, Status status, @Nullable String ignoredVersion) { if (!settings.isEnabled() - || !settings.useNativeImage() + || settings.getFormatterMode() != FormatterMode.NATIVE || settings.getNativeImagePath().isPresent()) { return Optional.empty(); } diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurable.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurable.java index 431cc0591..ef1b747db 100644 --- a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurable.java +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurable.java @@ -22,17 +22,25 @@ import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SearchableConfigurable; import com.intellij.openapi.project.Project; +import com.intellij.openapi.ui.ComboBox; import com.intellij.openapi.ui.TextBrowseFolderListener; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.util.Disposer; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; +import com.intellij.ui.ColoredListCellRenderer; import com.intellij.ui.DocumentAdapter; +import com.intellij.ui.SimpleTextAttributes; import com.intellij.ui.components.ActionLink; +import com.intellij.ui.components.JBLabel; import com.intellij.ui.components.JBTextArea; import com.intellij.ui.components.JBTextField; import com.intellij.util.ui.FormBuilder; import com.intellij.util.ui.JBUI; +import com.intellij.util.ui.UIUtil; import com.palantir.javaformat.intellij.EmbeddedNativeImage.Status; +import com.palantir.javaformat.intellij.FormatterJdk.Unusable; +import com.palantir.javaformat.intellij.FormatterJdk.Usable; +import com.palantir.javaformat.intellij.FormatterSelection.Fallback; import com.palantir.javaformat.intellij.PalantirJavaFormatSettings.EnabledState; import java.awt.Dimension; import java.awt.FlowLayout; @@ -41,12 +49,18 @@ import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; +import java.util.ArrayList; import java.util.Optional; +import java.util.function.Supplier; import javax.swing.Box; +import javax.swing.ButtonGroup; +import javax.swing.DefaultComboBoxModel; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; +import javax.swing.JList; import javax.swing.JPanel; +import javax.swing.JRadioButton; import javax.swing.JTextArea; import javax.swing.event.DocumentEvent; import org.jetbrains.annotations.Nls; @@ -56,9 +70,16 @@ class PalantirJavaFormatConfigurable extends BaseConfigurable implements Searcha private final Project project; private final EmbeddedNativeImage embeddedNativeImage; + private final Supplier> inProcessUnavailable; private final JPanel panel; private final JCheckBox enable; - private final JCheckBox useNativeImage; + private final JPanel modes; + private final JRadioButton inProcess; + private final JLabel inProcessNote; + private final JRadioButton separateJvm; + private final JdkChoices jdks = new JdkChoices(); + private final JPanel jdkOptions; + private final JRadioButton nativeImage; private final JPanel nativeImageOptions; private final JLabel embeddedStatus; private final ActionLink embeddedAction; @@ -71,14 +92,27 @@ class PalantirJavaFormatConfigurable extends BaseConfigurable implements Searcha private Disposable uiDisposable; public PalantirJavaFormatConfigurable(Project project) { - this(project, EmbeddedNativeImage.getInstance()); + this(project, EmbeddedNativeImage.getInstance(), InProcessFormatters.IDE::unavailable); } - PalantirJavaFormatConfigurable(Project project, EmbeddedNativeImage embeddedNativeImage) { + /** inProcessUnavailable: why the formatter cannot run in the IDE's own JVM, if it cannot. */ + PalantirJavaFormatConfigurable( + Project project, EmbeddedNativeImage embeddedNativeImage, Supplier> inProcessUnavailable) { this.project = project; this.embeddedNativeImage = embeddedNativeImage; + this.inProcessUnavailable = inProcessUnavailable; this.enable = new JCheckBox("Enable open-java-format"); - this.useNativeImage = new JCheckBox("Use native binary"); + this.inProcess = new JRadioButton("In the IDE process"); + this.inProcessNote = new JBLabel(); + inProcessNote.setForeground(UIUtil.getContextHelpForeground()); + this.separateJvm = new JRadioButton("In a separate JVM"); + this.nativeImage = new JRadioButton("Native binary"); + var mode = new ButtonGroup(); + mode.add(inProcess); + mode.add(separateJvm); + mode.add(nativeImage); + var jdk = new ComboBox<>(jdks); + jdk.setRenderer(new JdkChoiceRenderer()); this.embeddedStatus = new JLabel(); this.embeddedAction = new ActionLink(); embeddedAction.addActionListener(event -> embeddedNativeImage.download(project, pluginVersion())); @@ -95,11 +129,22 @@ public PalantirJavaFormatConfigurable(Project project) { statusRow.add(embeddedStatus); statusRow.add(Box.createHorizontalStrut(JBUI.scale(6))); statusRow.add(embeddedAction); - this.nativeImageOptions = FormBuilder.createFormBuilder() - .setFormLeftIndent(JBUI.scale(20)) + this.jdkOptions = underItsMode().addLabeledComponent("JDK", jdk).getPanel(); + this.nativeImageOptions = underItsMode() .addComponent(statusRow) .addLabeledComponent("Binary", nativeImagePath) .getPanel(); + // The options of every mode stay on the page, those of the modes not chosen greyed: hidden, they would move + // the modes under them each time another is chosen. + this.modes = FormBuilder.createFormBuilder() + .addComponent(new JBLabel("Run the formatter")) + .addComponent(inProcess) + .addComponent(underItsMode().addComponent(inProcessNote).getPanel()) + .addComponent(separateJvm) + .addComponent(jdkOptions) + .addComponent(nativeImage) + .addComponent(nativeImageOptions) + .getPanel(); // Filling its own form vertically: only then does the form put the label above the text, rather than beside // the middle of a wrapped path. this.activeFormatterRow = FormBuilder.createFormBuilder() @@ -107,9 +152,12 @@ public PalantirJavaFormatConfigurable(Project project) { .addLabeledComponentFillVertically("Active formatter", activeFormatter) .getPanel(); - // The page shows what runs once it is applied, so it follows every box and the path as they change. + // The page shows what runs once it is applied, so it follows every choice and the path as they change. enable.addItemListener(event -> showPage()); - useNativeImage.addItemListener(event -> showPage()); + inProcess.addItemListener(event -> showPage()); + separateJvm.addItemListener(event -> showPage()); + nativeImage.addItemListener(event -> showPage()); + jdk.addItemListener(event -> showActiveFormatter()); nativeImagePath.getTextField().getDocument().addDocumentListener(new DocumentAdapter() { @Override protected void textChanged(DocumentEvent event) { @@ -122,8 +170,7 @@ protected void textChanged(DocumentEvent event) { // above null: the page rendered nothing and reset() threw the moment it was opened. this.panel = FormBuilder.createFormBuilder() .addComponent(enable) - .addComponent(useNativeImage) - .addComponent(nativeImageOptions) + .addComponent(modes) .addComponent(activeFormatterRow) // Takes the rest of the page, so the rows stay at the top whichever of them are hidden. .addComponentFillVertically(new JPanel(), 0) @@ -166,8 +213,10 @@ public JComponent createComponent() { @Override public void apply() throws ConfigurationException { PalantirJavaFormatSettings settings = PalantirJavaFormatSettings.getInstance(project); + var mode = selectedMode(); var path = enteredNativeImagePath(); - if (useNativeImage.isSelected()) { + // Only of what the page shows: switched off, it has nothing on it to put right. + if (enable.isSelected() && mode == FormatterMode.NATIVE) { if (path.isPresent() && !(Files.isRegularFile(path.get()) && Files.isExecutable(path.get()))) { throw new ConfigurationException(path.get() + " is not an executable file"); } @@ -175,10 +224,17 @@ public void apply() throws ConfigurationException { throw new ConfigurationException("Download the embedded version or choose a binary"); } } + // A JDK that stopped being usable since it was chosen: the list lets no other such one be chosen. + if (enable.isSelected() + && mode == FormatterMode.JVM + && FormatterJdks.resolve(project, selectedJdk()) instanceof Unusable unusable) { + throw new ConfigurationException("Choose another JDK: " + unusable.reason()); + } var wasEnabled = settings.isEnabled(); settings.setEnabled( enable.isSelected() ? EnabledState.ENABLED : PalantirJavaFormatSettings.disabledState(project)); - settings.setUseNativeImage(useNativeImage.isSelected()); + settings.setFormatterMode(mode); + settings.setFormatterJdk(selectedJdk()); settings.setNativeImagePath(path); if (settings.isEnabled() != wasEnabled) { // The Java import settings of each file are cached, and PalantirJavaFormatCodeStyleSettingsModifier sets @@ -191,7 +247,12 @@ public void apply() throws ConfigurationException { public void reset() { PalantirJavaFormatSettings settings = PalantirJavaFormatSettings.getInstance(project); enable.setSelected(settings.isEnabled()); - useNativeImage.setSelected(settings.useNativeImage()); + switch (settings.getFormatterMode()) { + case IN_PROCESS -> inProcess.setSelected(true); + case JVM -> separateJvm.setSelected(true); + case NATIVE -> nativeImage.setSelected(true); + } + showJdks(settings.getFormatterJdk()); nativeImagePath.setText( settings.getNativeImagePath().map(Path::toString).orElse("")); showPage(); @@ -207,7 +268,8 @@ public boolean isModified() { return true; } return enable.isSelected() != settings.isEnabled() - || useNativeImage.isSelected() != settings.useNativeImage() + || selectedMode() != settings.getFormatterMode() + || !selectedJdk().equals(settings.getFormatterJdk()) || !path.equals(settings.getNativeImagePath()); } @@ -222,7 +284,7 @@ public void disposeUIResources() { record StatusLine(String text, Optional action) {} /** - * The line under Use native binary, and the link next to it, which downloads the plugin's version. There is a link + * The line under Native binary, and the link next to it, which downloads the plugin's version. There is a link * only when there is something to download. */ static StatusLine statusLine(Status status) { @@ -248,9 +310,18 @@ static StatusLine statusLine(Status status) { } private void showPage() { - useNativeImage.setVisible(enable.isSelected()); - nativeImageOptions.setVisible(enable.isSelected() && useNativeImage.isSelected()); + modes.setVisible(enable.isSelected()); activeFormatterRow.setVisible(enable.isSelected()); + var unavailable = inProcessUnavailable.get(); + // Left selected when the settings have it and it cannot run here: the page shows what is stored, why it does + // not run, and under Active formatter what runs instead. + inProcess.setEnabled(unavailable.isEmpty()); + inProcessNote.setText(unavailable + .map(reason -> "Not available: " + reason + ".") + .orElseGet(() -> "Fastest: nothing to start. The IDE's own Java " + + Runtime.version().feature() + " parses the code.")); + UIUtil.setEnabled(jdkOptions, separateJvm.isSelected(), true); + UIUtil.setEnabled(nativeImageOptions, nativeImage.isSelected(), true); showEmbeddedNativeImage(); } @@ -264,12 +335,43 @@ private void showEmbeddedNativeImage() { } /** - * The formatter the page would run once applied, chosen as FormatterProvider chooses it: the path typed in Binary, - * else the embedded binary, else the Java-based formatter. + * The JDKs to choose from, as they are now: the IDE's can change between two visits of the page. stored: what the + * settings have, listed even when the IDE no longer has a JDK of that name. */ + private void showJdks(FormatterJdk stored) { + var choices = new ArrayList<>(FormatterJdks.choices()); + if (!choices.contains(stored)) { + choices.add(stored); + } + jdks.removeAllElements(); + for (var choice : choices) { + var jdkChoice = new JdkChoice( + choice, + FormatterJdks.label(project, choice), + FormatterJdks.resolve(project, choice) instanceof Usable); + jdks.addElement(jdkChoice); + if (choice.equals(stored)) { + jdks.show(jdkChoice); + } + } + } + + private FormatterMode selectedMode() { + if (inProcess.isSelected()) { + return FormatterMode.IN_PROCESS; + } + return nativeImage.isSelected() ? FormatterMode.NATIVE : FormatterMode.JVM; + } + + private FormatterJdk selectedJdk() { + return jdks.getSelectedItem() instanceof JdkChoice choice ? choice.jdk() : new FormatterJdk.IdeRuntime(); + } + + /** The formatter the page would run once applied, chosen as FormatterProvider chooses it. */ private void showActiveFormatter() { var pending = new PalantirJavaFormatSettings(); - pending.setUseNativeImage(useNativeImage.isSelected()); + pending.setFormatterMode(selectedMode()); + pending.setFormatterJdk(selectedJdk()); try { pending.setNativeImagePath(enteredNativeImagePath()); } catch (ConfigurationException e) { @@ -278,18 +380,37 @@ private void showActiveFormatter() { return; } activeFormatter.setText( - switch (FormatterSelection.of(pending, embeddedNativeImage::installedPath)) { - case FormatterSelection.NativeImage nativeImage -> - nativeImage.path().toString(); - case FormatterSelection.JavaBased javaBased - when !javaBased.nativeImageMissing() -> "Java-based formatter"; - case FormatterSelection.JavaBased missing -> + switch (FormatterSelection.of( + pending, + FormatterSelection.in(project, inProcessUnavailable, embeddedNativeImage::installedPath))) { + case FormatterSelection.InProcess inProcessFormatter -> + "The IDE process (Java " + System.getProperty("java.version") + ")"; + case FormatterSelection.NativeImage nativeImageFormatter -> + nativeImageFormatter.path().toString(); + case FormatterSelection.SeparateJvm jvm + when jvm.fallbacks().contains(new Fallback.NativeImageMissing()) -> embeddedNativeImage.status(pluginVersion()) instanceof Status.NoImageForPlatform ? "Choose a native binary: none is published for this platform" : "Need to download version " + pluginVersion() + " from Maven Central"; + case FormatterSelection.SeparateJvm jvm -> separateJvmText(jvm); }); } + /** The java that runs, and under it why it is not what the page asks for, when it is not. */ + static String separateJvmText(FormatterSelection.SeparateJvm jvm) { + var lines = new ArrayList(); + lines.add(jvm.java() + " (Java " + jvm.javaVersion() + ")"); + for (var fallback : jvm.fallbacks()) { + switch (fallback) { + case Fallback.InProcessUnavailable unavailable -> + lines.add("A JVM of its own: the IDE process is not available."); + case Fallback.JdkUnusable unusable -> lines.add("The IDE's runtime: " + unusable.reason() + "."); + case Fallback.NativeImageMissing missing -> lines.add("A JVM of its own: there is no native binary."); + } + } + return String.join("\n", lines); + } + private String pluginVersion() { return PalantirJavaFormatSettings.getInstance(project) .getImplementationVersion() @@ -339,4 +460,44 @@ public void componentResized(ComponentEvent event) { return text; } + /** The options of a mode, indented under its radio button. */ + private static FormBuilder underItsMode() { + return FormBuilder.createFormBuilder().setFormLeftIndent(JBUI.scale(20)); + } + + /** usable: whether the formatter can run on it, which only Java 21 or later that is on this machine can. */ + private record JdkChoice(FormatterJdk jdk, FormatterJdks.Label label, boolean usable) {} + + /** Lets a JDK be chosen only if the formatter can run on it. The others stay in the list, greyed. */ + private static final class JdkChoices extends DefaultComboBoxModel { + @Override + public void setSelectedItem(@Nullable Object choice) { + if (choice instanceof JdkChoice jdkChoice && jdkChoice.usable()) { + super.setSelectedItem(choice); + } + } + + /** What the settings have, usable or not. */ + void show(JdkChoice stored) { + super.setSelectedItem(stored); + } + } + + private static final class JdkChoiceRenderer extends ColoredListCellRenderer { + @Override + protected void customizeCellRenderer( + JList list, + @Nullable JdkChoice choice, + int index, + boolean selected, + boolean focus) { + if (choice == null) { + return; + } + append( + choice.label().name(), + choice.usable() ? SimpleTextAttributes.REGULAR_ATTRIBUTES : SimpleTextAttributes.GRAYED_ATTRIBUTES); + append(" " + choice.label().detail(), SimpleTextAttributes.GRAYED_ATTRIBUTES); + } + } } diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatFormattingService.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatFormattingService.java index e503e6f22..0fedcc3d1 100644 --- a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatFormattingService.java +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatFormattingService.java @@ -52,8 +52,8 @@ class PalantirJavaFormatFormattingService extends AsyncDocumentFormattingService implements PluginAware { private static final Logger logger = Logger.getInstance(PalantirJavaFormatFormattingService.class); - private final FormatterProvider formatterProvider = - new FormatterProvider(() -> EmbeddedNativeImage.getInstance().installedPath()); + private final FormatterProvider formatterProvider = new FormatterProvider( + () -> EmbeddedNativeImage.getInstance().installedPath(), InProcessFormatters.IDE::unavailable); private final ImportOptimizer importOptimizer = new PalantirJavaFormatImportOptimizer(this); // The platform sets this right after creating the service from plugin.xml: the descriptor of the plugin that diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatSettings.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatSettings.java index d0d187571..add75a9f4 100644 --- a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatSettings.java +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatSettings.java @@ -88,13 +88,32 @@ Optional> getImplementationClassPath() { return state.implementationClassPath; } - /** Whether the native binary formats this project rather than the Java-based formatter. */ - boolean useNativeImage() { - return state.useNativeImage; + /** + * How the formatter runs. A file written before there was a choice says only whether the native binary runs: it + * goes on running, and every other project moves from a JVM of its own into the IDE's. + */ + FormatterMode getFormatterMode() { + for (var mode : FormatterMode.values()) { + if (mode.name().equals(state.formatterMode)) { + return mode; + } + } + return state.useNativeImage ? FormatterMode.NATIVE : FormatterMode.IN_PROCESS; + } + + void setFormatterMode(FormatterMode mode) { + state.formatterMode = mode.name(); + // All that a plugin from before the choice reads, in a file shared with one. + state.useNativeImage = mode == FormatterMode.NATIVE; } - void setUseNativeImage(boolean useNativeImage) { - state.useNativeImage = useNativeImage; + /** The JDK of the formatter's own JVM, for when it runs in one. */ + FormatterJdk getFormatterJdk() { + return FormatterJdk.parse(state.formatterJdk); + } + + void setFormatterJdk(FormatterJdk jdk) { + state.formatterJdk = jdk.stored(); } /** A native binary of the user's own, run instead of the embedded one. */ @@ -161,6 +180,12 @@ static class StoredSettings { public boolean useNativeImage = false; + @Nullable + public String formatterMode; + + @Nullable + public String formatterJdk; + @Nullable public String nativeImagePath; @@ -205,6 +230,10 @@ public String toString() { + implementationClassPath + ", useNativeImage=" + useNativeImage + + ", formatterMode=" + + formatterMode + + ", formatterJdk=" + + formatterJdk + ", nativeImagePath=" + nativeImagePath + '}'; diff --git a/open-java-format-idea-plugin/src/main/resources/META-INF/plugin.xml b/open-java-format-idea-plugin/src/main/resources/META-INF/plugin.xml index 06b45b020..49e149ae3 100644 --- a/open-java-format-idea-plugin/src/main/resources/META-INF/plugin.xml +++ b/open-java-format-idea-plugin/src/main/resources/META-INF/plugin.xml @@ -10,8 +10,8 @@ Formats Java code with open-java-format, a maintained fork of palantir-java-format: 120 columns, 4-space indents and lambda-friendly line breaking.

With the plugin enabled, Reformat Code runs open-java-format instead of the IDE's built-in Java formatter, and Optimize Imports removes unused imports and sorts the others as open-java-format does, so the IDE and your build produce identical files. The IDE's own Java code style settings no longer apply.

-

The formatter runs in a process of its own, on the IDE's runtime, so the project SDK can be any version. A project that applies the dev.openjavaformat.java-format Gradle plugin takes the formatter version from the build; every other project uses the version bundled with this plugin.

-

For many files at once, tick Use native binary on the plugin's settings page: the plugin downloads the formatter compiled to a native binary for your platform, which starts without a JVM, in a Maven, Gradle or any other project. A binary of your own works too.

+

The formatter runs inside the IDE, with no process to start for a file, whatever version the project SDK is. A project that applies the dev.openjavaformat.java-format Gradle plugin takes the formatter version from the build; every other project uses the version bundled with this plugin.

+

The plugin's settings page offers two other ways to run it. In a separate JVM runs it on the IDE's runtime, the project SDK or another JDK of the IDE, Java 21 or later, and parses the syntax of that JDK's version. Native binary runs the formatter compiled for your platform, which the plugin downloads, in a Maven, Gradle or any other project; a binary of your own works too.

Requires IntelliJ IDEA 2024.2 or later, or another IDE with Java support such as Android Studio.

]]> diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterProviderTest.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterProviderTest.java index 1dc3d138b..a4e5607e5 100644 --- a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterProviderTest.java +++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterProviderTest.java @@ -53,12 +53,52 @@ void tearDown() throws Exception { fixture.tearDown(); } + @Test + void formatsInsideTheIdeUnlessTheSettingsSayOtherwise() { + assertThat(new FormatterProvider(Optional::empty, Optional::empty).get(fixture.getProject(), settings)) + .get() + .isInstanceOf(InProcessFormatterService.class); + } + + @Test + void startsAJvmWhereTheIdeGivesNoAccessToJavac() { + var provider = new FormatterProvider(Optional::empty, () -> Optional.of("the IDE opens nothing")); + + assertThat(provider.get(fixture.getProject(), settings)) + .get() + .isInstanceOf(BootstrappingFormatterService.class) + .extracting("jdkPath") + .isEqualTo(FormatterJdks.ideRuntime().java()); + } + + @Test + void startsTheJvmOnTheJdkTheUserChose() { + // The formatter is cached: one created for a JDK must not outlive the choice of another. + var home = Path.of(System.getProperty("java.home")); + TestJdks.register("moved-here", home, "Eclipse Temurin 25", fixture.getTestRootDisposable()); + settings.setFormatterMode(FormatterMode.JVM); + var provider = new FormatterProvider(Optional::empty, Optional::empty); + + assertThat(provider.get(fixture.getProject(), settings)) + .get() + .extracting("jdkMajorVersion") + .isEqualTo(Runtime.version().feature()); + + settings.setFormatterJdk(new FormatterJdk.Named("moved-here")); + + assertThat(provider.get(fixture.getProject(), settings)) + .get() + .isInstanceOf(BootstrappingFormatterService.class) + .extracting("jdkPath", "jdkMajorVersion") + .containsExactly(home.resolve("bin").resolve("java"), 25); + } + @Test void runsTheBinaryTheUserChose() { - settings.setUseNativeImage(true); + settings.setFormatterMode(FormatterMode.NATIVE); settings.setNativeImagePath(Optional.of(Path.of("/opt/open-java-format"))); - assertThat(new FormatterProvider(Optional::empty).get(fixture.getProject(), settings)) + assertThat(new FormatterProvider(Optional::empty, Optional::empty).get(fixture.getProject(), settings)) .get() .isInstanceOf(NativeImageFormatterService.class); } @@ -66,9 +106,9 @@ void runsTheBinaryTheUserChose() { @Test void switchesToTheEmbeddedBinaryOnceItIsDownloaded() { // The formatter is cached: one created before the download must not outlive it. - settings.setUseNativeImage(true); + settings.setFormatterMode(FormatterMode.NATIVE); var embedded = new AtomicReference>(Optional.empty()); - var provider = new FormatterProvider(embedded::get); + var provider = new FormatterProvider(embedded::get, Optional::empty); assertThat(provider.get(fixture.getProject(), settings)) .get() diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterSelectionTest.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterSelectionTest.java index 79264a774..5f65ec37a 100644 --- a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterSelectionTest.java +++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterSelectionTest.java @@ -16,61 +16,173 @@ import static org.assertj.core.api.Assertions.assertThat; -import com.palantir.javaformat.intellij.FormatterSelection.JavaBased; +import com.palantir.javaformat.intellij.FormatterJdk.Resolved; +import com.palantir.javaformat.intellij.FormatterJdk.Unusable; +import com.palantir.javaformat.intellij.FormatterJdk.Usable; +import com.palantir.javaformat.intellij.FormatterSelection.Fallback; +import com.palantir.javaformat.intellij.FormatterSelection.InProcess; import com.palantir.javaformat.intellij.FormatterSelection.NativeImage; +import com.palantir.javaformat.intellij.FormatterSelection.SeparateJvm; import java.nio.file.Path; +import java.util.List; import java.util.Optional; -import java.util.function.Supplier; import org.junit.jupiter.api.Test; final class FormatterSelectionTest { private static final Path CUSTOM = Path.of("/opt/open-java-format"); private static final Path EMBEDDED = Path.of("/ide/system/open-java-format/native/21.0.1/open-java-format"); + private static final Usable IDE_RUNTIME = new Usable(Path.of("/ide/jbr/bin/java"), 21); + private static final Usable JDK_25 = new Usable(Path.of("/jdks/temurin-25/bin/java"), 25); + private static final String NO_JAVAC = "this IDE does not open java.lang to plugins"; + private static final String TOO_OLD = "temurin-17 is Java 17, and the formatter needs Java 21 or later"; private final PalantirJavaFormatSettings settings = new PalantirJavaFormatSettings(); + private final Machine machine = new Machine(); + + @Test + void formatsInsideTheIdeUnlessTheSettingsSayOtherwise() { + assertThat(FormatterSelection.of(settings, machine)).isEqualTo(new InProcess()); + } + + @Test + void formatsInAJvmOfItsOwnWhereTheIdeGivesNoAccessToJavac() { + machine.inProcessUnavailable = Optional.of(NO_JAVAC); + + assertThat(FormatterSelection.of(settings, machine)) + .isEqualTo( + new SeparateJvm(IDE_RUNTIME.java(), 21, List.of(new Fallback.InProcessUnavailable(NO_JAVAC)))); + } + + @Test + void runsTheJvmOnTheIdesRuntimeUnlessAJdkIsChosen() { + settings.setFormatterMode(FormatterMode.JVM); + + assertThat(FormatterSelection.of(settings, machine)) + .isEqualTo(new SeparateJvm(IDE_RUNTIME.java(), 21, List.of())); + } + + @Test + void runsTheJvmOnTheJdkTheUserChose() { + settings.setFormatterMode(FormatterMode.JVM); + settings.setFormatterJdk(new FormatterJdk.Named("temurin-25")); + machine.jdk = JDK_25; + + assertThat(FormatterSelection.of(settings, machine)).isEqualTo(new SeparateJvm(JDK_25.java(), 25, List.of())); + } + + @Test + void runsTheJvmOnTheIdesRuntimeWhenTheChosenJdkCannotRunTheFormatter() { + settings.setFormatterMode(FormatterMode.JVM); + settings.setFormatterJdk(new FormatterJdk.ProjectSdk()); + machine.jdk = new Unusable(TOO_OLD); + + assertThat(FormatterSelection.of(settings, machine)) + .isEqualTo(new SeparateJvm(IDE_RUNTIME.java(), 21, List.of(new Fallback.JdkUnusable(TOO_OLD)))); + } + + @Test + void usesTheChosenJdkWhenAnotherModeFallsBackToAJvm() { + // The JDK is kept whichever mode is on, and it is the JVM to fall back to. + settings.setFormatterJdk(new FormatterJdk.Named("temurin-25")); + machine.jdk = JDK_25; + machine.inProcessUnavailable = Optional.of(NO_JAVAC); + + assertThat(FormatterSelection.of(settings, machine)) + .isEqualTo(new SeparateJvm(JDK_25.java(), 25, List.of(new Fallback.InProcessUnavailable(NO_JAVAC)))); + } + + @Test + void saysEveryThingThatIsMissing() { + settings.setFormatterJdk(new FormatterJdk.Named("temurin-17")); + machine.jdk = new Unusable(TOO_OLD); + machine.inProcessUnavailable = Optional.of(NO_JAVAC); + + assertThat(FormatterSelection.of(settings, machine)) + .isEqualTo(new SeparateJvm( + IDE_RUNTIME.java(), + 21, + List.of(new Fallback.InProcessUnavailable(NO_JAVAC), new Fallback.JdkUnusable(TOO_OLD)))); + } @Test void runsTheBinaryTheUserChose() { - settings.setUseNativeImage(true); + settings.setFormatterMode(FormatterMode.NATIVE); settings.setNativeImagePath(Optional.of(CUSTOM)); + machine.embeddedNativeImage = Optional.of(EMBEDDED); - assertThat(FormatterSelection.of(settings, () -> Optional.of(EMBEDDED))) - .isEqualTo(new NativeImage(CUSTOM, false)); + assertThat(FormatterSelection.of(settings, machine)).isEqualTo(new NativeImage(CUSTOM, false)); } @Test void runsTheEmbeddedBinaryWithoutAPathOfTheUsersOwn() { - settings.setUseNativeImage(true); + settings.setFormatterMode(FormatterMode.NATIVE); + machine.embeddedNativeImage = Optional.of(EMBEDDED); - assertThat(FormatterSelection.of(settings, () -> Optional.of(EMBEDDED))) - .isEqualTo(new NativeImage(EMBEDDED, true)); + assertThat(FormatterSelection.of(settings, machine)).isEqualTo(new NativeImage(EMBEDDED, true)); } @Test - void fallsBackToTheJavaBasedFormatterWithoutABinary() { - settings.setUseNativeImage(true); + void fallsBackToAJvmWithoutABinary() { + settings.setFormatterMode(FormatterMode.NATIVE); - assertThat(FormatterSelection.of(settings, Optional::empty)).isEqualTo(new JavaBased(true)); + assertThat(FormatterSelection.of(settings, machine)) + .isEqualTo(new SeparateJvm(IDE_RUNTIME.java(), 21, List.of(new Fallback.NativeImageMissing()))); } @Test - void runsTheJavaBasedFormatterUnlessTheNativeOneIsOn() { + void runsNoBinaryUnlessTheNativeFormatterIsOn() { settings.setNativeImagePath(Optional.of(CUSTOM)); + machine.embeddedNativeImage = Optional.of(EMBEDDED); - assertThat(FormatterSelection.of(settings, () -> Optional.of(EMBEDDED))).isEqualTo(new JavaBased(false)); + assertThat(FormatterSelection.of(settings, machine)).isEqualTo(new InProcess()); } @Test - void looksForTheEmbeddedBinaryOnlyWhenItWouldRun() { - // It is asked for every file formatted, and most projects run the Java-based formatter. - Supplier> unasked = () -> { - throw new AssertionError("the embedded binary was looked for"); + void looksOnlyForWhatWouldRun() { + // It is asked for every file formatted: the embedded binary lists a directory, a JDK is looked up in the IDE. + var unasked = new Machine() { + @Override + public Optional embeddedNativeImage() { + throw new AssertionError("the embedded binary was looked for"); + } + + @Override + public Resolved resolve(FormatterJdk chosen) { + throw new AssertionError("the JDK was looked for"); + } }; settings.setNativeImagePath(Optional.of(CUSTOM)); - assertThat(FormatterSelection.of(settings, unasked)).isEqualTo(new JavaBased(false)); - settings.setUseNativeImage(true); + assertThat(FormatterSelection.of(settings, unasked)).isEqualTo(new InProcess()); + settings.setFormatterMode(FormatterMode.NATIVE); assertThat(FormatterSelection.of(settings, unasked)).isEqualTo(new NativeImage(CUSTOM, false)); } + + /** An IDE whose JVM reaches javac, with no native binary downloaded, and one JDK besides its runtime. */ + private static class Machine implements FormatterSelection.Environment { + Optional inProcessUnavailable = Optional.empty(); + Optional embeddedNativeImage = Optional.empty(); + Resolved jdk = new Unusable("there is no such JDK"); + + @Override + public Optional inProcessUnavailable() { + return inProcessUnavailable; + } + + @Override + public Resolved resolve(FormatterJdk chosen) { + return chosen instanceof FormatterJdk.IdeRuntime ? IDE_RUNTIME : jdk; + } + + @Override + public Usable ideRuntime() { + return IDE_RUNTIME; + } + + @Override + public Optional embeddedNativeImage() { + return embeddedNativeImage; + } + } } diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/NativeImageNoticeStartupActivityTest.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/NativeImageNoticeStartupActivityTest.java index 561442d6d..81d18d42b 100644 --- a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/NativeImageNoticeStartupActivityTest.java +++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/NativeImageNoticeStartupActivityTest.java @@ -39,7 +39,7 @@ final class NativeImageNoticeStartupActivityTest { @BeforeEach void setUp() { settings.setEnabled(true); - settings.setUseNativeImage(true); + settings.setFormatterMode(FormatterMode.NATIVE); } @Test @@ -67,16 +67,16 @@ void staysQuietAboutAVersionTheUserIgnored() { void staysQuietWhenTheEmbeddedBinaryDoesNotRun() { var custom = new PalantirJavaFormatSettings(); custom.setEnabled(true); - custom.setUseNativeImage(true); + custom.setFormatterMode(FormatterMode.NATIVE); custom.setNativeImagePath(Optional.of(Path.of("/opt/open-java-format"))); - var javaBased = new PalantirJavaFormatSettings(); - javaBased.setEnabled(true); + var inProcess = new PalantirJavaFormatSettings(); + inProcess.setEnabled(true); var disabled = new PalantirJavaFormatSettings(); - disabled.setUseNativeImage(true); + disabled.setFormatterMode(FormatterMode.NATIVE); assertThat(NativeImageNoticeStartupActivity.notice(custom, OUTDATED, null)) .isEmpty(); - assertThat(NativeImageNoticeStartupActivity.notice(javaBased, OUTDATED, null)) + assertThat(NativeImageNoticeStartupActivity.notice(inProcess, OUTDATED, null)) .isEmpty(); assertThat(NativeImageNoticeStartupActivity.notice(disabled, OUTDATED, null)) .isEmpty(); diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurableTest.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurableTest.java index c20c7c5f2..86c6f9312 100644 --- a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurableTest.java +++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurableTest.java @@ -22,6 +22,7 @@ import com.intellij.application.options.CodeStyle; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurationException; +import com.intellij.openapi.Disposable; import com.intellij.openapi.ui.ComboBox; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.testFramework.EdtTestUtil; @@ -31,6 +32,7 @@ import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture; import com.intellij.testFramework.fixtures.JavaTestFixtureFactory; import com.intellij.testFramework.fixtures.TestFixtureBuilder; +import com.intellij.ui.SimpleColoredComponent; import com.intellij.ui.components.ActionLink; import com.palantir.javaformat.intellij.EmbeddedNativeImage.Installed; import com.palantir.javaformat.intellij.EmbeddedNativeImage.Status; @@ -44,9 +46,12 @@ import java.util.Arrays; import java.util.List; import java.util.Optional; +import java.util.stream.IntStream; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JRadioButton; import javax.swing.JTextArea; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -63,10 +68,16 @@ final class PalantirJavaFormatConfigurableTest { @TempDir private Path dir; + private static final String IN_PROCESS = "In the IDE process"; + private static final String SEPARATE_JVM = "In a separate JVM"; + private static final String NATIVE = "Native binary"; + private JavaCodeInsightTestFixture fixture; private PalantirJavaFormatSettings settings; + private EmbeddedNativeImage embedded; private PalantirJavaFormatConfigurable configurable; private JComponent component; + private Disposable untilTheTestEnds; @BeforeEach void setUp() throws Exception { @@ -77,10 +88,12 @@ void setUp() throws Exception { settings = PalantirJavaFormatSettings.getInstance(fixture.getProject()); settings.loadState(new StoredSettings()); settings.setEnabled(true); + untilTheTestEnds = fixture.getTestRootDisposable(); // Nothing downloaded, and nowhere to download from. - var embedded = new EmbeddedNativeImage( + embedded = new EmbeddedNativeImage( dir.resolve("native"), Optional.of(new NativePlatform("macos", "aarch64")), "http://127.0.0.1:1"); - configurable = new PalantirJavaFormatConfigurable(fixture.getProject(), embedded); + // An IDE whose JVM lets the formatter reach javac. + configurable = new PalantirJavaFormatConfigurable(fixture.getProject(), embedded, Optional::empty); component = requireNonNull(configurable.createComponent()); } @@ -93,14 +106,153 @@ void tearDown() throws Exception { @Test void buildsAPanelWithItsControls() { assertThat(findCheckBox("Enable open-java-format")).isNotNull(); - assertThat(findCheckBox("Use native binary")).isNotNull(); + assertThat(findAll(component, JRadioButton.class)) + .extracting(JRadioButton::getText) + .containsExactly(IN_PROCESS, SEPARATE_JVM, NATIVE); assertThat(findAll(component, TextFieldWithBrowseButton.class)).hasSize(1); } @Test void hasNoChoiceOfCodeStyle() { - // There is one style, so the page does not offer a list of them. - assertThat(findAll(component, ComboBox.class)).isEmpty(); + // There is one style, so the page does not offer a list of them: its one list is of JDKs. + assertThat(findAll(component, ComboBox.class)).hasSize(1); + } + + @Test + void runsTheFormatterInOneWayAtATime() throws Throwable { + EdtTestUtil.runInEdtAndWait(() -> { + configurable.reset(); + assertThat(selectedModes()).containsExactly(IN_PROCESS); + + findRadioButton(NATIVE).setSelected(true); + assertThat(selectedModes()).containsExactly(NATIVE); + + findRadioButton(SEPARATE_JVM).setSelected(true); + assertThat(selectedModes()).containsExactly(SEPARATE_JVM); + }); + } + + @Test + void readsAndWritesTheMode() throws Throwable { + settings.setFormatterMode(FormatterMode.JVM); + + EdtTestUtil.runInEdtAndWait(() -> { + configurable.reset(); + assertThat(selectedModes()).containsExactly(SEPARATE_JVM); + assertThat(configurable.isModified()).isFalse(); + + findRadioButton(IN_PROCESS).setSelected(true); + assertThat(configurable.isModified()).isTrue(); + configurable.apply(); + }); + + assertThat(settings.getFormatterMode()).isEqualTo(FormatterMode.IN_PROCESS); + } + + @Test + void greysTheIdeProcessOutWhereTheFormatterCannotReachJavac() throws Throwable { + openThePageOfAnIdeWithout("this IDE does not open java.lang to plugins"); + var ideRuntime = FormatterJdks.ideRuntime(); + + EdtTestUtil.runInEdtAndWait(() -> { + configurable.reset(); + + // What the settings have stays selected, with the reason under it and what runs instead at the bottom. + assertThat(selectedModes()).containsExactly(IN_PROCESS); + assertThat(findRadioButton(IN_PROCESS).isEnabled()).isFalse(); + assertThat(findAll(component, JLabel.class)) + .extracting(JLabel::getText) + .contains("Not available: this IDE does not open java.lang to plugins."); + assertThat(activeFormatter().getText()) + .isEqualTo( + "%s (Java %s)\nA JVM of its own: the IDE process is not available.", + ideRuntime.java(), ideRuntime.javaVersion()); + assertThat(configurable.isModified()).isFalse(); + }); + } + + @Test + void saysWhatTheIdeProcessIsGoodFor() throws Throwable { + EdtTestUtil.runInEdtAndWait(() -> { + configurable.reset(); + + assertThat(findRadioButton(IN_PROCESS).isEnabled()).isTrue(); + assertThat(findAll(component, JLabel.class)) + .extracting(JLabel::getText) + .contains("Fastest: nothing to start. The IDE's own Java " + + Runtime.version().feature() + " parses the code."); + }); + } + + @Test + void listsTheJdksThatCanRunTheFormatterAndGreysOutTheOthers() throws Throwable { + TestJdks.running("this-jdk", untilTheTestEnds); + TestJdks.register("temurin-17", dir, "Eclipse Temurin 17.0.9", untilTheTestEnds); + + EdtTestUtil.runInEdtAndWait(() -> { + configurable.reset(); + var jdk = jdk(); + assertThat(jdkLabels()).startsWith("IDE runtime", "Project SDK").contains("this-jdk", "temurin-17"); + assertThat(selectedJdkLabel()).isEqualTo("IDE runtime"); + + jdk.setSelectedIndex(jdkLabels().indexOf("this-jdk")); + assertThat(selectedJdkLabel()).isEqualTo("this-jdk"); + + // Java 17 does not run the formatter: it is listed, to say why it is no choice, and stays unchosen. + jdk.setSelectedIndex(jdkLabels().indexOf("temurin-17")); + assertThat(selectedJdkLabel()).isEqualTo("this-jdk"); + }); + } + + @Test + void readsAndWritesTheJdk() throws Throwable { + TestJdks.running("this-jdk", untilTheTestEnds); + settings.setFormatterMode(FormatterMode.JVM); + settings.setFormatterJdk(new FormatterJdk.Named("this-jdk")); + + EdtTestUtil.runInEdtAndWait(() -> { + configurable.reset(); + assertThat(selectedJdkLabel()).isEqualTo("this-jdk"); + assertThat(configurable.isModified()).isFalse(); + assertThat(activeFormatter().getText()) + .isEqualTo( + "%s (Java %s)", + Path.of(System.getProperty("java.home"), "bin", "java"), + Runtime.version().feature()); + + jdk().setSelectedIndex(jdkLabels().indexOf("IDE runtime")); + assertThat(configurable.isModified()).isTrue(); + configurable.apply(); + }); + + assertThat(settings.getFormatterJdk()).isEqualTo(new FormatterJdk.IdeRuntime()); + } + + @Test + void refusesAJdkThatNoLongerRunsTheFormatter() throws Throwable { + // Chosen when the IDE had it. The page shows what the settings have, and what runs instead. + settings.setFormatterMode(FormatterMode.JVM); + settings.setFormatterJdk(new FormatterJdk.Named("gone")); + var ideRuntime = FormatterJdks.ideRuntime(); + + EdtTestUtil.runInEdtAndWait(() -> { + configurable.reset(); + assertThat(selectedJdkLabel()).isEqualTo("gone"); + assertThat(activeFormatter().getText()) + .isEqualTo( + "%s (Java %s)\nThe IDE's runtime: there is no JDK named gone.", + ideRuntime.java(), ideRuntime.javaVersion()); + + assertThatThrownBy(configurable::apply) + .isInstanceOf(ConfigurationException.class) + .hasMessage("Choose another JDK: there is no JDK named gone"); + + // Only the JVM needs it. + findRadioButton(IN_PROCESS).setSelected(true); + configurable.apply(); + }); + + assertThat(settings.getFormatterMode()).isEqualTo(FormatterMode.IN_PROCESS); } @Test @@ -161,54 +313,77 @@ void hasNoRowsOfVersions() { } @Test - void showsTheNativeBinaryOnlyWhileOpenJavaFormatIsOn() throws Throwable { + void asksNothingOfTheChoicesOnceOpenJavaFormatIsSwitchedOff() throws Throwable { + // They are not on the page then, so there is nothing on it to put right. + settings.setFormatterMode(FormatterMode.JVM); + settings.setFormatterJdk(new FormatterJdk.Named("gone")); + + EdtTestUtil.runInEdtAndWait(() -> { + configurable.reset(); + findCheckBox("Enable open-java-format").setSelected(false); + configurable.apply(); + + configurable.reset(); + findRadioButton(NATIVE).setSelected(true); + configurable.apply(); + }); + + assertThat(settings.isEnabled()).isFalse(); + assertThat(settings.getFormatterMode()).isEqualTo(FormatterMode.NATIVE); + } + + @Test + void showsTheWaysToRunTheFormatterOnlyWhileOpenJavaFormatIsOn() throws Throwable { EdtTestUtil.runInEdtAndWait(() -> { var enable = findCheckBox("Enable open-java-format"); - var useNativeImage = findCheckBox("Use native binary"); + var nativeImage = findRadioButton(NATIVE); var path = findAll(component, TextFieldWithBrowseButton.class).get(0); - settings.setUseNativeImage(true); configurable.reset(); - assertThat(isDisplayed(useNativeImage)).isTrue(); + assertThat(isDisplayed(nativeImage)).isTrue(); assertThat(isDisplayed(path)).isTrue(); enable.setSelected(false); - assertThat(isDisplayed(useNativeImage)).isFalse(); + assertThat(isDisplayed(findRadioButton(IN_PROCESS))).isFalse(); + assertThat(isDisplayed(nativeImage)).isFalse(); assertThat(isDisplayed(path)).isFalse(); assertThat(isDisplayed(activeFormatter())).isFalse(); enable.setSelected(true); - assertThat(isDisplayed(useNativeImage)).isTrue(); + assertThat(isDisplayed(nativeImage)).isTrue(); assertThat(isDisplayed(path)).isTrue(); }); } @Test void showsTheActiveFormatterAsThePageStands() throws Throwable { - // What runs once the page is applied, so it follows the boxes and the path as they change. + // What runs once the page is applied, so it follows the choices and the path as they change. var pluginVersion = settings.getImplementationVersion().orElseThrow(); + var ideRuntime = FormatterJdks.ideRuntime(); + EdtTestUtil.runInEdtAndWait(() -> { - var useNativeImage = findCheckBox("Use native binary"); var path = findAll(component, TextFieldWithBrowseButton.class).get(0); configurable.reset(); - assertThat(activeFormatter().getText()).isEqualTo("Java-based formatter"); + assertThat(activeFormatter().getText()) + .isEqualTo("The IDE process (Java %s)", System.getProperty("java.version")); - useNativeImage.setSelected(true); + findRadioButton(NATIVE).setSelected(true); assertThat(activeFormatter().getText()) .isEqualTo("Need to download version %s from Maven Central", pluginVersion); path.setText("/opt/open-java-format"); assertThat(activeFormatter().getText()).isEqualTo("/opt/open-java-format"); - useNativeImage.setSelected(false); - assertThat(activeFormatter().getText()).isEqualTo("Java-based formatter"); + findRadioButton(SEPARATE_JVM).setSelected(true); + assertThat(activeFormatter().getText()) + .isEqualTo("%s (Java %s)", ideRuntime.java(), ideRuntime.javaVersion()); }); } @Test void showsTheEmbeddedBinaryOnceItIsThere() throws Throwable { var binary = installByHand("21.0.1"); - settings.setUseNativeImage(true); + settings.setFormatterMode(FormatterMode.NATIVE); EdtTestUtil.runInEdtAndWait(() -> { configurable.reset(); @@ -227,29 +402,35 @@ void showsTheVersionOfThePlugin() { } @Test - void showsTheNativeOptionsOnlyWithTheNativeBinaryOn() throws Throwable { + void offersTheOptionsOfTheChosenWayOnly() throws Throwable { + // The others stay on the page, greyed: hidden, they would move the page about with every choice. EdtTestUtil.runInEdtAndWait(() -> { - var useNativeImage = findCheckBox("Use native binary"); var path = findAll(component, TextFieldWithBrowseButton.class).get(0); configurable.reset(); - assertThat(isDisplayed(path)).isFalse(); + assertThat(path.isEnabled()).isFalse(); + assertThat(jdk().isEnabled()).isFalse(); - useNativeImage.setSelected(true); - assertThat(isDisplayed(path)).isTrue(); + findRadioButton(NATIVE).setSelected(true); + assertThat(path.isEnabled()).isTrue(); + assertThat(jdk().isEnabled()).isFalse(); + + findRadioButton(SEPARATE_JVM).setSelected(true); + assertThat(path.isEnabled()).isFalse(); + assertThat(jdk().isEnabled()).isTrue(); }); } @Test void readsAndWritesTheNativeBinarySettings() throws Throwable { var binary = executable("open-java-format"); - settings.setUseNativeImage(true); + settings.setFormatterMode(FormatterMode.NATIVE); EdtTestUtil.runInEdtAndWait(() -> { var path = findAll(component, TextFieldWithBrowseButton.class).get(0); configurable.reset(); - assertThat(findCheckBox("Use native binary").isSelected()).isTrue(); + assertThat(selectedModes()).containsExactly(NATIVE); assertThat(path.getText()).isEmpty(); assertThat(configurable.isModified()).isFalse(); @@ -258,7 +439,7 @@ void readsAndWritesTheNativeBinarySettings() throws Throwable { configurable.apply(); }); - assertThat(settings.useNativeImage()).isTrue(); + assertThat(settings.getFormatterMode()).isEqualTo(FormatterMode.NATIVE); assertThat(settings.getNativeImagePath()).hasValue(binary); } @@ -266,14 +447,14 @@ void readsAndWritesTheNativeBinarySettings() throws Throwable { void refusesTheNativeBinaryWithoutABinary() throws Throwable { EdtTestUtil.runInEdtAndWait(() -> { configurable.reset(); - findCheckBox("Use native binary").setSelected(true); + findRadioButton(NATIVE).setSelected(true); assertThatThrownBy(configurable::apply) .isInstanceOf(ConfigurationException.class) .hasMessage("Download the embedded version or choose a binary"); }); - assertThat(settings.useNativeImage()).isFalse(); + assertThat(settings.getFormatterMode()).isNotEqualTo(FormatterMode.NATIVE); } @Test @@ -282,7 +463,7 @@ void refusesAPathThatIsNotAnExecutableFile() throws Throwable { EdtTestUtil.runInEdtAndWait(() -> { configurable.reset(); - findCheckBox("Use native binary").setSelected(true); + findRadioButton(NATIVE).setSelected(true); findAll(component, TextFieldWithBrowseButton.class).get(0).setText(missing.toString()); assertThatThrownBy(configurable::apply) @@ -312,7 +493,7 @@ void wrapsTheActiveFormatterAndLetsItsPathBeCopied() throws Throwable { // the dialog, and a label would not let anyone copy it. A long path of one's own in Binary must not either. var path = Path.of("/Users/someone/Library/Caches/JetBrains/IntelliJIdea2026.2/open-java-format/native/" + "21.0.1/".repeat(40) + "open-java-format-macos_aarch64"); - settings.setUseNativeImage(true); + settings.setFormatterMode(FormatterMode.NATIVE); settings.setNativeImagePath(Optional.of(path)); EdtTestUtil.runInEdtAndWait(() -> { @@ -355,6 +536,14 @@ void describesEveryStateOfTheEmbeddedBinary() { }); } + /** The page as an IDE shows it whose JVM does not let the formatter reach javac. */ + private void openThePageOfAnIdeWithout(String javacAccess) { + configurable.disposeUIResources(); + configurable = + new PalantirJavaFormatConfigurable(fixture.getProject(), embedded, () -> Optional.of(javacAccess)); + component = requireNonNull(configurable.createComponent()); + } + private JCheckBox findCheckBox(String text) { return findAll(component, JCheckBox.class).stream() .filter(checkBox -> checkBox.getText().equals(text)) @@ -362,6 +551,46 @@ private JCheckBox findCheckBox(String text) { .orElseThrow(); } + private JRadioButton findRadioButton(String text) { + return findAll(component, JRadioButton.class).stream() + .filter(radioButton -> radioButton.getText().equals(text)) + .findFirst() + .orElseThrow(); + } + + private List selectedModes() { + return findAll(component, JRadioButton.class).stream() + .filter(JRadioButton::isSelected) + .map(JRadioButton::getText) + .toList(); + } + + /** The page's one list. */ + private ComboBox jdk() { + return findAll(component, ComboBox.class).stream().collect(onlyElement()); + } + + /** The names in the list of JDKs, without what stands beside them in grey. */ + private List jdkLabels() { + var model = jdk().getModel(); + return IntStream.range(0, model.getSize()) + .mapToObj(index -> jdkLabel(model.getElementAt(index))) + .toList(); + } + + private String selectedJdkLabel() { + return jdkLabel(requireNonNull(jdk().getSelectedItem())); + } + + /** As the list draws the JDK. */ + @SuppressWarnings({"unchecked", "rawtypes"}) + private String jdkLabel(Object choice) { + var jdk = (ComboBox) jdk(); + var drawn = (SimpleColoredComponent) + jdk.getRenderer().getListCellRendererComponent(new JList<>(), choice, 0, false, false); + return drawn.getCharSequence(true).toString(); + } + /** Whether the component and every container up to the page are visible. */ private boolean isDisplayed(Component target) { for (var current = target; current != null && current != component; current = current.getParent()) { diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatSettingsTest.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatSettingsTest.java index 8a7eae315..fa4a9d25a 100644 --- a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatSettingsTest.java +++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatSettingsTest.java @@ -52,16 +52,101 @@ void doesNotWriteACodeStyle() { @Test void keepsTheNativeBinarySettings() throws Exception { var settings = new PalantirJavaFormatSettings(); - settings.setUseNativeImage(true); + settings.setFormatterMode(FormatterMode.NATIVE); settings.setNativeImagePath(Optional.of(Path.of("/opt/open-java-format"))); - var reloaded = new PalantirJavaFormatSettings(); - reloaded.loadState(deserialize(JDOMUtil.write(XmlSerializer.serialize(settings.getState())))); + var reloaded = reload(settings); - assertThat(reloaded.useNativeImage()).isTrue(); + assertThat(reloaded.getFormatterMode()).isEqualTo(FormatterMode.NATIVE); assertThat(reloaded.getNativeImagePath()).hasValue(Path.of("/opt/open-java-format")); } + @Test + void keepsTheNativeBinaryOfAFileWrittenBeforeThereWereModes() throws Exception { + var settings = new PalantirJavaFormatSettings(); + settings.loadState(deserialize(""" + + + """)); + + assertThat(settings.getFormatterMode()).isEqualTo(FormatterMode.NATIVE); + } + + @Test + void movesAProjectThatFormattedInAJvmOfItsOwnIntoTheIde() throws Exception { + // Before there were modes, a project without the native binary started a JVM for every file. + var settings = new PalantirJavaFormatSettings(); + settings.loadState(deserialize(""" + + + """)); + + assertThat(settings.getFormatterMode()).isEqualTo(FormatterMode.IN_PROCESS); + assertThat(new PalantirJavaFormatSettings().getFormatterMode()).isEqualTo(FormatterMode.IN_PROCESS); + } + + @Test + void keepsTheModeAndTheJdk() throws Exception { + var settings = new PalantirJavaFormatSettings(); + settings.setFormatterMode(FormatterMode.JVM); + settings.setFormatterJdk(new FormatterJdk.Named("temurin-25")); + + var reloaded = reload(settings); + + assertThat(reloaded.getFormatterMode()).isEqualTo(FormatterMode.JVM); + assertThat(reloaded.getFormatterJdk()).isEqualTo(new FormatterJdk.Named("temurin-25")); + } + + @Test + void keepsTheProjectSdkAsTheJdk() throws Exception { + var settings = new PalantirJavaFormatSettings(); + settings.setFormatterJdk(new FormatterJdk.ProjectSdk()); + + assertThat(reload(settings).getFormatterJdk()).isEqualTo(new FormatterJdk.ProjectSdk()); + } + + @Test + void runsTheJvmOnTheIdesRuntimeUnlessAJdkIsStored() throws Exception { + var settings = new PalantirJavaFormatSettings(); + assertThat(settings.getFormatterJdk()).isEqualTo(new FormatterJdk.IdeRuntime()); + + settings.setFormatterJdk(new FormatterJdk.Named("temurin-25")); + settings.setFormatterJdk(new FormatterJdk.IdeRuntime()); + + // It has no name to store: the file says nothing, as a file from before the choice of a JDK does. + assertThat(settings.getState().formatterJdk).isNull(); + assertThat(reload(settings).getFormatterJdk()).isEqualTo(new FormatterJdk.IdeRuntime()); + } + + @Test + void tellsAPluginFromBeforeTheModesWhetherTheNativeBinaryRuns() { + // A plugin from before the modes reads useNativeImage alone, in a file a team shares. + var settings = new PalantirJavaFormatSettings(); + + settings.setFormatterMode(FormatterMode.NATIVE); + assertThat(settings.getState().useNativeImage).isTrue(); + + settings.setFormatterMode(FormatterMode.JVM); + assertThat(settings.getState().useNativeImage).isFalse(); + } + + @Test + void takesAModeItDoesNotKnowForNone() throws Exception { + // A later plugin can have modes that this one has not. + var settings = new PalantirJavaFormatSettings(); + settings.loadState(deserialize(""" + + + """)); + + assertThat(settings.getFormatterMode()).isEqualTo(FormatterMode.NATIVE); + } + @Test void keepsTheImplementationClassPath() throws Exception { var state = new StoredSettings(); @@ -86,7 +171,7 @@ void ignoresTheNativeImageTheGradlePluginUsedToWrite() throws Exception { """)); - assertThat(settings.useNativeImage()).isFalse(); + assertThat(settings.getFormatterMode()).isNotEqualTo(FormatterMode.NATIVE); assertThat(settings.getNativeImagePath()).isEmpty(); } @@ -100,6 +185,13 @@ void takesABlankPathForNone() { assertThat(settings.getNativeImagePath()).isEmpty(); } + /** The settings as a project reads them back from the file they were written to. */ + private static PalantirJavaFormatSettings reload(PalantirJavaFormatSettings settings) throws Exception { + var reloaded = new PalantirJavaFormatSettings(); + reloaded.loadState(deserialize(JDOMUtil.write(XmlSerializer.serialize(settings.getState())))); + return reloaded; + } + private static StoredSettings deserialize(@Language("xml") String xml) throws Exception { return XmlSerializer.deserialize(JDOMUtil.load(xml), StoredSettings.class); } From d929bed8a3ad37d2fb34425754cb1427a6f0218b Mon Sep 17 00:00:00 2001 From: Alex Abashev Date: Mon, 23 Nov 2026 00:30:22 +0300 Subject: [PATCH 4/5] Record ADR-005: the IntelliJ plugin formats inside the IDE's JVM Why the formatter runs inside the IDE by default, how it reaches javac there without anyone editing VM options, why it is loaded apart from the IDE's classes, and what was rejected: a formatter daemon, asking users for --add-exports, the plugin's class loader as the formatter's parent, and leaving a JVM for each call as the default. --- .../ADR-005-formatting-inside-the-ide.md | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 docs/decisions/ADR-005-formatting-inside-the-ide.md diff --git a/docs/decisions/ADR-005-formatting-inside-the-ide.md b/docs/decisions/ADR-005-formatting-inside-the-ide.md new file mode 100644 index 000000000..718b6a043 --- /dev/null +++ b/docs/decisions/ADR-005-formatting-inside-the-ide.md @@ -0,0 +1,66 @@ +# ADR-005: The IntelliJ plugin formats inside the IDE's JVM, and offers a JVM of its own and the native binary + +## Status +Accepted + +## Date +2026-11-22 + +## Context + +The plugin started a process for every Reformat and every Optimize imports: a new JVM on the IDE's runtime, or the native binary. Optimize imports runs under a read action, and "Optimize imports on the fly" runs while typing ([ADR-003](ADR-003-imports-in-intellij-idea.md), #253). + +One call on JDK 21, macOS aarch64, with 21.0.2 (#223): + +| How the formatter runs | `JavaInputAstVisitor.java`, 4,026 lines | A 5-line file | +|---|---|---| +| A new JVM for each call | 0.97 s | 0.3 s | +| Native binary | 0.28 s | 0.02 s | +| In the IDE's JVM, first call | 0.65 s | | +| In the IDE's JVM, warm (median of 30) | 124 ms to format, 9 ms for `fixImports` | | + +The formatter parses with javac's own classes, in packages that module `jdk.compiler` exports to nobody. A JVM started for the formatter gets `--add-exports`; the IDE's JVM is already running. google-java-format formats inside the IDE and asks its users to add six `--add-exports` lines to the IDE's VM options. + +IntelliJ IDEA starts its JVM with `--add-opens=java.base/java.lang=ALL-UNNAMED`: it is among the `additionalJvmArguments` of `product-info.json` in 2024.2.6, the oldest IDE the plugin supports, and in 2026.3. With `java.lang` open, a plugin can call `Module.implAddExports`, the method `--add-exports` ends in, for one class loader's module. Tried on Temurin 21.0.12 and on the JBR 25.0.4 of 2026.3, in a JVM started with that flag alone: the formatter, in a class loader of its own, formats as the command line does, and javac stays unexported to every other class loader. + +## Decision + +- **Three ways to run the formatter, one of them chosen per project** on the settings page: in the IDE process, in a separate JVM, as the native binary. +- **In the IDE process is the default.** A project whose settings switch the native binary on keeps it; every other project moves from a JVM for each call into the IDE. +- **The plugin exports javac to the formatter itself**, with `Module.implAddExports`, to the formatter's class loader only. Nobody edits VM options. The settings page offers the IDE process only where `JavacAccess` finds that it can: `jdk.compiler` is there, and either javac is exported already or `java.lang` is open. +- **The formatter is loaded apart from the IDE.** Its class loader's parent is the JDK's platform class loader, which finds javac and nothing of the IDE. From the plugin come only the types the two exchange: the classes of `open-java-format-spi`, and Guava, which their signatures name. One class loader per set of formatter jars, kept across projects and calls. +- **The IDE process is the faster way, never the only one.** A file that the formatter fails on there with an `Error`, a stack overflow for one, is formatted in a separate JVM on the IDE's runtime. A formatter that does not load or link there sends every file to a separate JVM until the IDE restarts, and logs an error once, for the plugin's error reports. +- **A file with a syntax error is left alone without a message** inside the IDE too, as `FormatterCommandRunner` leaves it: a file is rarely free of them while it is typed in. +- **A separate JVM runs on a JDK the user chooses**: the IDE's runtime, which is the default and what the plugin ran on before, the project SDK, or a JDK registered in the IDE. Only Java 21 or later can be chosen. +- **What cannot run falls back, and says so in `idea.log` and under Active formatter**: the IDE process to a separate JVM, a JDK that cannot run the formatter to the IDE's runtime, a missing native binary to a separate JVM as before. No balloon for the first two. + +## Alternatives Considered + +### A formatter daemon, as Gradle has one +- Pros: as fast once warm; a formatter bug stays out of the IDE; it can run on a newer JDK than the IDE's. +- Cons: a server mode in `Main`, a protocol, restarts and cleanup. +- Rejected: worth it only if formatting inside the IDE turned out not to work. + +### Ask users to add `--add-exports` to the IDE's VM options, as google-java-format does +- Pros: public flags only. +- Cons: every user edits a file per IDE installation, and javac is exported to every plugin. +- Rejected as the way in; a user who did add the flags gets the IDE process without `implAddExports` being called. + +### Load the formatter with the plugin's class loader as the parent, as the Gradle plugin does +- Pros: a plain `URLClassLoader`. +- Cons: every class the IDE has wins over the formatter's own copy: Jackson of another version, for one, and whatever a later IDE adds. +- Rejected: the IDE's class path is not ours to know. + +### Keep a JVM for each call as the default, and the IDE process as an option +- Pros: a formatter bug cannot touch the IDE until a user opts in. +- Cons: the projects that wait 0.3 s to 1 s a file, and for imports while typing, stay there unless they find the setting. +- Rejected: the time is what #223 is about. + +## Consequences + +- `Module.implAddExports` is not public API. If JetBrains stops opening `java.lang`, or a JDK drops the method, the IDE process is greyed out with the reason, and those projects format in a separate JVM as before. +- The javac of the IDE's runtime decides which syntax parses inside the IDE: Java 21 in 2024.2, Java 25 in 2026.3. A project with newer syntax chooses a separate JVM on a newer JDK. +- A formatter bug that throws no `Error`, such as one that never returns, now happens inside the IDE. +- A formatter from a build is loaded into the IDE's JVM where it used to be run by a JVM of its own. Both happen only in a trusted project. +- A formatter from a build that needs a newer Guava than the plugin's can fail to link inside the IDE. It then runs in a separate JVM, on its own jars alone, and so does every other project's formatter until the IDE restarts: one failure switches the IDE process off for the session. +- A project whose `.idea/open-java-format.xml` is shared keeps `useNativeImage` in it beside the new `formatterMode`, for plugins from before the modes. From 0050bea6a13f1d973b1fd76a446adc3fb0066663 Mon Sep 17 00:00:00 2001 From: Alex Abashev Date: Mon, 23 Nov 2026 13:41:40 +0300 Subject: [PATCH 5/5] Say the formatter's mode in one setting, and name a mode's settings after it The settings said how the formatter runs twice: formatterMode, and beside it useNativeImage, written with every mode for a plugin from before the modes. And the JDK of the separate JVM was formatterJdk, which a mode added later, a daemon with a JDK of its own for one, could not tell from its own. formatterMode alone says it now, as in-process, jvm or native: words of the file's own, which stay when a constant is renamed. A file from before the modes has useNativeImage instead. It is read once, when the file is loaded: true switches the project to native, and the setting is emptied, so the IDE writes the file without it from then on. With neither, or with a mode this plugin does not know, a project formats inside the IDE. A setting of one mode has that mode at the start of its name: jvmJdk, which was formatterJdk and was not released under that name, and nativeImagePath, which keeps the name it was released with. A plugin from before the modes that reads a file written since finds no useNativeImage, and formats in a JVM of its own. ADR-005 says so. --- .../ADR-005-formatting-inside-the-ide.md | 3 +- .../javaformat/intellij/FormatterMode.java | 28 ++++- .../intellij/FormatterSelection.java | 2 +- .../PalantirJavaFormatConfigurable.java | 8 +- .../intellij/PalantirJavaFormatSettings.java | 54 +++++---- .../intellij/FormatterProviderTest.java | 2 +- .../intellij/FormatterSelectionTest.java | 8 +- .../PalantirJavaFormatConfigurableTest.java | 8 +- .../PalantirJavaFormatSettingsTest.java | 112 ++++++++++++++---- 9 files changed, 156 insertions(+), 69 deletions(-) diff --git a/docs/decisions/ADR-005-formatting-inside-the-ide.md b/docs/decisions/ADR-005-formatting-inside-the-ide.md index 718b6a043..8a33de6a8 100644 --- a/docs/decisions/ADR-005-formatting-inside-the-ide.md +++ b/docs/decisions/ADR-005-formatting-inside-the-ide.md @@ -63,4 +63,5 @@ IntelliJ IDEA starts its JVM with `--add-opens=java.base/java.lang=ALL-UNNAMED`: - A formatter bug that throws no `Error`, such as one that never returns, now happens inside the IDE. - A formatter from a build is loaded into the IDE's JVM where it used to be run by a JVM of its own. Both happen only in a trusted project. - A formatter from a build that needs a newer Guava than the plugin's can fail to link inside the IDE. It then runs in a separate JVM, on its own jars alone, and so does every other project's formatter until the IDE restarts: one failure switches the IDE process off for the session. -- A project whose `.idea/open-java-format.xml` is shared keeps `useNativeImage` in it beside the new `formatterMode`, for plugins from before the modes. +- `formatterMode` alone says how a project formats, as `in-process`, `jvm` or `native`, and a setting of one mode has that mode at the start of its name: `jvmJdk`, `nativeImagePath`. A mode added later, such as a daemon with a JDK of its own, then has settings no other mode reads. +- `useNativeImage`, which a file from before the modes has, is read once, as the native mode, and not written again. A plugin from before the modes that reads a file written since finds no `useNativeImage`, and formats in a JVM of its own. diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterMode.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterMode.java index d89c9e5d7..201758955 100644 --- a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterMode.java +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterMode.java @@ -14,12 +14,32 @@ package com.palantir.javaformat.intellij; -/** How a project asks for the formatter to run. The names are what .idea/open-java-format.xml holds. */ +import java.util.Arrays; +import java.util.Optional; +import org.jspecify.annotations.Nullable; + +/** How a project asks for the formatter to run. */ enum FormatterMode { /** Loaded into the IDE's own JVM: nothing to start for a file. */ - IN_PROCESS, + IN_PROCESS("in-process"), /** In a JVM started for each call, on the JDK the settings name. */ - JVM, + JVM("jvm"), /** As the native binary, started for each call. */ - NATIVE + NATIVE("native"); + + private final String text; + + FormatterMode(String text) { + this.text = text; + } + + /** What .idea/open-java-format.xml holds for the mode, whatever the constant is called here. */ + String text() { + return text; + } + + /** The mode a file names: none for a file that names none, or one that only a later plugin has. */ + static Optional of(@Nullable String text) { + return Arrays.stream(values()).filter(mode -> mode.text.equals(text)).findFirst(); + } } diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterSelection.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterSelection.java index 0b6c42965..393c40910 100644 --- a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterSelection.java +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterSelection.java @@ -73,7 +73,7 @@ static FormatterSelection of(PalantirJavaFormatSettings settings, Environment en private static SeparateJvm separateJvm( PalantirJavaFormatSettings settings, Environment environment, Fallback... fromAnotherMode) { var fallbacks = new ArrayList<>(List.of(fromAnotherMode)); - var jvm = switch (environment.resolve(settings.getFormatterJdk())) { + var jvm = switch (environment.resolve(settings.getJvmJdk())) { case Usable usable -> usable; case Unusable unusable -> { fallbacks.add(new Fallback.JdkUnusable(unusable.reason())); diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurable.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurable.java index ef1b747db..a7634b9b9 100644 --- a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurable.java +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurable.java @@ -234,7 +234,7 @@ public void apply() throws ConfigurationException { settings.setEnabled( enable.isSelected() ? EnabledState.ENABLED : PalantirJavaFormatSettings.disabledState(project)); settings.setFormatterMode(mode); - settings.setFormatterJdk(selectedJdk()); + settings.setJvmJdk(selectedJdk()); settings.setNativeImagePath(path); if (settings.isEnabled() != wasEnabled) { // The Java import settings of each file are cached, and PalantirJavaFormatCodeStyleSettingsModifier sets @@ -252,7 +252,7 @@ public void reset() { case JVM -> separateJvm.setSelected(true); case NATIVE -> nativeImage.setSelected(true); } - showJdks(settings.getFormatterJdk()); + showJdks(settings.getJvmJdk()); nativeImagePath.setText( settings.getNativeImagePath().map(Path::toString).orElse("")); showPage(); @@ -269,7 +269,7 @@ public boolean isModified() { } return enable.isSelected() != settings.isEnabled() || selectedMode() != settings.getFormatterMode() - || !selectedJdk().equals(settings.getFormatterJdk()) + || !selectedJdk().equals(settings.getJvmJdk()) || !path.equals(settings.getNativeImagePath()); } @@ -371,7 +371,7 @@ private FormatterJdk selectedJdk() { private void showActiveFormatter() { var pending = new PalantirJavaFormatSettings(); pending.setFormatterMode(selectedMode()); - pending.setFormatterJdk(selectedJdk()); + pending.setJvmJdk(selectedJdk()); try { pending.setNativeImagePath(enteredNativeImagePath()); } catch (ConfigurationException e) { diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatSettings.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatSettings.java index add75a9f4..7ddf35581 100644 --- a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatSettings.java +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatSettings.java @@ -53,6 +53,12 @@ public StoredSettings getState() { @Override public void loadState(StoredSettings state) { this.state = state; + // A file from before there were modes says only whether the native binary runs. It says so this once: the + // mode takes its place here, and the file is next written without it. + if (Boolean.TRUE.equals(state.useNativeImage)) { + state.formatterMode = FormatterMode.NATIVE.text(); + } + state.useNativeImage = null; } boolean isEnabled() { @@ -89,34 +95,27 @@ Optional> getImplementationClassPath() { } /** - * How the formatter runs. A file written before there was a choice says only whether the native binary runs: it - * goes on running, and every other project moves from a JVM of its own into the IDE's. + * How the formatter runs: the one setting that says so. A project that names no mode, or one that this plugin + * does not know, formats inside the IDE: until there were modes, such a project started a JVM for every file. */ FormatterMode getFormatterMode() { - for (var mode : FormatterMode.values()) { - if (mode.name().equals(state.formatterMode)) { - return mode; - } - } - return state.useNativeImage ? FormatterMode.NATIVE : FormatterMode.IN_PROCESS; + return FormatterMode.of(state.formatterMode).orElse(FormatterMode.IN_PROCESS); } void setFormatterMode(FormatterMode mode) { - state.formatterMode = mode.name(); - // All that a plugin from before the choice reads, in a file shared with one. - state.useNativeImage = mode == FormatterMode.NATIVE; + state.formatterMode = mode.text(); } - /** The JDK of the formatter's own JVM, for when it runs in one. */ - FormatterJdk getFormatterJdk() { - return FormatterJdk.parse(state.formatterJdk); + /** Of {@link FormatterMode#JVM}: the JDK that the formatter's own JVM runs on. */ + FormatterJdk getJvmJdk() { + return FormatterJdk.parse(state.jvmJdk); } - void setFormatterJdk(FormatterJdk jdk) { - state.formatterJdk = jdk.stored(); + void setJvmJdk(FormatterJdk jdk) { + state.jvmJdk = jdk.stored(); } - /** A native binary of the user's own, run instead of the embedded one. */ + /** Of {@link FormatterMode#NATIVE}: a native binary of the user's own, run instead of the embedded one. */ Optional getNativeImagePath() { return Optional.ofNullable(state.nativeImagePath) .filter(path -> !path.isBlank()) @@ -178,17 +177,26 @@ static class StoredSettings { private EnabledState enabled = EnabledState.UNKNOWN; private Optional> implementationClassPath = Optional.empty(); - public boolean useNativeImage = false; - + /** The text of a {@link FormatterMode}. */ @Nullable public String formatterMode; + // A setting of one mode has that mode at the start of its name, so that a mode added later, such as a daemon + // with a JDK of its own, has settings that cannot be taken for another mode's. + @Nullable - public String formatterJdk; + public String jvmJdk; @Nullable public String nativeImagePath; + /** + * What a file from before there were modes has for the mode. Read, and never written: loadState turns it into + * formatterMode and empties it, and an empty setting is left out of the file. + */ + @Nullable + public Boolean useNativeImage; + public void setImplementationClassPath(@Nullable List value) { implementationClassPath = Optional.ofNullable(value) .map(strings -> strings.stream().map(URI::create).toList()); @@ -228,12 +236,10 @@ public String toString() { + enabled + ", implementationClassPath=" + implementationClassPath - + ", useNativeImage=" - + useNativeImage + ", formatterMode=" + formatterMode - + ", formatterJdk=" - + formatterJdk + + ", jvmJdk=" + + jvmJdk + ", nativeImagePath=" + nativeImagePath + '}'; diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterProviderTest.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterProviderTest.java index a4e5607e5..3dfc83457 100644 --- a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterProviderTest.java +++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterProviderTest.java @@ -84,7 +84,7 @@ void startsTheJvmOnTheJdkTheUserChose() { .extracting("jdkMajorVersion") .isEqualTo(Runtime.version().feature()); - settings.setFormatterJdk(new FormatterJdk.Named("moved-here")); + settings.setJvmJdk(new FormatterJdk.Named("moved-here")); assertThat(provider.get(fixture.getProject(), settings)) .get() diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterSelectionTest.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterSelectionTest.java index 5f65ec37a..b9acee986 100644 --- a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterSelectionTest.java +++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterSelectionTest.java @@ -65,7 +65,7 @@ void runsTheJvmOnTheIdesRuntimeUnlessAJdkIsChosen() { @Test void runsTheJvmOnTheJdkTheUserChose() { settings.setFormatterMode(FormatterMode.JVM); - settings.setFormatterJdk(new FormatterJdk.Named("temurin-25")); + settings.setJvmJdk(new FormatterJdk.Named("temurin-25")); machine.jdk = JDK_25; assertThat(FormatterSelection.of(settings, machine)).isEqualTo(new SeparateJvm(JDK_25.java(), 25, List.of())); @@ -74,7 +74,7 @@ void runsTheJvmOnTheJdkTheUserChose() { @Test void runsTheJvmOnTheIdesRuntimeWhenTheChosenJdkCannotRunTheFormatter() { settings.setFormatterMode(FormatterMode.JVM); - settings.setFormatterJdk(new FormatterJdk.ProjectSdk()); + settings.setJvmJdk(new FormatterJdk.ProjectSdk()); machine.jdk = new Unusable(TOO_OLD); assertThat(FormatterSelection.of(settings, machine)) @@ -84,7 +84,7 @@ void runsTheJvmOnTheIdesRuntimeWhenTheChosenJdkCannotRunTheFormatter() { @Test void usesTheChosenJdkWhenAnotherModeFallsBackToAJvm() { // The JDK is kept whichever mode is on, and it is the JVM to fall back to. - settings.setFormatterJdk(new FormatterJdk.Named("temurin-25")); + settings.setJvmJdk(new FormatterJdk.Named("temurin-25")); machine.jdk = JDK_25; machine.inProcessUnavailable = Optional.of(NO_JAVAC); @@ -94,7 +94,7 @@ void usesTheChosenJdkWhenAnotherModeFallsBackToAJvm() { @Test void saysEveryThingThatIsMissing() { - settings.setFormatterJdk(new FormatterJdk.Named("temurin-17")); + settings.setJvmJdk(new FormatterJdk.Named("temurin-17")); machine.jdk = new Unusable(TOO_OLD); machine.inProcessUnavailable = Optional.of(NO_JAVAC); diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurableTest.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurableTest.java index 86c6f9312..a30a89434 100644 --- a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurableTest.java +++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurableTest.java @@ -208,7 +208,7 @@ void listsTheJdksThatCanRunTheFormatterAndGreysOutTheOthers() throws Throwable { void readsAndWritesTheJdk() throws Throwable { TestJdks.running("this-jdk", untilTheTestEnds); settings.setFormatterMode(FormatterMode.JVM); - settings.setFormatterJdk(new FormatterJdk.Named("this-jdk")); + settings.setJvmJdk(new FormatterJdk.Named("this-jdk")); EdtTestUtil.runInEdtAndWait(() -> { configurable.reset(); @@ -225,14 +225,14 @@ void readsAndWritesTheJdk() throws Throwable { configurable.apply(); }); - assertThat(settings.getFormatterJdk()).isEqualTo(new FormatterJdk.IdeRuntime()); + assertThat(settings.getJvmJdk()).isEqualTo(new FormatterJdk.IdeRuntime()); } @Test void refusesAJdkThatNoLongerRunsTheFormatter() throws Throwable { // Chosen when the IDE had it. The page shows what the settings have, and what runs instead. settings.setFormatterMode(FormatterMode.JVM); - settings.setFormatterJdk(new FormatterJdk.Named("gone")); + settings.setJvmJdk(new FormatterJdk.Named("gone")); var ideRuntime = FormatterJdks.ideRuntime(); EdtTestUtil.runInEdtAndWait(() -> { @@ -316,7 +316,7 @@ void hasNoRowsOfVersions() { void asksNothingOfTheChoicesOnceOpenJavaFormatIsSwitchedOff() throws Throwable { // They are not on the page then, so there is nothing on it to put right. settings.setFormatterMode(FormatterMode.JVM); - settings.setFormatterJdk(new FormatterJdk.Named("gone")); + settings.setJvmJdk(new FormatterJdk.Named("gone")); EdtTestUtil.runInEdtAndWait(() -> { configurable.reset(); diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatSettingsTest.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatSettingsTest.java index fa4a9d25a..7c6db9a2a 100644 --- a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatSettingsTest.java +++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatSettingsTest.java @@ -62,7 +62,7 @@ void keepsTheNativeBinarySettings() throws Exception { } @Test - void keepsTheNativeBinaryOfAFileWrittenBeforeThereWereModes() throws Exception { + void switchesAFileFromBeforeTheModesToTheNativeBinaryItHadOn() throws Exception { var settings = new PalantirJavaFormatSettings(); settings.loadState(deserialize(""" @@ -72,65 +72,126 @@ void keepsTheNativeBinaryOfAFileWrittenBeforeThereWereModes() throws Exception { """)); assertThat(settings.getFormatterMode()).isEqualTo(FormatterMode.NATIVE); + // The mode says it from here on. useNativeImage is empty, and the IDE leaves an empty setting out of the file. + assertThat(settings.getState().formatterMode).isEqualTo("native"); + assertThat(settings.getState().useNativeImage).isNull(); + assertThat(reload(settings).getFormatterMode()).isEqualTo(FormatterMode.NATIVE); } @Test - void movesAProjectThatFormattedInAJvmOfItsOwnIntoTheIde() throws Exception { - // Before there were modes, a project without the native binary started a JVM for every file. + void forgetsUseNativeImageOnceItIsRead() throws Exception { + // It decides the mode when the file is read, and no more after that: another mode chosen since stays chosen. + var settings = new PalantirJavaFormatSettings(); + settings.loadState(deserialize(""" + + + """)); + + settings.setFormatterMode(FormatterMode.JVM); + + assertThat(settings.getFormatterMode()).isEqualTo(FormatterMode.JVM); + assertThat(reload(settings).getFormatterMode()).isEqualTo(FormatterMode.JVM); + } + + @Test + void switchesToTheNativeBinaryWhateverModeStandsBesideUseNativeImage() throws Exception { + // The plugin never writes the two together, so a file with both was written to by a plugin from before the + // modes, which knows only useNativeImage. var settings = new PalantirJavaFormatSettings(); settings.loadState(deserialize(""" + + + """)); + + assertThat(settings.getFormatterMode()).isEqualTo(FormatterMode.NATIVE); + } + + @Test + void movesAProjectThatFormattedInAJvmOfItsOwnIntoTheIde() throws Exception { + // Before there were modes, a project without the native binary started a JVM for every file. + var withoutTheNativeBinary = new PalantirJavaFormatSettings(); + withoutTheNativeBinary.loadState(deserialize(""" """)); + var withTheNativeBinaryOff = new PalantirJavaFormatSettings(); + withTheNativeBinaryOff.loadState(deserialize(""" + + + """)); - assertThat(settings.getFormatterMode()).isEqualTo(FormatterMode.IN_PROCESS); + assertThat(withoutTheNativeBinary.getFormatterMode()).isEqualTo(FormatterMode.IN_PROCESS); + assertThat(withTheNativeBinaryOff.getFormatterMode()).isEqualTo(FormatterMode.IN_PROCESS); + assertThat(withTheNativeBinaryOff.getState().useNativeImage).isNull(); assertThat(new PalantirJavaFormatSettings().getFormatterMode()).isEqualTo(FormatterMode.IN_PROCESS); } + @Test + void namesTheModeInOneSetting() { + // In words of the file's own, which stay when a constant is renamed. + var settings = new PalantirJavaFormatSettings(); + + settings.setFormatterMode(FormatterMode.IN_PROCESS); + assertThat(settings.getState().formatterMode).isEqualTo("in-process"); + settings.setFormatterMode(FormatterMode.JVM); + assertThat(settings.getState().formatterMode).isEqualTo("jvm"); + settings.setFormatterMode(FormatterMode.NATIVE); + assertThat(settings.getState().formatterMode).isEqualTo("native"); + + // And in no other: useNativeImage is only ever read. + assertThat(settings.getState().useNativeImage).isNull(); + } + @Test void keepsTheModeAndTheJdk() throws Exception { var settings = new PalantirJavaFormatSettings(); settings.setFormatterMode(FormatterMode.JVM); - settings.setFormatterJdk(new FormatterJdk.Named("temurin-25")); + settings.setJvmJdk(new FormatterJdk.Named("temurin-25")); var reloaded = reload(settings); assertThat(reloaded.getFormatterMode()).isEqualTo(FormatterMode.JVM); - assertThat(reloaded.getFormatterJdk()).isEqualTo(new FormatterJdk.Named("temurin-25")); + assertThat(reloaded.getJvmJdk()).isEqualTo(new FormatterJdk.Named("temurin-25")); } @Test - void keepsTheProjectSdkAsTheJdk() throws Exception { + void namesTheSettingsOfAModeAfterIt() { + // A mode added later, such as a daemon with a JDK of its own, then has settings no other mode reads. var settings = new PalantirJavaFormatSettings(); - settings.setFormatterJdk(new FormatterJdk.ProjectSdk()); + settings.setJvmJdk(new FormatterJdk.Named("temurin-25")); + settings.setNativeImagePath(Optional.of(Path.of("/opt/open-java-format"))); - assertThat(reload(settings).getFormatterJdk()).isEqualTo(new FormatterJdk.ProjectSdk()); + assertThat(JDOMUtil.write(XmlSerializer.serialize(settings.getState()))) + .contains( + "