Skip to content

Commit b366c3e

Browse files
authored
Merge pull request #264 from openjavaformat/abashev/intellij-plugin-every-format-opens-the-builds-fo
Read the version of a build's formatter once in IntelliJ IDEA, and close its jars
2 parents e07d9c3 + 5b820f1 commit b366c3e

5 files changed

Lines changed: 236 additions & 31 deletions

File tree

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/*
2+
* Licensed under the Apache License, Version 2.0 (the "License");
3+
* you may not use this file except in compliance with the License.
4+
* You may obtain a copy of the License at
5+
*
6+
* http://www.apache.org/licenses/LICENSE-2.0
7+
*
8+
* Unless required by applicable law or agreed to in writing, software
9+
* distributed under the License is distributed on an "AS IS" BASIS,
10+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
* See the License for the specific language governing permissions and
12+
* limitations under the License.
13+
*/
14+
15+
package com.palantir.javaformat.intellij;
16+
17+
import com.github.benmanes.caffeine.cache.Caffeine;
18+
import com.github.benmanes.caffeine.cache.LoadingCache;
19+
import com.palantir.javaformat.java.FormatterService;
20+
import java.io.IOException;
21+
import java.io.UncheckedIOException;
22+
import java.nio.file.Path;
23+
import java.util.List;
24+
import java.util.Optional;
25+
import java.util.jar.Attributes;
26+
import java.util.jar.JarFile;
27+
28+
/**
29+
* The versions of the formatters on class paths, such as the one a build writes to {@code .idea/open-java-format.xml}:
30+
* what the manifest of the jar that provides the formatter says.
31+
*
32+
* <p>Every file formatted asks, and the jars are read once for as long as they stay the same: a jar rebuilt in place
33+
* is noticed, as {@link InProcessFormatters} notices it, without opening the jars for every file.
34+
*/
35+
final class FormatterVersions {
36+
37+
/** The versions of the IDE's projects. */
38+
static final FormatterVersions IDE = new FormatterVersions();
39+
40+
// The class paths of the projects open at once, as InProcessFormatters keeps their formatters.
41+
private static final int KEPT = 4;
42+
43+
private final LoadingCache<List<Jar>, Optional<String>> versions = Caffeine.newBuilder()
44+
.maximumSize(KEPT)
45+
.build(jars -> read(jars.stream().map(Jar::path).toList()));
46+
47+
/**
48+
* The Implementation-Version of the first of these jars that provides the formatter, if its manifest has one.
49+
*
50+
* @throws IllegalStateException when none of them provides the formatter
51+
* @throws UncheckedIOException when one before it cannot be read
52+
*/
53+
Optional<String> of(List<Path> classPath) {
54+
return versions.get(classPath.stream().map(Jar::of).toList());
55+
}
56+
57+
private static Optional<String> read(List<Path> classPath) {
58+
for (var path : classPath) {
59+
// Closed at once: on Windows an open jar is one that nobody can replace or delete, a Gradle build included.
60+
try (var jar = new JarFile(path.toFile())) {
61+
// Identify the implementation jar by the service it produces.
62+
if (jar.getEntry("META-INF/services/" + FormatterService.class.getName()) != null) {
63+
return Optional.ofNullable(jar.getManifest())
64+
.map(manifest ->
65+
manifest.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION));
66+
}
67+
} catch (IOException e) {
68+
throw new UncheckedIOException("Cannot read " + path, e);
69+
}
70+
}
71+
throw new IllegalStateException("No jar provides the formatter in " + classPath);
72+
}
73+
}

‎open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/InProcessFormatters.java‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -121,12 +121,4 @@ private static URL toUrl(Path jar) {
121121
throw new UncheckedIOException("Cannot turn " + jar + " into a URL", e);
122122
}
123123
}
124-
125-
/** A jar as it was when the formatter was loaded from it: rebuilt in place, it changes size or time. */
126-
private record Jar(Path path, long length, long lastModified) {
127-
static Jar of(Path path) {
128-
var file = path.toFile();
129-
return new Jar(path, file.length(), file.lastModified());
130-
}
131-
}
132124
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/*
2+
* Licensed under the Apache License, Version 2.0 (the "License");
3+
* you may not use this file except in compliance with the License.
4+
* You may obtain a copy of the License at
5+
*
6+
* http://www.apache.org/licenses/LICENSE-2.0
7+
*
8+
* Unless required by applicable law or agreed to in writing, software
9+
* distributed under the License is distributed on an "AS IS" BASIS,
10+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
* See the License for the specific language governing permissions and
12+
* limitations under the License.
13+
*/
14+
15+
package com.palantir.javaformat.intellij;
16+
17+
import java.nio.file.Path;
18+
19+
/**
20+
* 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
21+
* of a set of jars for as long as they stay the same.
22+
*/
23+
record Jar(Path path, long length, long lastModified) {
24+
static Jar of(Path path) {
25+
var file = path.toFile();
26+
return new Jar(path, file.length(), file.lastModified());
27+
}
28+
}

