Skip to content

Commit 1a648bb

Browse files
dansanduleaciamdanfox
authored andcommitted
Improvement: IntelliJ plugin with configurable implementation (#18)
1 parent f201316 commit 1a648bb

File tree

54 files changed

+1070
-681
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

54 files changed

+1070
-681
lines changed

CONTRIBUTING.md

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Contributing
2+
3+
The team welcomes contributions! To make changes:
4+
5+
- Fork the repo and make a branch
6+
- Write your code (ideally with tests) and make sure the CircleCI build passes
7+
- Open a PR (optionally linking to a github issue)
8+
9+
## Local development
10+
11+
We recommend using [Intellij IDEA Community Edition](https://www.jetbrains.com/idea/) for Java projects. You'll need Java 8 on your machine.
12+
13+
1. Fork the repository
14+
1. Generate the IDE configuration: `./gradlew idea`
15+
1. Import projects into Intellij: `open *.ipr`
16+
17+
Tips:
18+
19+
- run `./gradlew checkstyleMain checkstyleTest` locally to make sure your code conforms to the code-style.
20+
21+
## Working on `:idea-plugin`
22+
23+
Tip: run `./gradlew runIde` to spin up an instance of IntelliJ with the plugin applied.

build.gradle

+1
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ allprojects {
3737
mavenLocal()
3838
jcenter()
3939
maven { url 'https://dl.bintray.com/palantir/releases/' }
40+
gradlePluginPortal()
4041
}
4142
}
4243

changelog/@unreleased/pr-18.v2.yml

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
type: improvement
2+
improvement:
3+
description: IntelliJ plugin can be automatically configured with a custom version
4+
of the formatter, by applying `com.palantir.java-format` in gradle and setting
5+
the `palantirJavaFormat.implementationVersion`.
6+
links:
7+
- https://github.com/palantir/palantir-java-format/pull/18
+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
apply plugin: 'java-gradle-plugin'
2+
apply plugin: 'groovy'
3+
apply from: rootProject.file('gradle/publish-jar.gradle')
4+
5+
dependencies {
6+
implementation gradleApi()
7+
implementation 'com.google.guava:guava'
8+
implementation 'gradle.plugin.org.jetbrains.gradle.plugin.idea-ext:gradle-idea-ext'
9+
10+
testImplementation 'com.netflix.nebula:nebula-test'
11+
}
12+
13+
gradlePlugin {
14+
automatedPublishing = false
15+
plugins {
16+
palantirJavaFormat {
17+
id = 'com.palantir.java-format'
18+
implementationClass = 'com.palantir.javaformat.gradle.JavaFormatPlugin'
19+
description = 'Plugin to configure the PalantirJavaFormat IDEA plugin based on an optional implementation version of the formatter.'
20+
}
21+
}
22+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.palantir.javaformat.gradle
2+
3+
class ConfigureJavaFormatterXml {
4+
static void configure(Node rootNode, List<URI> uris) {
5+
def settings = matchOrCreateChild(rootNode, 'component', [name: 'PalantirJavaFormatSettings'])
6+
def classPath = matchOrCreateChild(settings, 'option', [name: 'implementationClassPath'])
7+
def listItems = matchOrCreateChild(classPath, 'list')
8+
listItems.children().clear()
9+
uris.forEach { URI uri ->
10+
listItems.appendNode('option', [value: uri])
11+
}
12+
}
13+
14+
private static Node matchOrCreateChild(Node base, String name, Map attributes = [:], Map defaults = [:]) {
15+
def child = base[name].find { it.attributes().entrySet().containsAll(attributes.entrySet()) }
16+
if (child) {
17+
return child
18+
}
19+
20+
return base.appendNode(name, attributes + defaults)
21+
}
22+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package com.palantir.javaformat.gradle;
2+
3+
import com.google.common.collect.ImmutableMap;
4+
import com.google.common.io.Files;
5+
import groovy.util.Node;
6+
import groovy.util.XmlNodePrinter;
7+
import groovy.util.XmlParser;
8+
import java.io.BufferedWriter;
9+
import java.io.File;
10+
import java.io.IOException;
11+
import java.io.PrintWriter;
12+
import java.net.URI;
13+
import java.nio.charset.Charset;
14+
import java.util.List;
15+
import java.util.stream.Collectors;
16+
import javax.xml.parsers.ParserConfigurationException;
17+
import org.gradle.api.DefaultTask;
18+
import org.gradle.api.artifacts.Configuration;
19+
import org.gradle.api.provider.Property;
20+
import org.gradle.api.tasks.Classpath;
21+
import org.gradle.api.tasks.OutputFile;
22+
import org.gradle.api.tasks.PathSensitive;
23+
import org.gradle.api.tasks.PathSensitivity;
24+
import org.gradle.api.tasks.TaskAction;
25+
import org.xml.sax.SAXException;
26+
27+
public class ConfigurePalantirJavaFormatXml extends DefaultTask {
28+
private final Property<Configuration> implConfiguration = getProject().getObjects().property(Configuration.class);
29+
30+
@Classpath
31+
Property<Configuration> getImplConfiguration() {
32+
return implConfiguration;
33+
}
34+
35+
@PathSensitive(PathSensitivity.RELATIVE)
36+
@OutputFile
37+
File getOutputFile() {
38+
return getProject().file(".idea/palantir-java-format.xml");
39+
}
40+
41+
@TaskAction
42+
public void run() {
43+
File configurationFile = getOutputFile();
44+
Node rootNode;
45+
if (configurationFile.isFile()) {
46+
try {
47+
rootNode = new XmlParser().parse(configurationFile);
48+
} catch (IOException | SAXException | ParserConfigurationException e) {
49+
throw new RuntimeException("Couldn't parse existing configuration file: " + configurationFile, e);
50+
}
51+
} else {
52+
rootNode = new Node(null, "project", ImmutableMap.of("version", "4"));
53+
}
54+
55+
List<URI> uris = implConfiguration.get().getFiles().stream().map(File::toURI).collect(Collectors.toList());
56+
ConfigureJavaFormatterXml.configure(rootNode, uris);
57+
58+
try (BufferedWriter writer = Files.newWriter(configurationFile, Charset.defaultCharset());
59+
PrintWriter printWriter = new PrintWriter(writer)) {
60+
XmlNodePrinter nodePrinter = new XmlNodePrinter(printWriter);
61+
nodePrinter.setPreserveWhitespace(true);
62+
nodePrinter.print(rootNode);
63+
} catch (IOException e) {
64+
throw new RuntimeException("Failed to write back to configuration file: " + configurationFile, e);
65+
}
66+
}
67+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
/*
2+
* (c) Copyright 2019 Palantir Technologies Inc. All rights reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.palantir.javaformat.gradle;
18+
19+
import com.google.common.base.Preconditions;
20+
import com.google.common.collect.ImmutableMap;
21+
import java.io.File;
22+
import java.net.URI;
23+
import java.util.List;
24+
import java.util.stream.Collectors;
25+
import org.gradle.api.Plugin;
26+
import org.gradle.api.Project;
27+
import org.gradle.api.artifacts.Configuration;
28+
import org.gradle.api.plugins.ExtensionAware;
29+
import org.gradle.plugins.ide.idea.model.IdeaModel;
30+
import org.jetbrains.gradle.ext.TaskTriggersConfig;
31+
32+
public class JavaFormatPlugin implements Plugin<Project> {
33+
34+
private static final String EXTENSION_NAME = "palantirJavaFormat";
35+
36+
@Override
37+
public void apply(Project project) {
38+
Preconditions.checkState(
39+
project == project.getRootProject(), "May only apply com.palantir.java-format to the root project");
40+
41+
JavaFormatExtension extension =
42+
project.getExtensions().create(EXTENSION_NAME, JavaFormatExtension.class, project);
43+
44+
Configuration implConfiguration = project.getConfigurations().create("palantirJavaFormat", conf -> {
45+
conf.setDescription("Internal configuration for resolving the palantirJavaFormat implementation");
46+
conf.setVisible(false);
47+
conf.setCanBeConsumed(false);
48+
// Using addLater instead of afterEvaluate, in order to delay reading the extension until after the user
49+
// has configured it.
50+
conf.defaultDependencies(deps -> deps.addLater(project.provider(() -> {
51+
String version = extension.getImplementationVersion().get();
52+
53+
return project.getDependencies().create(ImmutableMap.of(
54+
"group", "com.palantir.javaformat",
55+
"name", "palantir-java-format",
56+
"version", version));
57+
})));
58+
});
59+
60+
project.getPluginManager().withPlugin("idea", ideaPlugin -> {
61+
configureLegacyIdea(project, implConfiguration);
62+
configureIntelliJImport(project, implConfiguration);
63+
});
64+
}
65+
66+
private static void configureLegacyIdea(Project project, Configuration implConfiguration) {
67+
IdeaModel ideaModel = project.getExtensions().getByType(IdeaModel.class);
68+
ideaModel.getProject().getIpr().withXml(xmlProvider -> {
69+
// this block is lazy
70+
List<URI> uris = implConfiguration.getFiles().stream().map(File::toURI).collect(Collectors.toList());
71+
ConfigureJavaFormatterXml.configure(xmlProvider.asNode(), uris);
72+
});
73+
}
74+
75+
private static void configureIntelliJImport(Project project, Configuration implConfiguration) {
76+
project.getPluginManager().apply("org.jetbrains.gradle.plugin.idea-ext");
77+
78+
ConfigurePalantirJavaFormatXml fixPalantirJavaFormatXmlTask = project.getTasks()
79+
.create("fixPalantirJavaFormatXml", ConfigurePalantirJavaFormatXml.class, task -> {
80+
task.getImplConfiguration().set(implConfiguration);
81+
});
82+
83+
ExtensionAware ideaProject = (ExtensionAware) project.getExtensions().getByType(IdeaModel.class).getProject();
84+
ExtensionAware settings = (ExtensionAware) ideaProject.getExtensions().getByName("settings");
85+
TaskTriggersConfig taskTriggers = settings.getExtensions().getByType(TaskTriggersConfig.class);
86+
taskTriggers.afterSync(fixPalantirJavaFormatXmlTask);
87+
}
88+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.palantir.javaformat.gradle;
2+
3+
import org.gradle.api.Project;
4+
import org.gradle.api.provider.Property;
5+
6+
public class JavaFormatExtension {
7+
private final Property<String> implementationVersion;
8+
private static final String IMPLEMENTATION_VERSION =
9+
JavaFormatExtension.class.getPackage().getImplementationVersion();
10+
11+
public JavaFormatExtension(Project project) {
12+
implementationVersion = project.getObjects().property(String.class);
13+
implementationVersion.set(IMPLEMENTATION_VERSION);
14+
}
15+
16+
public final Property<String> getImplementationVersion() {
17+
return implementationVersion;
18+
}
19+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
package com.palantir.javaformat.gradle
2+
3+
4+
import spock.lang.Specification
5+
6+
class ConfigureJavaFormatterXmlTest extends Specification {
7+
8+
private static final String EXISTING_CLASS_PATH = """
9+
<root>
10+
<component name="PalantirJavaFormatSettings">
11+
<option name="implementationClassPath">
12+
<list>
13+
<option value="foo" />
14+
<option value="aldfjh://barz" />
15+
</list>
16+
</option>
17+
</component>
18+
</root>
19+
""".stripIndent()
20+
21+
private static final String MISSING_CLASS_PATH = """
22+
<root>
23+
<component name="PalantirJavaFormatSettings">
24+
<option name="style" value="PALANTIR"/>
25+
</component>
26+
</root>
27+
""".stripIndent()
28+
29+
private static final String MISSING_ENTIRE_BLOCK = """
30+
<root>
31+
</root>
32+
""".stripIndent()
33+
34+
public static final String EXPECTED = """\
35+
<root>
36+
<component name="PalantirJavaFormatSettings">
37+
<option name="implementationClassPath">
38+
<list>
39+
<option value="foo"/>
40+
<option value="bar"/>
41+
</list>
42+
</option>
43+
</component>
44+
</root>
45+
""".stripIndent()
46+
47+
void testConfigure_missingEntireBlock_added() {
48+
def node = new XmlParser().parseText(MISSING_ENTIRE_BLOCK)
49+
50+
when:
51+
ConfigureJavaFormatterXml.configure(node, ['foo', 'bar'].collect { URI.create(it) })
52+
53+
then:
54+
xmlToString(node) == EXPECTED
55+
}
56+
57+
void testConfigure_missingClassPath_added() {
58+
def node = new XmlParser().parseText(MISSING_CLASS_PATH)
59+
60+
when:
61+
ConfigureJavaFormatterXml.configure(node, ['foo', 'bar'].collect { URI.create(it) })
62+
63+
then:
64+
xmlToString(node) == """\
65+
<root>
66+
<component name="PalantirJavaFormatSettings">
67+
<option name="style" value="PALANTIR"/>
68+
<option name="implementationClassPath">
69+
<list>
70+
<option value="foo"/>
71+
<option value="bar"/>
72+
</list>
73+
</option>
74+
</component>
75+
</root>
76+
""".stripIndent()
77+
}
78+
79+
void testConfigure_existingClassPath_modified() {
80+
def node = new XmlParser().parseText(EXISTING_CLASS_PATH)
81+
82+
when:
83+
ConfigureJavaFormatterXml.configure(node, ['foo', 'bar'].collect { URI.create(it) })
84+
85+
then:
86+
xmlToString(node) == EXPECTED
87+
}
88+
89+
static String xmlToString(Node node) {
90+
StringWriter sw = new StringWriter();
91+
XmlNodePrinter nodePrinter = new XmlNodePrinter(new PrintWriter(sw));
92+
nodePrinter.setPreserveWhitespace(true);
93+
nodePrinter.print(node);
94+
return sw.toString()
95+
}
96+
}

0 commit comments

Comments
 (0)