diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterVersions.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterVersions.java new file mode 100644 index 000000000..8bee1cfdc --- /dev/null +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/FormatterVersions.java @@ -0,0 +1,73 @@ +/* + * 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.github.benmanes.caffeine.cache.Caffeine; +import com.github.benmanes.caffeine.cache.LoadingCache; +import com.palantir.javaformat.java.FormatterService; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Path; +import java.util.List; +import java.util.Optional; +import java.util.jar.Attributes; +import java.util.jar.JarFile; + +/** + * The versions of the formatters on class paths, such as the one a build writes to {@code .idea/open-java-format.xml}: + * what the manifest of the jar that provides the formatter says. + * + *

Every file formatted asks, and the jars are read once for as long as they stay the same: a jar rebuilt in place + * is noticed, as {@link InProcessFormatters} notices it, without opening the jars for every file. + */ +final class FormatterVersions { + + /** The versions of the IDE's projects. */ + static final FormatterVersions IDE = new FormatterVersions(); + + // The class paths of the projects open at once, as InProcessFormatters keeps their formatters. + private static final int KEPT = 4; + + private final LoadingCache, Optional> versions = Caffeine.newBuilder() + .maximumSize(KEPT) + .build(jars -> read(jars.stream().map(Jar::path).toList())); + + /** + * The Implementation-Version of the first of these jars that provides the formatter, if its manifest has one. + * + * @throws IllegalStateException when none of them provides the formatter + * @throws UncheckedIOException when one before it cannot be read + */ + Optional of(List classPath) { + return versions.get(classPath.stream().map(Jar::of).toList()); + } + + private static Optional read(List classPath) { + for (var path : classPath) { + // Closed at once: on Windows an open jar is one that nobody can replace or delete, a Gradle build included. + try (var jar = new JarFile(path.toFile())) { + // Identify the implementation jar by the service it produces. + if (jar.getEntry("META-INF/services/" + FormatterService.class.getName()) != null) { + return Optional.ofNullable(jar.getManifest()) + .map(manifest -> + manifest.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION)); + } + } catch (IOException e) { + throw new UncheckedIOException("Cannot read " + path, e); + } + } + throw new IllegalStateException("No jar provides the formatter in " + classPath); + } +} 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 index d79f1d3eb..8a5c751b6 100644 --- 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 @@ -121,12 +121,4 @@ private static URL toUrl(Path jar) { 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/Jar.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/Jar.java new file mode 100644 index 000000000..3d9dca0eb --- /dev/null +++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/Jar.java @@ -0,0 +1,28 @@ +/* + * 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; + +/** + * A jar as it was when something was read from it: rebuilt in place, it changes size or time. A key for what is kept + * of a set of jars for as long as they stay the same. + */ +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/PalantirJavaFormatSettings.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatSettings.java index 7ddf35581..62d22be4a 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 @@ -22,17 +22,12 @@ import com.intellij.openapi.components.Storage; import com.intellij.openapi.extensions.PluginDescriptor; import com.intellij.openapi.project.Project; -import com.palantir.javaformat.java.FormatterService; import org.jspecify.annotations.Nullable; -import java.io.IOException; -import java.io.UncheckedIOException; import java.net.URI; import java.nio.file.Path; import java.util.List; import java.util.Optional; -import java.util.jar.JarFile; -import java.util.stream.Stream; import static java.util.Optional.ofNullable; @@ -144,26 +139,11 @@ Optional getImplementationVersion() { .map(PluginDescriptor::getVersion); } + /** The version of the formatter on the implementation class path, if there is one and it states its version. */ Optional computeFormatterVersion() { return getImplementationClassPath() - .map(classpath -> classpath.stream() - .flatMap(uri -> { - try { - JarFile jar = new JarFile(uri.getPath()); - // Identify the implementation jar by the service it produces. - if (jar.getEntry("META-INF/services/" + FormatterService.class.getName()) != null) { - String implementationVersion = jar.getManifest() - .getMainAttributes() - .getValue("Implementation-Version"); - return Stream.of(implementationVersion); - } - return Stream.empty(); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - }) - .findFirst() - .orElseThrow(() -> new RuntimeException("Couldn't find implementation JAR"))); + .flatMap(classpath -> FormatterVersions.IDE.of( + classpath.stream().map(Path::of).toList())); } enum EnabledState { diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterVersionsTest.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterVersionsTest.java new file mode 100644 index 000000000..912593d0e --- /dev/null +++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/FormatterVersionsTest.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 static java.nio.charset.StandardCharsets.UTF_8; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.palantir.javaformat.java.FormatterService; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.FileTime; +import java.util.ArrayList; +import java.util.List; +import java.util.jar.Attributes; +import java.util.jar.JarEntry; +import java.util.jar.JarOutputStream; +import java.util.jar.Manifest; +import org.jspecify.annotations.Nullable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledOnOs; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.io.TempDir; + +final class FormatterVersionsTest { + + @TempDir + private Path dir; + + private final FormatterVersions versions = new FormatterVersions(); + + @Test + void readsTheVersionOfTheJarThatProvidesTheFormatter() throws Exception { + // Every jar of a build's class path has a version of its own. + var classPath = List.of(jar("guava.jar", "33.4.0", false), jar("open-java-format.jar", "21.1.0", true)); + + assertThat(versions.of(classPath)).hasValue("21.1.0"); + } + + @Test + void readsTheJarsOnceForAsLongAsTheyStayTheSame() throws Exception { + var formatter = jar("open-java-format.jar", "21.1.0", true); + assertThat(versions.of(List.of(formatter))).hasValue("21.1.0"); + + // No jar at all now, of the same size and time: not opened again, it still has the version read before. + var lastModified = Files.getLastModifiedTime(formatter); + Files.write(formatter, new byte[(int) Files.size(formatter)]); + Files.setLastModifiedTime(formatter, lastModified); + + assertThat(versions.of(List.of(formatter))).hasValue("21.1.0"); + + // A jar rebuilt in place. + jar("open-java-format.jar", "21.2.0", true); + Files.setLastModifiedTime( + formatter, FileTime.from(lastModified.toInstant().plusSeconds(60))); + + assertThat(versions.of(List.of(formatter))).hasValue("21.2.0"); + } + + @Test + @EnabledOnOs(value = OS.LINUX, disabledReason = "Only Linux names the files a process holds open, in /proc/self/fd") + void leavesNoJarOpen() throws Exception { + // On Windows a jar the IDE holds open is one that nobody can replace or delete, a Gradle build included. + var dependency = jar("guava.jar", "33.4.0", false); + var formatter = jar("open-java-format.jar", "21.1.0", true); + + versions.of(List.of(dependency, formatter)); + + assertThat(openFiles()).doesNotContain(dependency.toRealPath(), formatter.toRealPath()); + } + + @Test + void takesAFormatterWithoutAVersionForNone() throws Exception { + // As a version it cannot parse: the plugin formats with the formatter bundled with it. + assertThat(versions.of(List.of(jar("open-java-format.jar", null, true)))) + .isEmpty(); + } + + @Test + void saysSoWhenNoJarProvidesTheFormatter() throws Exception { + var classPath = List.of(jar("guava.jar", "33.4.0", false)); + + assertThatThrownBy(() -> versions.of(classPath)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("No jar provides the formatter in %s", classPath); + } + + /** A jar in the test's directory, written over the one there, with the formatter in it if it provides it. */ + private Path jar(String name, @Nullable String version, boolean providesTheFormatter) throws IOException { + var manifest = new Manifest(); + manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); + if (version != null) { + manifest.getMainAttributes().put(Attributes.Name.IMPLEMENTATION_VERSION, version); + } + var path = dir.resolve(name); + try (var jar = new JarOutputStream(Files.newOutputStream(path), manifest)) { + if (providesTheFormatter) { + jar.putNextEntry(new JarEntry("META-INF/services/" + FormatterService.class.getName())); + jar.write("com.palantir.javaformat.java.FormatterServiceImpl\n".getBytes(UTF_8)); + jar.closeEntry(); + } + } + return path; + } + + private static List openFiles() throws IOException { + var open = new ArrayList(); + try (var descriptors = Files.list(Path.of("/proc/self/fd"))) { + for (var descriptor : descriptors.toList()) { + try { + open.add(Files.readSymbolicLink(descriptor)); + } catch (IOException e) { + // Closed since it was listed, as the listing's own is. + } + } + } + return open; + } +}