‎open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatSettings.java‎

Lines changed: 3 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -22,17 +22,12 @@
2222
import com.intellij.openapi.components.Storage;
2323
import com.intellij.openapi.extensions.PluginDescriptor;
2424
import com.intellij.openapi.project.Project;
25-
import com.palantir.javaformat.java.FormatterService;
2625
import org.jspecify.annotations.Nullable;
2726

28-
import java.io.IOException;
29-
import java.io.UncheckedIOException;
3027
import java.net.URI;
3128
import java.nio.file.Path;
3229
import java.util.List;
3330
import java.util.Optional;
34-
import java.util.jar.JarFile;
35-
import java.util.stream.Stream;
3631

3732
import static java.util.Optional.ofNullable;
3833

@@ -144,26 +139,11 @@ Optional<String> getImplementationVersion() {
144139
.map(PluginDescriptor::getVersion);
145140
}
146141

142+
/** The version of the formatter on the implementation class path, if there is one and it states its version. */
147143
Optional<String> computeFormatterVersion() {
148144
return getImplementationClassPath()
149-
.map(classpath -> classpath.stream()
150-
.flatMap(uri -> {
151-
try {
152-
JarFile jar = new JarFile(uri.getPath());
153-
// Identify the implementation jar by the service it produces.
154-
if (jar.getEntry("META-INF/services/" + FormatterService.class.getName()) != null) {
155-
String implementationVersion = jar.getManifest()
156-
.getMainAttributes()
157-
.getValue("Implementation-Version");
158-
return Stream.of(implementationVersion);
159-
}
160-
return Stream.empty();
161-
} catch (IOException e) {
162-
throw new UncheckedIOException(e);
163-
}
164-
})
165-
.findFirst()
166-
.orElseThrow(() -> new RuntimeException("Couldn't find implementation JAR")));
145+
.flatMap(classpath -> FormatterVersions.IDE.of(
146+
classpath.stream().map(Path::of).toList()));
167147
}
168148

