Skip to content

Commit 9d62ee3

Browse files
committed
Improved config handling in maven plugin
Exposed `encoding` and `lineEndings` in the plugin xml configuration. Renamed `eclipseFormatFile` to `eclipseConfigFile` and moved it inside the `<java>` tag. Maven plugins can handle nested configs using Plexus dependency injection and POJO objects. Thus introduced a dedicated class for all java related configuration called `Java`. Plugin xml configuration can now look like: ``` <plugin> <groupId>com.diffplug.spotless</groupId> <artifactId>spotless-maven-plugin</artifactId> <version>${spotless.version}</version> <configuration> <encoding>UTF-8</encoding> <lineEndings>UNIX</lineEndings> <java> <eclipseConfigFile>${basedir}/eclipse-fmt.xml</eclipseConfigFile> </java> </configuration> </plugin> ``` Extracted an abstract `AbstractSpotlessMojo` to hold all injected dependencies. It can be potentially used in future to implement the `check` goal. Changed name of `SpotlessMojo` from "spotless" to "apply" so that it can be invoked with `mvn spotless:apply`.
1 parent 9956473 commit 9d62ee3

File tree

3 files changed

+156
-51
lines changed

3 files changed

+156
-51
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
/*
2+
* Copyright 2016 DiffPlug
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+
package com.diffplug.gradle.spotless;
17+
18+
import static java.util.stream.Collectors.toList;
19+
20+
import java.io.File;
21+
import java.nio.charset.Charset;
22+
import java.nio.file.Files;
23+
import java.nio.file.Path;
24+
import java.nio.file.Paths;
25+
import java.util.List;
26+
import java.util.stream.Stream;
27+
28+
import org.apache.maven.plugin.AbstractMojo;
29+
import org.apache.maven.plugins.annotations.Component;
30+
import org.apache.maven.plugins.annotations.Parameter;
31+
import org.apache.maven.project.MavenProject;
32+
import org.eclipse.aether.RepositorySystem;
33+
import org.eclipse.aether.RepositorySystemSession;
34+
import org.eclipse.aether.repository.RemoteRepository;
35+
36+
import com.diffplug.spotless.LineEnding;
37+
38+
public abstract class AbstractSpotlessMojo extends AbstractMojo {
39+
40+
private static final String DEFAULT_ENCODING = "UTF-8";
41+
private static final String DEFAULT_LINE_ENDINGS = "GIT_ATTRIBUTES";
42+
43+
@Component
44+
private RepositorySystem repositorySystem;
45+
46+
@Parameter(defaultValue = "${repositorySystemSession}", required = true, readonly = true)
47+
private RepositorySystemSession repositorySystemSession;
48+
49+
@Parameter(defaultValue = "${project.remotePluginRepositories}", required = true, readonly = true)
50+
private List<RemoteRepository> repositories;
51+
52+
@Parameter(defaultValue = "${project}", required = true, readonly = true)
53+
private MavenProject project;
54+
55+
@Parameter(defaultValue = DEFAULT_ENCODING)
56+
private String encoding;
57+
58+
@Parameter(defaultValue = DEFAULT_LINE_ENDINGS)
59+
private LineEnding lineEndings;
60+
61+
@Parameter(required = true)
62+
private Java java;
63+
64+
protected ArtifactResolver createArtifactResolver() {
65+
return new ArtifactResolver(repositorySystem, repositorySystemSession, repositories);
66+
}
67+
68+
protected List<Path> getAllSourceRoots() {
69+
Stream<String> compileSourceRoots = project.getCompileSourceRoots().stream();
70+
Stream<String> testCompileSourceRoots = project.getTestCompileSourceRoots().stream();
71+
return Stream.concat(compileSourceRoots, testCompileSourceRoots)
72+
.map(Paths::get)
73+
.filter(Files::isDirectory)
74+
.collect(toList());
75+
}
76+
77+
protected Charset getEncoding() {
78+
return Charset.forName(encoding);
79+
}
80+
81+
protected LineEnding.Policy getLineEndingsPolicy(List<File> filesToFormat) {
82+
return lineEndings.createPolicy(getRootDir(), () -> filesToFormat);
83+
}
84+
85+
protected File getRootDir() {
86+
return project.getBasedir();
87+
}
88+
89+
protected Java getJavaConfig() {
90+
return java;
91+
}
92+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/*
2+
* Copyright 2016 DiffPlug
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+
package com.diffplug.gradle.spotless;
17+
18+
import java.io.File;
19+
20+
public class Java {
21+
private File eclipseConfigFile;
22+
23+
public File getEclipseConfigFile() {
24+
return eclipseConfigFile;
25+
}
26+
27+
public void setEclipseConfigFile(File eclipseConfigFile) {
28+
this.eclipseConfigFile = eclipseConfigFile;
29+
}
30+
}

plugin-maven/src/main/java/com/diffplug/gradle/spotless/SpotlessMojo.java

+34-51
Original file line numberDiff line numberDiff line change
@@ -16,95 +16,78 @@
1616
package com.diffplug.gradle.spotless;
1717

1818
import static java.util.Collections.singleton;
19+
import static java.util.Collections.singletonList;
1920

2021
import java.io.File;
2122
import java.io.IOException;
22-
import java.nio.charset.StandardCharsets;
2323
import java.nio.file.Files;
2424
import java.nio.file.Path;
25-
import java.nio.file.Paths;
2625
import java.util.ArrayList;
27-
import java.util.Collections;
2826
import java.util.List;
2927
import java.util.Set;
3028
import java.util.stream.Stream;
3129

32-
import org.apache.maven.plugin.AbstractMojo;
3330
import org.apache.maven.plugin.MojoExecutionException;
3431
import org.apache.maven.plugin.MojoFailureException;
35-
import org.apache.maven.plugins.annotations.Component;
3632
import org.apache.maven.plugins.annotations.Mojo;
37-
import org.apache.maven.plugins.annotations.Parameter;
38-
import org.apache.maven.project.MavenProject;
39-
import org.eclipse.aether.RepositorySystem;
40-
import org.eclipse.aether.RepositorySystemSession;
41-
import org.eclipse.aether.repository.RemoteRepository;
4233

34+
import com.diffplug.spotless.FormatExceptionPolicyStrict;
4335
import com.diffplug.spotless.Formatter;
4436
import com.diffplug.spotless.FormatterStep;
45-
import com.diffplug.spotless.LineEnding;
4637
import com.diffplug.spotless.Provisioner;
47-
import com.diffplug.spotless.ThrowingEx;
4838
import com.diffplug.spotless.extra.java.EclipseFormatterStep;
4939

50-
@Mojo(name = "spotless")
51-
public class SpotlessMojo extends AbstractMojo {
52-
53-
@Component
54-
private RepositorySystem repositorySystem;
55-
56-
@Parameter(defaultValue = "${repositorySystemSession}", required = true, readonly = true)
57-
private RepositorySystemSession repositorySystemSession;
58-
59-
@Parameter(defaultValue = "${project.remotePluginRepositories}", required = true, readonly = true)
60-
private List<RemoteRepository> repositories;
61-
62-
@Parameter(defaultValue = "${project}", required = true, readonly = true)
63-
private MavenProject project;
64-
65-
@Parameter(property = "eclipseFormatFile", required = true)
66-
private String eclipseFormatFile;
40+
@Mojo(name = "apply")
41+
public class SpotlessMojo extends AbstractSpotlessMojo {
6742

6843
@Override
6944
public void execute() throws MojoExecutionException, MojoFailureException {
70-
ArtifactResolver resolver = new ArtifactResolver(repositorySystem, repositorySystemSession, repositories);
71-
Provisioner provisioner = MavenProvisioner.create(resolver);
45+
List<File> filesToFormat = collectFilesToFormat();
7246

73-
// create the eclipse step
74-
Set<File> settingFiles = singleton(new File(eclipseFormatFile));
75-
FormatterStep step = EclipseFormatterStep.create(EclipseFormatterStep.defaultVersion(),
76-
settingFiles, provisioner);
47+
Formatter formatter = createFormatter(filesToFormat);
7748

78-
// collect all the files that are going to be formatted
79-
File rootDir = project.getFile();
49+
formatAll(filesToFormat, formatter);
50+
}
51+
52+
private List<File> collectFilesToFormat() throws MojoExecutionException {
8053
List<File> toFormat = new ArrayList<>();
81-
for (String compileSourceRoot : project.getCompileSourceRoots()) {
82-
Path root = Paths.get(compileSourceRoot);
54+
for (Path root : getAllSourceRoots()) {
8355
try (Stream<Path> entries = Files.walk(root)) {
8456
entries.filter(Files::isRegularFile)
8557
.filter(file -> file.getFileName().toString().endsWith(".java"))
8658
.map(Path::toFile)
8759
.forEach(toFormat::add);
88-
} catch (Exception e) {
60+
} catch (IOException e) {
8961
throw new MojoExecutionException("Unable to walk the file tree", e);
9062
}
9163
}
64+
return toFormat;
65+
}
9266

93-
// create a formatter
94-
Formatter formatter = Formatter.builder()
95-
.lineEndingsPolicy(LineEnding.GIT_ATTRIBUTES.createPolicy(rootDir, () -> toFormat))
96-
.encoding(StandardCharsets.UTF_8)
97-
.rootDir(rootDir.toPath())
98-
.steps(Collections.singletonList(step))
67+
private Formatter createFormatter(List<File> filesToFormat) {
68+
return Formatter.builder()
69+
.encoding(getEncoding())
70+
.lineEndingsPolicy(getLineEndingsPolicy(filesToFormat))
71+
.exceptionPolicy(new FormatExceptionPolicyStrict())
72+
.steps(singletonList(createEclipseFormatterStep()))
73+
.rootDir(getRootDir().toPath())
9974
.build();
75+
}
76+
77+
private FormatterStep createEclipseFormatterStep() {
78+
ArtifactResolver artifactResolver = createArtifactResolver();
79+
Provisioner provisioner = MavenProvisioner.create(artifactResolver);
80+
Set<File> settingFiles = singleton(getJavaConfig().getEclipseConfigFile());
81+
return EclipseFormatterStep.create(EclipseFormatterStep.defaultVersion(), settingFiles, provisioner);
82+
}
10083

101-
// use the formatter to format all the files
102-
try {
103-
for (File file : toFormat) {
84+
private static void formatAll(List<File> files, Formatter formatter) throws MojoExecutionException {
85+
for (File file : files) {
86+
try {
10487
formatter.applyTo(file);
88+
} catch (IOException e) {
89+
throw new MojoExecutionException("Unable to format file " + file, e);
10590
}
106-
} catch (IOException e) {
107-
throw ThrowingEx.asRuntime(e);
10891
}
10992
}
11093
}

0 commit comments

Comments
 (0)