169149
enum EnabledState {
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
/*
2+
* Licensed under the Apache License, Version 2.0 (the "License");
3+
* you may not use this file except in compliance with the License.
4+
* You may obtain a copy of the License at
5+
*
6+
* http://www.apache.org/licenses/LICENSE-2.0
7+
*
8+
* Unless required by applicable law or agreed to in writing, software
9+
* distributed under the License is distributed on an "AS IS" BASIS,
10+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
* See the License for the specific language governing permissions and
12+
* limitations under the License.
13+
*/
14+
15+
package com.palantir.javaformat.intellij;
16+
17+
import static java.nio.charset.StandardCharsets.UTF_8;
18+
import static org.assertj.core.api.Assertions.assertThat;
19+
import static org.assertj.core.api.Assertions.assertThatThrownBy;
20+
21+
import com.palantir.javaformat.java.FormatterService;
22+
import java.io.IOException;
23+
import java.nio.file.Files;
24+
import java.nio.file.Path;
25+
import java.nio.file.attribute.FileTime;
26+
import java.util.ArrayList;
27+
import java.util.List;
28+
import java.util.jar.Attributes;
29+
import java.util.jar.JarEntry;
30+
import java.util.jar.JarOutputStream;
31+
import java.util.jar.Manifest;
32+
import org.jspecify.annotations.Nullable;
33+
import org.junit.jupiter.api.Test;
34+
import org.junit.jupiter.api.condition.EnabledOnOs;
35+
import org.junit.jupiter.api.condition.OS;
36+
import org.junit.jupiter.api.io.TempDir;
37+
38+
final class FormatterVersionsTest {
39+
40+
@TempDir
41+
private Path dir;
42+
43+
private final FormatterVersions versions = new FormatterVersions();
44+
45+
@Test
46+
void readsTheVersionOfTheJarThatProvidesTheFormatter() throws Exception {
47+
// Every jar of a build's class path has a version of its own.
48+
var classPath = List.of(jar("guava.jar", "33.4.0", false), jar("open-java-format.jar", "21.1.0", true));
49+
50+
assertThat(versions.of(classPath)).hasValue("21.1.0");
51+
}
52+
53+
@Test
54+
void readsTheJarsOnceForAsLongAsTheyStayTheSame() throws Exception {
55+
var formatter = jar("open-java-format.jar", "21.1.0", true);
56+
assertThat(versions.of(List.of(formatter))).hasValue("21.1.0");
57+
58+
// No jar at all now, of the same size and time: not opened again, it still has the version read before.
59+
var lastModified = Files.getLastModifiedTime(formatter);
60+
Files.write(formatter, new byte[(int) Files.size(formatter)]);
61+
Files.setLastModifiedTime(formatter, lastModified);
62+
63+
assertThat(versions.of(List.of(formatter))).hasValue("21.1.0");
64+
65+
// A jar rebuilt in place.
66+
jar("open-java-format.jar", "21.2.0", true);
67+
Files.setLastModifiedTime(
68+
formatter, FileTime.from(lastModified.toInstant().plusSeconds(60)));
69+
70+
assertThat(versions.of(List.of(formatter))).hasValue("21.2.0");
71+
}
72+
73+
@Test
74+
@EnabledOnOs(value = OS.LINUX, disabledReason = "Only Linux names the files a process holds open, in /proc/self/fd")
75+
void leavesNoJarOpen() throws Exception {
76+
// On Windows a jar the IDE holds open is one that nobody can replace or delete, a Gradle build included.
77+
var dependency = jar("guava.jar", "33.4.0", false);
78+
var formatter = jar("open-java-format.jar", "21.1.0", true);
79+
80+
versions.of(List.of(dependency, formatter));
81+
82+
assertThat(openFiles()).doesNotContain(dependency.toRealPath(), formatter.toRealPath());
83+
}
84+
85+
@Test
86+
void takesAFormatterWithoutAVersionForNone() throws Exception {
87+
// As a version it cannot parse: the plugin formats with the formatter bundled with it.
88+
assertThat(versions.of(List.of(jar("open-java-format.jar", null, true))))
89+
.isEmpty();
90+
}
91+
92+
@Test
93+
void saysSoWhenNoJarProvidesTheFormatter() throws Exception {
94+
var classPath = List.of(jar("guava.jar", "33.4.0", false));
95+
96+
assertThatThrownBy(() -> versions.of(classPath))
97+
.isInstanceOf(IllegalStateException.class)
98+
.hasMessage("No jar provides the formatter in %s", classPath);
99+
}
100+
101+
/** A jar in the test's directory, written over the one there, with the formatter in it if it provides it. */
102+
private Path jar(String name, @Nullable String version, boolean providesTheFormatter) throws IOException {
103+
var manifest = new Manifest();
104+
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
105+
if (version != null) {
106+
manifest.getMainAttributes().put(Attributes.Name.IMPLEMENTATION_VERSION, version);
107+
}
108+
var path = dir.resolve(name);
109+
try (var jar = new JarOutputStream(Files.newOutputStream(path), manifest)) {
110+
if (providesTheFormatter) {
111+
jar.putNextEntry(new JarEntry("META-INF/services/" + FormatterService.class.getName()));
112+
jar.write("com.palantir.javaformat.java.FormatterServiceImpl\n".getBytes(UTF_8));
113+
jar.closeEntry();
114+
}
115+
}
116+
return path;
117+
}
118+
119+
private static List<Path> openFiles() throws IOException {
120+
var open = new ArrayList<Path>();
121+
try (var descriptors = Files.list(Path.of("/proc/self/fd"))) {
122+
for (var descriptor : descriptors.toList()) {
123+
try {
124+
open.add(Files.readSymbolicLink(descriptor));
125+
} catch (IOException e) {
126+
// Closed since it was listed, as the listing's own is.
127+
}
128+
}
129+
}
130+
return open;
131+
}
132+
}

0 commit comments

Comments
 (0)