diff --git a/README.md b/README.md
index bdf428eb46..2c01d70459 100644
--- a/README.md
+++ b/README.md
@@ -42,7 +42,7 @@ output = [
'| Toggle with [`spotless:off` and `spotless:on`](plugin-gradle/#spotlessoff-and-spotlesson) | {{yes}} | {{yes}} | {{no}} | {{no}} |',
'| [Ratchet from](https://github.com/diffplug/spotless/tree/main/plugin-gradle#ratchet) `origin/main` or other git ref | {{yes}} | {{yes}} | {{no}} | {{no}} |',
'| Define [line endings using git](https://github.com/diffplug/spotless/tree/main/plugin-gradle#line-endings-and-encodings-invisible-stuff) | {{yes}} | {{yes}} | {{yes}} | {{no}} |',
-'| Fast incremental format and up-to-date check | {{yes}} | {{no}} | {{no}} | {{no}} |',
+'| Fast incremental format and up-to-date check | {{yes}} | {{yes}} | {{no}} | {{no}} |',
'| Fast format on fresh checkout using buildcache | {{yes}} | {{no}} | {{no}} | {{no}} |',
lib('generic.EndWithNewlineStep') +'{{yes}} | {{yes}} | {{no}} | {{no}} |',
lib('generic.IndentStep') +'{{yes}} | {{yes}} | {{no}} | {{no}} |',
@@ -81,7 +81,7 @@ extra('wtp.EclipseWtpFormatterStep') +'{{yes}} | {{yes}}
| Toggle with [`spotless:off` and `spotless:on`](plugin-gradle/#spotlessoff-and-spotlesson) | :+1: | :+1: | :white_large_square: | :white_large_square: |
| [Ratchet from](https://github.com/diffplug/spotless/tree/main/plugin-gradle#ratchet) `origin/main` or other git ref | :+1: | :+1: | :white_large_square: | :white_large_square: |
| Define [line endings using git](https://github.com/diffplug/spotless/tree/main/plugin-gradle#line-endings-and-encodings-invisible-stuff) | :+1: | :+1: | :+1: | :white_large_square: |
-| Fast incremental format and up-to-date check | :+1: | :white_large_square: | :white_large_square: | :white_large_square: |
+| Fast incremental format and up-to-date check | :+1: | :+1: | :white_large_square: | :white_large_square: |
| Fast format on fresh checkout using buildcache | :+1: | :white_large_square: | :white_large_square: | :white_large_square: |
| [`generic.EndWithNewlineStep`](lib/src/main/java/com/diffplug/spotless/generic/EndWithNewlineStep.java) | :+1: | :+1: | :white_large_square: | :white_large_square: |
| [`generic.IndentStep`](lib/src/main/java/com/diffplug/spotless/generic/IndentStep.java) | :+1: | :+1: | :white_large_square: | :white_large_square: |
diff --git a/gradle.properties b/gradle.properties
index 4d4530ea8d..c50c63f277 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -16,6 +16,7 @@ artifactIdGradle=spotless-plugin-gradle
# Build requirements
VER_JAVA=1.8
VER_SPOTBUGS=4.5.0
+VER_JSR_305=3.0.2
# Dependencies provided by Spotless plugin
VER_SLF4J=[1.6,2.0[
diff --git a/gradle/java-setup.gradle b/gradle/java-setup.gradle
index 2df8805844..5d9d756414 100644
--- a/gradle/java-setup.gradle
+++ b/gradle/java-setup.gradle
@@ -35,5 +35,5 @@ tasks.named('spotbugsMain') {
dependencies {
compileOnly 'net.jcip:jcip-annotations:1.0'
compileOnly "com.github.spotbugs:spotbugs-annotations:${VER_SPOTBUGS}"
- compileOnly 'com.google.code.findbugs:jsr305:3.0.2'
+ compileOnly "com.google.code.findbugs:jsr305:${VER_JSR_305}"
}
diff --git a/plugin-maven/CHANGES.md b/plugin-maven/CHANGES.md
index 51ba44cee0..d5f1ff5b74 100644
--- a/plugin-maven/CHANGES.md
+++ b/plugin-maven/CHANGES.md
@@ -3,6 +3,8 @@
We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (starting after version `1.27.0`).
## [Unreleased]
+### Added
+* Incremental up-to-date checking ([#935](https://github.com/diffplug/spotless/pull/935)).
## [2.17.7] - 2021-12-16
### Fixed
diff --git a/plugin-maven/README.md b/plugin-maven/README.md
index a4ff8d6006..4b57e19ee8 100644
--- a/plugin-maven/README.md
+++ b/plugin-maven/README.md
@@ -900,6 +900,47 @@ If your project has not been rigorous with copyright headers, and you'd like to
+## Incremental up-to-date checking and formatting
+
+**This feature is turned off by default.**
+
+Execution of `spotless:check` and `spotless:apply` for large projects can take time.
+By default, Spotless Maven plugin needs to read and format each source file.
+Repeated executions of `spotless:check` or `spotless:apply` are completely independent.
+
+If your project has many source files managed by Spotless and formatting takes a long time, you can
+enable incremental up-to-date checking with the following configuration:
+
+```xml
+
+
+ true
+
+
+
+```
+
+With up-to-date checking enabled, Spotless creates an index file in the `target` directory.
+The index file contains source file paths and corresponding last modified timestamps.
+It allows Spotless to skip already formatted files that have not changed.
+
+**Note:** the index file is located in the `target` directory. Executing `mvn clean` will delete
+the index file, and Spotless will need to check/format all the source files.
+
+Spotless will remove the index file when up-to-date checking is explicitly turned off with the
+following configuration:
+
+```xml
+
+
+ false
+
+
+
+```
+
+Consider using this configuration if you experience issues with up-to-date checking.
+
## How can I enforce formatting gradually? (aka "ratchet")
If your project is not currently enforcing formatting, then it can be a noisy transition. Having a giant commit where every single file gets changed makes the history harder to read. To address this, you can use the `ratchet` feature:
diff --git a/plugin-maven/build.gradle b/plugin-maven/build.gradle
index f5257e065c..ac062dd497 100644
--- a/plugin-maven/build.gradle
+++ b/plugin-maven/build.gradle
@@ -79,6 +79,7 @@ dependencies {
compileOnly "org.apache.maven:maven-plugin-api:${VER_MAVEN_API}"
compileOnly "org.apache.maven.plugin-tools:maven-plugin-annotations:${VER_MAVEN_API}"
+ compileOnly "org.apache.maven:maven-core:${VER_MAVEN_API}"
compileOnly "org.eclipse.aether:aether-api:${VER_ECLIPSE_AETHER}"
compileOnly "org.eclipse.aether:aether-util:${VER_ECLIPSE_AETHER}"
@@ -95,6 +96,7 @@ dependencies {
testImplementation "org.apache.maven:maven-plugin-api:${VER_MAVEN_API}"
testImplementation "org.eclipse.aether:aether-api:${VER_ECLIPSE_AETHER}"
testImplementation "org.codehaus.plexus:plexus-resources:${VER_PLEXUS_RESOURCES}"
+ testImplementation "org.apache.maven:maven-core:${VER_MAVEN_API}"
}
task cleanMavenProjectDir(type: Delete) { delete MAVEN_PROJECT_DIR }
@@ -159,6 +161,7 @@ task createPomXml(dependsOn: installLocalDependencies) {
mavenApiVersion : VER_MAVEN_API,
eclipseAetherVersion : VER_ECLIPSE_AETHER,
spotlessLibVersion : libVersion,
+ jsr305Version : VER_JSR_305,
additionalDependencies : additionalDependencies
]
diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java
index 3a98ee240b..6f6636a946 100644
--- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java
+++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/AbstractSpotlessMojo.java
@@ -22,12 +22,16 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
+import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
+import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -37,6 +41,7 @@
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
+import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.resource.ResourceManager;
import org.codehaus.plexus.resource.loader.FileResourceLoader;
import org.codehaus.plexus.util.FileUtils;
@@ -54,6 +59,8 @@
import com.diffplug.spotless.maven.generic.Format;
import com.diffplug.spotless.maven.generic.LicenseHeader;
import com.diffplug.spotless.maven.groovy.Groovy;
+import com.diffplug.spotless.maven.incremental.UpToDateChecker;
+import com.diffplug.spotless.maven.incremental.UpToDateChecking;
import com.diffplug.spotless.maven.java.Java;
import com.diffplug.spotless.maven.kotlin.Kotlin;
import com.diffplug.spotless.maven.pom.Pom;
@@ -84,6 +91,9 @@ public abstract class AbstractSpotlessMojo extends AbstractMojo {
@Parameter(property = "spotless.check.skip", defaultValue = "false")
private boolean checkSkip;
+ @Parameter(defaultValue = "${project}", required = true, readonly = true)
+ private MavenProject project;
+
@Parameter(defaultValue = "${repositorySystemSession}", required = true, readonly = true)
private RepositorySystemSession repositorySystemSession;
@@ -147,13 +157,36 @@ public abstract class AbstractSpotlessMojo extends AbstractMojo {
@Parameter(property = LicenseHeaderStep.spotlessSetLicenseHeaderYearsFromGitHistory)
private String setLicenseHeaderYearsFromGitHistory;
- protected abstract void process(Iterable files, Formatter formatter) throws MojoExecutionException;
+ @Parameter
+ private UpToDateChecking upToDateChecking;
+
+ protected abstract void process(Iterable files, Formatter formatter, UpToDateChecker upToDateChecker) throws MojoExecutionException;
@Override
public final void execute() throws MojoExecutionException {
+ if (shouldSkip()) {
+ getLog().info(String.format("Spotless %s skipped", goal));
+ return;
+ }
+
List formatterFactories = getFormatterFactories();
+ FormatterConfig config = getFormatterConfig();
+
+ Map>> formatterFactoryToFiles = new HashMap<>();
for (FormatterFactory formatterFactory : formatterFactories) {
- execute(formatterFactory);
+ Supplier> filesToFormat = () -> collectFiles(formatterFactory, config);
+ formatterFactoryToFiles.put(formatterFactory, filesToFormat);
+ }
+
+ try (FormattersHolder formattersHolder = FormattersHolder.create(formatterFactoryToFiles, config);
+ UpToDateChecker upToDateChecker = createUpToDateChecker(formattersHolder.getFormatters())) {
+ for (Entry>> entry : formattersHolder.getFormattersWithFiles().entrySet()) {
+ Formatter formatter = entry.getKey();
+ Iterable files = entry.getValue().get();
+ process(files, formatter, upToDateChecker);
+ }
+ } catch (PluginException e) {
+ throw e.asMojoExecutionException();
}
}
@@ -169,21 +202,7 @@ private boolean shouldSkip() {
return false;
}
- private void execute(FormatterFactory formatterFactory) throws MojoExecutionException {
- if (shouldSkip()) {
- getLog().info(String.format("Spotless %s skipped", goal));
- return;
- }
-
- FormatterConfig config = getFormatterConfig();
- List files = collectFiles(formatterFactory, config);
-
- try (Formatter formatter = formatterFactory.newFormatter(files, config)) {
- process(files, formatter);
- }
- }
-
- private List collectFiles(FormatterFactory formatterFactory, FormatterConfig config) throws MojoExecutionException {
+ private List collectFiles(FormatterFactory formatterFactory, FormatterConfig config) {
Optional ratchetFrom = formatterFactory.ratchetFrom(config);
try {
final List files;
@@ -208,11 +227,11 @@ private List collectFiles(FormatterFactory formatterFactory, FormatterConf
.filter(shouldInclude)
.collect(toList());
} catch (IOException e) {
- throw new MojoExecutionException("Unable to scan file tree rooted at " + baseDir, e);
+ throw new PluginException("Unable to scan file tree rooted at " + baseDir, e);
}
}
- private List collectFilesFromGit(FormatterFactory formatterFactory, String ratchetFrom) throws MojoExecutionException {
+ private List collectFilesFromGit(FormatterFactory formatterFactory, String ratchetFrom) {
MatchPatterns includePatterns = MatchPatterns.from(
withNormalizedFileSeparators(getIncludes(formatterFactory)));
MatchPatterns excludePatterns = MatchPatterns.from(
@@ -223,7 +242,7 @@ private List collectFilesFromGit(FormatterFactory formatterFactory, String
dirtyFiles = GitRatchetMaven
.instance().getDirtyFiles(baseDir, ratchetFrom);
} catch (IOException e) {
- throw new MojoExecutionException("Unable to scan file tree rooted at " + baseDir, e);
+ throw new PluginException("Unable to scan file tree rooted at " + baseDir, e);
}
List result = new ArrayList<>();
@@ -237,8 +256,7 @@ private List collectFilesFromGit(FormatterFactory formatterFactory, String
return result;
}
- private List collectFilesFromFormatterFactory(FormatterFactory formatterFactory)
- throws MojoExecutionException, IOException {
+ private List collectFilesFromFormatterFactory(FormatterFactory formatterFactory) throws IOException {
String includesString = String.join(",", getIncludes(formatterFactory));
String excludesString = String.join(",", getExcludes(formatterFactory));
@@ -256,11 +274,11 @@ private static String withTrailingSeparator(String path) {
return path.endsWith(File.separator) ? path : path + File.separator;
}
- private Set getIncludes(FormatterFactory formatterFactory) throws MojoExecutionException {
+ private Set getIncludes(FormatterFactory formatterFactory) {
Set configuredIncludes = formatterFactory.includes();
Set includes = configuredIncludes.isEmpty() ? formatterFactory.defaultIncludes() : configuredIncludes;
if (includes.isEmpty()) {
- throw new MojoExecutionException("You must specify some files to include, such as 'src/**'");
+ throw new PluginException("You must specify some files to include, such as 'src/**'");
}
return includes;
}
@@ -300,4 +318,12 @@ private List getFormatterStepFactories() {
.filter(Objects::nonNull)
.collect(toList());
}
+
+ private UpToDateChecker createUpToDateChecker(Iterable formatters) {
+ if (upToDateChecking != null && upToDateChecking.isEnabled()) {
+ getLog().info("Up-to-date checking enabled");
+ return UpToDateChecker.forProject(project, formatters, getLog());
+ }
+ return UpToDateChecker.noop(project, getLog());
+ }
}
diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/FormatterFactory.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/FormatterFactory.java
index e15c987ffa..c06822486c 100644
--- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/FormatterFactory.java
+++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/FormatterFactory.java
@@ -24,6 +24,7 @@
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
+import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.apache.maven.plugins.annotations.Parameter;
@@ -71,10 +72,10 @@ public final Set excludes() {
return excludes == null ? emptySet() : Sets.newHashSet(excludes);
}
- public final Formatter newFormatter(List filesToFormat, FormatterConfig config) {
+ public final Formatter newFormatter(Supplier> filesToFormat, FormatterConfig config) {
Charset formatterEncoding = encoding(config);
LineEnding formatterLineEndings = lineEndings(config);
- LineEnding.Policy formatterLineEndingPolicy = formatterLineEndings.createPolicy(config.getFileLocator().getBaseDir(), () -> filesToFormat);
+ LineEnding.Policy formatterLineEndingPolicy = formatterLineEndings.createPolicy(config.getFileLocator().getBaseDir(), filesToFormat);
FormatterStepConfig stepConfig = stepConfig(formatterEncoding, config);
List factories = gatherStepFactories(config.getGlobalStepFactories(), stepFactories);
diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/FormattersHolder.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/FormattersHolder.java
new file mode 100644
index 0000000000..1c226423f6
--- /dev/null
+++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/FormattersHolder.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright 2021 DiffPlug
+ *
+ * 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.diffplug.spotless.maven;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.function.Supplier;
+
+import com.diffplug.spotless.Formatter;
+
+class FormattersHolder implements AutoCloseable {
+
+ private final Map>> formatterToFiles;
+
+ FormattersHolder(Map>> formatterToFiles) {
+ this.formatterToFiles = formatterToFiles;
+ }
+
+ static FormattersHolder create(Map>> formatterFactoryToFiles, FormatterConfig config) {
+ Map>> formatterToFiles = new HashMap<>();
+ try {
+ for (Entry>> entry : formatterFactoryToFiles.entrySet()) {
+ FormatterFactory formatterFactory = entry.getKey();
+ Supplier> files = entry.getValue();
+
+ Formatter formatter = formatterFactory.newFormatter(files, config);
+ formatterToFiles.put(formatter, files);
+ }
+ } catch (RuntimeException openError) {
+ try {
+ close(formatterToFiles.keySet());
+ } catch (Exception closeError) {
+ openError.addSuppressed(closeError);
+ }
+ throw openError;
+ }
+
+ return new FormattersHolder(formatterToFiles);
+ }
+
+ Iterable getFormatters() {
+ return formatterToFiles.keySet();
+ }
+
+ Map>> getFormattersWithFiles() {
+ return formatterToFiles;
+ }
+
+ @Override
+ public void close() {
+ try {
+ close(formatterToFiles.keySet());
+ } catch (Exception e) {
+ throw new RuntimeException("Unable to close formatters", e);
+ }
+ }
+
+ private static void close(Set formatters) throws Exception {
+ Exception error = null;
+ for (Formatter formatter : formatters) {
+ try {
+ formatter.close();
+ } catch (Exception e) {
+ if (error == null) {
+ error = e;
+ } else {
+ error.addSuppressed(e);
+ }
+ }
+ }
+ if (error != null) {
+ throw error;
+ }
+ }
+}
diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/PluginException.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/PluginException.java
new file mode 100644
index 0000000000..b7594939c7
--- /dev/null
+++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/PluginException.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2021 DiffPlug
+ *
+ * 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.diffplug.spotless.maven;
+
+import org.apache.maven.plugin.MojoExecutionException;
+
+class PluginException extends RuntimeException {
+
+ PluginException(String message) {
+ super(message);
+ }
+
+ PluginException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ MojoExecutionException asMojoExecutionException() {
+ return new MojoExecutionException(getMessage(), getCause());
+ }
+}
diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java
index b7c0c31080..6ea67240ee 100644
--- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java
+++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessApplyMojo.java
@@ -23,6 +23,7 @@
import com.diffplug.spotless.Formatter;
import com.diffplug.spotless.PaddedCell;
+import com.diffplug.spotless.maven.incremental.UpToDateChecker;
/**
* Performs formatting of all source files according to configured formatters.
@@ -31,8 +32,15 @@
public class SpotlessApplyMojo extends AbstractSpotlessMojo {
@Override
- protected void process(Iterable files, Formatter formatter) throws MojoExecutionException {
+ protected void process(Iterable files, Formatter formatter, UpToDateChecker upToDateChecker) throws MojoExecutionException {
for (File file : files) {
+ if (upToDateChecker.isUpToDate(file.toPath())) {
+ if (getLog().isDebugEnabled()) {
+ getLog().debug("Spotless will not format an up-to-date file: " + file);
+ }
+ continue;
+ }
+
try {
PaddedCell.DirtyState dirtyState = PaddedCell.calculateDirtyState(formatter, file);
if (!dirtyState.isClean() && !dirtyState.didNotConverge()) {
@@ -41,6 +49,8 @@ protected void process(Iterable files, Formatter formatter) throws MojoExe
} catch (IOException e) {
throw new MojoExecutionException("Unable to format file " + file, e);
}
+
+ upToDateChecker.setUpToDate(file.toPath());
}
}
}
diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessCheckMojo.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessCheckMojo.java
index 440a43f3bb..ad3230f583 100644
--- a/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessCheckMojo.java
+++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/SpotlessCheckMojo.java
@@ -27,6 +27,7 @@
import com.diffplug.spotless.Formatter;
import com.diffplug.spotless.PaddedCell;
import com.diffplug.spotless.extra.integration.DiffMessageFormatter;
+import com.diffplug.spotless.maven.incremental.UpToDateChecker;
/**
* Performs code formatting analysis and prints all violations to the console.
@@ -36,13 +37,22 @@
public class SpotlessCheckMojo extends AbstractSpotlessMojo {
@Override
- protected void process(Iterable files, Formatter formatter) throws MojoExecutionException {
+ protected void process(Iterable files, Formatter formatter, UpToDateChecker upToDateChecker) throws MojoExecutionException {
List problemFiles = new ArrayList<>();
for (File file : files) {
+ if (upToDateChecker.isUpToDate(file.toPath())) {
+ if (getLog().isDebugEnabled()) {
+ getLog().debug("Spotless will not check an up-to-date file: " + file);
+ }
+ continue;
+ }
+
try {
PaddedCell.DirtyState dirtyState = PaddedCell.calculateDirtyState(formatter, file);
if (!dirtyState.isClean() && !dirtyState.didNotConverge()) {
problemFiles.add(file);
+ } else {
+ upToDateChecker.setUpToDate(file.toPath());
}
} catch (IOException e) {
throw new MojoExecutionException("Unable to format file " + file, e);
diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/FileIndex.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/FileIndex.java
new file mode 100644
index 0000000000..728f8a57bc
--- /dev/null
+++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/FileIndex.java
@@ -0,0 +1,199 @@
+/*
+ * Copyright 2021 DiffPlug
+ *
+ * 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.diffplug.spotless.maven.incremental;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static java.nio.file.Files.newBufferedReader;
+import static java.nio.file.Files.newBufferedWriter;
+import static java.nio.file.StandardOpenOption.CREATE;
+import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.UncheckedIOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.time.Instant;
+import java.time.format.DateTimeParseException;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.TreeMap;
+
+import javax.annotation.Nullable;
+
+import org.apache.maven.plugin.logging.Log;
+
+import com.diffplug.common.annotations.VisibleForTesting;
+
+class FileIndex {
+
+ private static final String SEPARATOR = " ";
+
+ private final Path indexFile;
+ private final PluginFingerprint pluginFingerprint;
+ private final Map fileToLastModifiedTime;
+ private final Path projectDir;
+
+ private boolean modified;
+
+ private FileIndex(Path indexFile, PluginFingerprint pluginFingerprint, Map fileToLastModifiedTime, Path projectDir, boolean needsRewrite) {
+ this.indexFile = indexFile;
+ this.pluginFingerprint = pluginFingerprint;
+ this.fileToLastModifiedTime = fileToLastModifiedTime;
+ this.projectDir = projectDir;
+ this.modified = needsRewrite;
+ }
+
+ static FileIndex read(FileIndexConfig config, Log log) {
+ Path indexFile = config.getIndexFile();
+ if (Files.notExists(indexFile)) {
+ log.info("Index file does not exist. Fallback to an empty index");
+ return emptyIndexFallback(config);
+ }
+
+ try (BufferedReader reader = newBufferedReader(indexFile, UTF_8)) {
+ String firstLine = reader.readLine();
+ if (firstLine == null) {
+ log.info("Index file is empty. Fallback to an empty index");
+ return emptyIndexFallback(config);
+ }
+
+ PluginFingerprint computedFingerprint = config.getPluginFingerprint();
+ PluginFingerprint storedFingerprint = PluginFingerprint.from(firstLine);
+ if (!computedFingerprint.equals(storedFingerprint)) {
+ log.info("Fingerprint mismatch in the index file. Fallback to an empty index");
+ return emptyIndexFallback(config);
+ } else {
+ Content content = readIndexContent(reader, config.getProjectDir(), log);
+ return new FileIndex(indexFile, computedFingerprint, content.fileToLastModifiedTime, config.getProjectDir(), content.needsRewrite);
+ }
+ } catch (IOException e) {
+ log.warn("Error reading the index file. Fallback to an empty index", e);
+ return emptyIndexFallback(config);
+ }
+ }
+
+ static void delete(FileIndexConfig config, Log log) {
+ Path indexFile = config.getIndexFile();
+ boolean deleted = false;
+ try {
+ deleted = Files.deleteIfExists(indexFile);
+ } catch (IOException e) {
+ log.warn("Unable to delete the index file: " + indexFile, e);
+ }
+ if (deleted) {
+ log.info("Deleted the index file: " + indexFile);
+ }
+ }
+
+ @Nullable
+ Instant getLastModifiedTime(Path file) {
+ if (!file.startsWith(projectDir)) {
+ return null;
+ }
+ Path relativeFile = projectDir.relativize(file);
+ return fileToLastModifiedTime.get(relativeFile);
+ }
+
+ void setLastModifiedTime(Path file, Instant time) {
+ Path relativeFile = projectDir.relativize(file);
+ fileToLastModifiedTime.put(relativeFile, time);
+ modified = true;
+ }
+
+ @VisibleForTesting
+ int size() {
+ return fileToLastModifiedTime.size();
+ }
+
+ void write() {
+ if (!modified) {
+ return;
+ }
+
+ ensureParentDirExists();
+ try (PrintWriter writer = new PrintWriter(newBufferedWriter(indexFile, UTF_8, CREATE, TRUNCATE_EXISTING))) {
+ writer.println(pluginFingerprint.value());
+
+ for (Entry entry : fileToLastModifiedTime.entrySet()) {
+ writer.println(entry.getKey() + SEPARATOR + entry.getValue());
+ }
+ } catch (IOException e) {
+ throw new UncheckedIOException("Unable to write the index", e);
+ }
+ }
+
+ private void ensureParentDirExists() {
+ Path parentDir = indexFile.getParent();
+ if (parentDir == null) {
+ throw new IllegalStateException("Index file does not have a parent dir: " + indexFile);
+ }
+ try {
+ Files.createDirectories(parentDir);
+ } catch (IOException e) {
+ throw new UncheckedIOException("Unable to create parent directory for the index file: " + indexFile, e);
+ }
+ }
+
+ private static Content readIndexContent(BufferedReader reader, Path projectDir, Log log) throws IOException {
+ Map fileToLastModifiedTime = new TreeMap<>();
+ boolean needsRewrite = false;
+
+ String line;
+ while ((line = reader.readLine()) != null) {
+ int separatorIndex = line.lastIndexOf(SEPARATOR);
+ if (separatorIndex == -1) {
+ throw new IOException("Incorrect index file. No separator found in '" + line + "'");
+ }
+
+ Path relativeFile = Paths.get(line.substring(0, separatorIndex));
+ Path absoluteFile = projectDir.resolve(relativeFile);
+ if (Files.notExists(absoluteFile)) {
+ log.info("File stored in the index does not exist: " + relativeFile);
+ needsRewrite = true;
+ } else {
+ Instant lastModifiedTime = parseLastModifiedTime(line, separatorIndex);
+ fileToLastModifiedTime.put(relativeFile, lastModifiedTime);
+ }
+ }
+
+ return new Content(fileToLastModifiedTime, needsRewrite);
+ }
+
+ private static Instant parseLastModifiedTime(String line, int separatorIndex) throws IOException {
+ try {
+ return Instant.parse(line.substring(separatorIndex + 1));
+ } catch (DateTimeParseException e) {
+ throw new IOException("Incorrect index file. Unable to parse last modified time from '" + line + "'", e);
+ }
+ }
+
+ private static FileIndex emptyIndexFallback(FileIndexConfig config) {
+ return new FileIndex(config.getIndexFile(), config.getPluginFingerprint(), new TreeMap<>(), config.getProjectDir(), true);
+ }
+
+ private static class Content {
+ final Map fileToLastModifiedTime;
+ final boolean needsRewrite;
+
+ Content(Map fileToLastModifiedTime, boolean needsRewrite) {
+ this.fileToLastModifiedTime = fileToLastModifiedTime;
+ this.needsRewrite = needsRewrite;
+ }
+ }
+}
diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/FileIndexConfig.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/FileIndexConfig.java
new file mode 100644
index 0000000000..5ea1dcb8b5
--- /dev/null
+++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/FileIndexConfig.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2021 DiffPlug
+ *
+ * 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.diffplug.spotless.maven.incremental;
+
+import java.nio.file.Path;
+
+import org.apache.maven.project.MavenProject;
+
+class FileIndexConfig {
+
+ private static final String INDEX_FILE_NAME = "spotless-index";
+
+ private final MavenProject project;
+ private final PluginFingerprint pluginFingerprint;
+
+ FileIndexConfig(MavenProject project) {
+ this(project, PluginFingerprint.empty());
+ }
+
+ FileIndexConfig(MavenProject project, PluginFingerprint pluginFingerprint) {
+ this.project = project;
+ this.pluginFingerprint = pluginFingerprint;
+ }
+
+ Path getProjectDir() {
+ return project.getBasedir().toPath();
+ }
+
+ Path getIndexFile() {
+ Path targetDir = getProjectDir().resolve(project.getBuild().getDirectory());
+ return targetDir.resolve(INDEX_FILE_NAME);
+ }
+
+ PluginFingerprint getPluginFingerprint() {
+ return pluginFingerprint;
+ }
+}
diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/IndexBasedChecker.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/IndexBasedChecker.java
new file mode 100644
index 0000000000..e58c479f2e
--- /dev/null
+++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/IndexBasedChecker.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright 2021 DiffPlug
+ *
+ * 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.diffplug.spotless.maven.incremental;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.util.Objects;
+
+import org.apache.maven.plugin.logging.Log;
+import org.apache.maven.project.MavenProject;
+
+import com.diffplug.common.annotations.VisibleForTesting;
+import com.diffplug.spotless.Formatter;
+
+class IndexBasedChecker implements UpToDateChecker {
+
+ private final FileIndex index;
+ private final Log log;
+
+ @VisibleForTesting
+ IndexBasedChecker(FileIndex index, Log log) {
+ this.index = index;
+ this.log = log;
+ }
+
+ static IndexBasedChecker create(MavenProject project, Iterable formatters, Log log) {
+ PluginFingerprint pluginFingerprint = PluginFingerprint.from(project, formatters);
+ FileIndexConfig indexConfig = new FileIndexConfig(project, pluginFingerprint);
+ FileIndex fileIndex = FileIndex.read(indexConfig, log);
+ return new IndexBasedChecker(fileIndex, log);
+ }
+
+ @Override
+ public boolean isUpToDate(Path file) {
+ Instant storedLastModifiedTime = index.getLastModifiedTime(file);
+ return Objects.equals(storedLastModifiedTime, lastModifiedTime(file));
+ }
+
+ @Override
+ public void setUpToDate(Path file) {
+ Instant lastModified = lastModifiedTime(file);
+ if (Instant.MIN.equals(lastModified) || Instant.MAX.equals(lastModified)) {
+ // FileTime can store timestamps further in the past/future than Instant.
+ // Such timestamps are saturated to Instant.MIN/Instant.MAX.
+ // Do not store such timestamps in the index because they are imprecise.
+ log.warn("File " + file + " has an approximated last modified time of " + lastModified + ". "
+ + "It will not be recorded in the up-to-date index.");
+ return;
+ }
+ index.setLastModifiedTime(file, lastModified);
+ }
+
+ @Override
+ public void close() {
+ index.write();
+ }
+
+ private static Instant lastModifiedTime(Path path) {
+ try {
+ return Files.getLastModifiedTime(path).toInstant();
+ } catch (IOException e) {
+ throw new UncheckedIOException("Unable to get last modified date for " + path, e);
+ }
+ }
+}
diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/NoopChecker.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/NoopChecker.java
new file mode 100644
index 0000000000..0814938f5f
--- /dev/null
+++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/NoopChecker.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2021 DiffPlug
+ *
+ * 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.diffplug.spotless.maven.incremental;
+
+import java.nio.file.Path;
+
+import org.apache.maven.plugin.logging.Log;
+import org.apache.maven.project.MavenProject;
+
+class NoopChecker implements UpToDateChecker {
+
+ private NoopChecker() {}
+
+ static NoopChecker create(MavenProject project, Log log) {
+ FileIndexConfig indexConfig = new FileIndexConfig(project);
+ FileIndex.delete(indexConfig, log);
+ return new NoopChecker();
+ }
+
+ @Override
+ public boolean isUpToDate(Path file) {
+ return false;
+ }
+
+ @Override
+ public void setUpToDate(Path file) {}
+
+ @Override
+ public void close() {}
+}
diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/ObjectDigestOutputStream.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/ObjectDigestOutputStream.java
new file mode 100644
index 0000000000..8ff2c03c9f
--- /dev/null
+++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/ObjectDigestOutputStream.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright 2021 DiffPlug
+ *
+ * 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.diffplug.spotless.maven.incremental;
+
+import java.io.IOException;
+import java.io.ObjectOutputStream;
+import java.io.OutputStream;
+import java.security.DigestOutputStream;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+
+class ObjectDigestOutputStream extends ObjectOutputStream {
+
+ private final MessageDigest messageDigest;
+
+ private ObjectDigestOutputStream(DigestOutputStream out) throws IOException {
+ super(out);
+ messageDigest = out.getMessageDigest();
+ }
+
+ static ObjectDigestOutputStream create() throws IOException {
+ return new ObjectDigestOutputStream(createDigestOutputStream());
+ }
+
+ byte[] digest() {
+ return messageDigest.digest();
+ }
+
+ private static DigestOutputStream createDigestOutputStream() {
+ OutputStream nullOutputStream = new OutputStream() {
+ @Override
+ public void write(int b) {}
+ };
+
+ MessageDigest result;
+ try {
+ result = MessageDigest.getInstance("SHA-256");
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException("SHA-256 digest algorithm not available", e);
+ }
+
+ return new DigestOutputStream(nullOutputStream, result);
+ }
+}
diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/PluginFingerprint.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/PluginFingerprint.java
new file mode 100644
index 0000000000..48dfb1914d
--- /dev/null
+++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/PluginFingerprint.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright 2021 DiffPlug
+ *
+ * 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.diffplug.spotless.maven.incremental;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.Base64;
+import java.util.Objects;
+
+import org.apache.maven.model.Plugin;
+import org.apache.maven.project.MavenProject;
+
+import com.diffplug.spotless.Formatter;
+
+class PluginFingerprint {
+
+ private static final String SPOTLESS_PLUGIN_KEY = "com.diffplug.spotless:spotless-maven-plugin";
+
+ private final String value;
+
+ private PluginFingerprint(String value) {
+ this.value = value;
+ }
+
+ static PluginFingerprint from(MavenProject project, Iterable formatters) {
+ Plugin spotlessPlugin = project.getPlugin(SPOTLESS_PLUGIN_KEY);
+ byte[] digest = digest(spotlessPlugin, formatters);
+ String value = Base64.getEncoder().encodeToString(digest);
+ return new PluginFingerprint(value);
+ }
+
+ static PluginFingerprint from(String value) {
+ return new PluginFingerprint(value);
+ }
+
+ static PluginFingerprint empty() {
+ return new PluginFingerprint("");
+ }
+
+ String value() {
+ return value;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ PluginFingerprint that = (PluginFingerprint) o;
+ return value.equals(that.value);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(value);
+ }
+
+ @Override
+ public String toString() {
+ return "PluginFingerprint[" + value + "]";
+ }
+
+ private static byte[] digest(Plugin plugin, Iterable formatters) {
+ try (ObjectDigestOutputStream out = ObjectDigestOutputStream.create()) {
+ out.writeObject(plugin);
+ for (Formatter formatter : formatters) {
+ out.writeObject(formatter);
+ }
+ out.flush();
+ return out.digest();
+ } catch (IOException e) {
+ throw new UncheckedIOException("Unable to serialize plugin " + plugin, e);
+ }
+ }
+}
diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/UpToDateChecker.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/UpToDateChecker.java
new file mode 100644
index 0000000000..0851679707
--- /dev/null
+++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/UpToDateChecker.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright 2021 DiffPlug
+ *
+ * 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.diffplug.spotless.maven.incremental;
+
+import java.nio.file.Path;
+
+import org.apache.maven.plugin.logging.Log;
+import org.apache.maven.project.MavenProject;
+
+import com.diffplug.spotless.Formatter;
+
+public interface UpToDateChecker extends AutoCloseable {
+
+ boolean isUpToDate(Path file);
+
+ void setUpToDate(Path file);
+
+ void close();
+
+ static UpToDateChecker noop(MavenProject project, Log log) {
+ return NoopChecker.create(project, log);
+ }
+
+ static UpToDateChecker forProject(MavenProject project, Iterable formatters, Log log) {
+ return IndexBasedChecker.create(project, formatters, log);
+ }
+}
diff --git a/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/UpToDateChecking.java b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/UpToDateChecking.java
new file mode 100644
index 0000000000..098d24fb81
--- /dev/null
+++ b/plugin-maven/src/main/java/com/diffplug/spotless/maven/incremental/UpToDateChecking.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2021 DiffPlug
+ *
+ * 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.diffplug.spotless.maven.incremental;
+
+import org.apache.maven.plugins.annotations.Parameter;
+
+public class UpToDateChecking {
+
+ @Parameter
+ private boolean enabled;
+
+ public boolean isEnabled() {
+ return enabled;
+ }
+}
diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java
index fa5224bb8d..a5dad0b904 100644
--- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java
+++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenIntegrationHarness.java
@@ -59,6 +59,7 @@ public class MavenIntegrationHarness extends ResourceHarness {
private static final String MODULES = "modules";
private static final String MODULE_NAME = "name";
private static final String CHILD_ID = "childId";
+ private static final int REMOTE_DEBUG_PORT = 5005;
private final MustacheFactory mustacheFactory = new DefaultMustacheFactory();
@@ -153,12 +154,25 @@ protected MavenRunner mavenRunner() throws IOException {
.withLocalRepository(new File(getSystemProperty(LOCAL_MAVEN_REPOSITORY_DIR)));
}
+ /**
+ * Useful for local development. Allows debugging the Spotless Maven Plugin remotely.
+ * Effectively translates into running {@code mvnDebug} on port 5005. The forked JVM will be
+ * suspended until the debugger connects.
+ */
+ protected MavenRunner mavenRunnerWithRemoteDebug() throws IOException {
+ return mavenRunner().withRemoteDebug(REMOTE_DEBUG_PORT);
+ }
+
protected MultiModuleProjectCreator multiModuleProject() {
return new MultiModuleProjectCreator();
}
- private String createPomXmlContent(String[] executions, String[] configuration) throws IOException {
- Map params = buildPomXmlParams(executions, configuration, null);
+ protected String createPomXmlContent(String[] executions, String[] configuration) throws IOException {
+ return createPomXmlContent(null, executions, configuration);
+ }
+
+ protected String createPomXmlContent(String pluginVersion, String[] executions, String[] configuration) throws IOException {
+ Map params = buildPomXmlParams(pluginVersion, executions, configuration, null);
return createPomXmlContent("/pom-test.xml.mustache", params);
}
@@ -172,9 +186,9 @@ private String createPomXmlContent(String pomTemplate, Map param
}
}
- private static Map buildPomXmlParams(String[] executions, String[] configuration, String[] modules) {
+ private static Map buildPomXmlParams(String pluginVersion, String[] executions, String[] configuration, String[] modules) {
Map params = new HashMap<>();
- params.put(SPOTLESS_MAVEN_PLUGIN_VERSION, getSystemProperty(SPOTLESS_MAVEN_PLUGIN_VERSION));
+ params.put(SPOTLESS_MAVEN_PLUGIN_VERSION, pluginVersion == null ? getSystemProperty(SPOTLESS_MAVEN_PLUGIN_VERSION) : pluginVersion);
if (configuration != null) {
params.put(CONFIGURATION, String.join("\n", configuration));
@@ -265,7 +279,7 @@ private void createRootPom() throws IOException {
modulesList.addAll(subProjects.keySet());
String[] modules = modulesList.toArray(new String[0]);
- Map rootPomParams = buildPomXmlParams(null, configuration, modules);
+ Map rootPomParams = buildPomXmlParams(null, null, configuration, modules);
setFile("pom.xml").toContent(createPomXmlContent("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/multi-module/pom-parent.xml.mustache", rootPomParams));
}
diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenRunner.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenRunner.java
index aebf3265fc..a86e000187 100644
--- a/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenRunner.java
+++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/MavenRunner.java
@@ -23,12 +23,15 @@
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
import java.util.Objects;
import com.diffplug.common.base.Throwables;
import com.diffplug.common.io.ByteStreams;
import com.diffplug.spotless.FileSignature;
+import com.diffplug.spotless.Jvm;
/**
* Harness for running a maven build, same idea as the
@@ -44,6 +47,7 @@ private MavenRunner() {}
private File projectDir;
private String[] args;
private File localRepositoryDir;
+ private Map environment = new HashMap<>();
public MavenRunner withProjectDir(File projectDir) {
this.projectDir = Objects.requireNonNull(projectDir);
@@ -60,6 +64,12 @@ public MavenRunner withLocalRepository(File localRepositoryDir) {
return this;
}
+ public MavenRunner withRemoteDebug(int port) {
+ String address = (Jvm.version() < 9 ? "" : "*:") + port;
+ environment.put("MAVEN_OPTS", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=" + address);
+ return this;
+ }
+
private Result run() throws IOException, InterruptedException {
Objects.requireNonNull(projectDir, "Need to call withProjectDir() first");
Objects.requireNonNull(args, "Need to call withArguments() first");
@@ -68,6 +78,7 @@ private Result run() throws IOException, InterruptedException {
List cmds = getPlatformCmds("-e -Dmaven.repo.local=" + localRepositoryDir + ' ' + argsString);
ProcessBuilder builder = new ProcessBuilder(cmds);
builder.directory(projectDir);
+ builder.environment().putAll(environment);
Process process = builder.start();
// slurp and return the stdout, stderr, and exitValue
Slurper output = new Slurper(process.getInputStream());
diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexConfigTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexConfigTest.java
new file mode 100644
index 0000000000..17b3a338ba
--- /dev/null
+++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexConfigTest.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright 2021 DiffPlug
+ *
+ * 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.diffplug.spotless.maven.incremental;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.io.File;
+import java.nio.file.Paths;
+
+import org.apache.maven.model.Build;
+import org.apache.maven.project.MavenProject;
+import org.junit.jupiter.api.Test;
+
+class FileIndexConfigTest {
+
+ @Test
+ void returnsCorrectProjectDir() {
+ FileIndexConfig config = new FileIndexConfig(mavenProject(), PluginFingerprint.from("foo"));
+
+ assertThat(config.getProjectDir()).isEqualTo(Paths.get("projectDir"));
+ }
+
+ @Test
+ void returnsCorrectIndexFile() {
+ FileIndexConfig config = new FileIndexConfig(mavenProject(), PluginFingerprint.from("foo"));
+
+ assertThat(config.getIndexFile())
+ .isEqualTo(Paths.get("projectDir", "target", "spotless-index"));
+ }
+
+ @Test
+ void returnsCorrectPluginFingerprint() {
+ FileIndexConfig config = new FileIndexConfig(mavenProject(), PluginFingerprint.from("foo"));
+
+ assertThat(config.getPluginFingerprint()).isEqualTo(PluginFingerprint.from("foo"));
+ }
+
+ @Test
+ void returnsEmptyPluginFingerprint() {
+ FileIndexConfig config = new FileIndexConfig(mavenProject());
+
+ assertThat(config.getPluginFingerprint()).isEqualTo(PluginFingerprint.from(""));
+ }
+
+ private static MavenProject mavenProject() {
+ MavenProject project = new MavenProject();
+ project.setFile(new File("projectDir", "pom.xml"));
+ Build build = new Build();
+ build.setDirectory("target");
+ project.setBuild(build);
+ return project;
+ }
+}
diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexHarness.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexHarness.java
new file mode 100644
index 0000000000..8260038efa
--- /dev/null
+++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexHarness.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright 2021 DiffPlug
+ *
+ * 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.diffplug.spotless.maven.incremental;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static java.nio.file.StandardOpenOption.APPEND;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.apache.maven.plugin.logging.Log;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
+
+abstract class FileIndexHarness {
+
+ protected static final PluginFingerprint FINGERPRINT = PluginFingerprint.from("foo");
+
+ protected final FileIndexConfig config = mock(FileIndexConfig.class);
+ protected final Log log = mock(Log.class);
+
+ protected Path tempDir;
+
+ @BeforeEach
+ void beforeEach(@TempDir Path tempDir) throws Exception {
+ this.tempDir = tempDir;
+
+ Path projectDir = tempDir.resolve("my-project");
+ Files.createDirectory(projectDir);
+ when(config.getProjectDir()).thenReturn(projectDir);
+
+ Path indexFile = projectDir.resolve("target").resolve("spotless-index");
+ when(config.getIndexFile()).thenReturn(indexFile);
+
+ when(config.getPluginFingerprint()).thenReturn(FINGERPRINT);
+ }
+
+ protected List createSourceFilesAndWriteIndexFile(PluginFingerprint fingerprint, String... files) throws IOException {
+ List lines = new ArrayList<>();
+ lines.add(fingerprint.value());
+
+ List sourceFiles = new ArrayList<>();
+ for (String file : files) {
+ Path path = createSourceFile(file);
+ lines.add(file + " " + Files.getLastModifiedTime(path).toInstant());
+ sourceFiles.add(path);
+ }
+
+ writeIndexFile(lines.toArray(new String[0]));
+ return sourceFiles;
+ }
+
+ protected void writeIndexFile(String... lines) throws IOException {
+ Files.createDirectory(config.getIndexFile().getParent());
+ Files.createFile(config.getIndexFile());
+ Files.write(config.getIndexFile(), Arrays.asList(lines), UTF_8, APPEND);
+ }
+
+ protected Path createSourceFile(String name) throws IOException {
+ Path file = config.getProjectDir().resolve(name);
+ Files.createFile(file);
+ return file;
+ }
+}
diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexTest.java
new file mode 100644
index 0000000000..ce9c0077e8
--- /dev/null
+++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/FileIndexTest.java
@@ -0,0 +1,266 @@
+/*
+ * Copyright 2021 DiffPlug
+ *
+ * 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.diffplug.spotless.maven.incremental;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.contains;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.attribute.FileTime;
+import java.time.Instant;
+import java.util.List;
+
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+class FileIndexTest extends FileIndexHarness {
+
+ @Test
+ void readFallsBackToEmptyIndexWhenIndexFileDoesNotExist() {
+ FileIndex index = FileIndex.read(config, log);
+
+ assertThat(index.size()).isZero();
+ verify(log).info("Index file does not exist. Fallback to an empty index");
+ }
+
+ @Test
+ void readFallsBackToEmptyIndexWhenIndexFileIsEmpty() throws Exception {
+ writeIndexFile();
+
+ FileIndex index = FileIndex.read(config, log);
+
+ assertThat(index.size()).isZero();
+ verify(log).info("Index file is empty. Fallback to an empty index");
+ }
+
+ @Test
+ void readFallsBackToEmptyIndexOnFingerprintMismatch() throws Exception {
+ createSourceFilesAndWriteIndexFile(PluginFingerprint.from("wrong"), "source1.txt", "source2.txt");
+
+ FileIndex index = FileIndex.read(config, log);
+
+ assertThat(index.size()).isZero();
+ verify(log).info("Fingerprint mismatch in the index file. Fallback to an empty index");
+ }
+
+ @Test
+ void readFallsBackToEmptyIndexWhenIncorrectSeparator() throws Exception {
+ createSourceFile("source.txt");
+ writeIndexFile(config.getPluginFingerprint().value(), "source.txt|" + Instant.now());
+
+ FileIndex index = FileIndex.read(config, log);
+
+ assertThat(index.size()).isZero();
+ ArgumentCaptor errorCaptor = ArgumentCaptor.forClass(Throwable.class);
+ verify(log).warn(eq("Error reading the index file. Fallback to an empty index"), errorCaptor.capture());
+ assertThat(errorCaptor.getValue()).hasMessageContaining("Incorrect index file. No separator found");
+ }
+
+ @Test
+ void readFallsBackToEmptyIndexWhenUnparseableTimestamp() throws Exception {
+ createSourceFile("source.txt");
+ writeIndexFile(config.getPluginFingerprint().value(), "source.txt 12345-bad-instant");
+
+ FileIndex index = FileIndex.read(config, log);
+
+ assertThat(index.size()).isZero();
+ ArgumentCaptor errorCaptor = ArgumentCaptor.forClass(Throwable.class);
+ verify(log).warn(eq("Error reading the index file. Fallback to an empty index"), errorCaptor.capture());
+ assertThat(errorCaptor.getValue()).hasMessageContaining("Incorrect index file. Unable to parse last modified time");
+ }
+
+ @Test
+ void readEmptyIndex() throws Exception {
+ writeIndexFile("foo");
+
+ FileIndex index = FileIndex.read(config, log);
+
+ assertThat(index.size()).isZero();
+ verifyNoInteractions(log);
+ }
+
+ @Test
+ void readIndexWithSingleEntry() throws Exception {
+ Path sourceFile = createSourceFilesAndWriteIndexFile(FINGERPRINT, "source.txt").get(0);
+
+ FileIndex index = FileIndex.read(config, log);
+
+ assertThat(index.size()).isOne();
+ assertThat(index.getLastModifiedTime(sourceFile)).isEqualTo(Files.getLastModifiedTime(sourceFile).toInstant());
+ verifyNoInteractions(log);
+ }
+
+ @Test
+ void readIndexWithMultipleEntries() throws Exception {
+ List sourceFiles = createSourceFilesAndWriteIndexFile(FINGERPRINT, "source1.txt", "source2.txt", "source3.txt");
+
+ FileIndex index = FileIndex.read(config, log);
+
+ assertThat(index.size()).isEqualTo(3);
+ for (Path sourceFile : sourceFiles) {
+ assertThat(index.getLastModifiedTime(sourceFile)).isEqualTo(Files.getLastModifiedTime(sourceFile).toInstant());
+ }
+ verifyNoInteractions(log);
+ }
+
+ @Test
+ void writeIndexWithoutUpdatesDoesNotUpdateTheFile() throws Exception {
+ createSourceFilesAndWriteIndexFile(FINGERPRINT, "source.txt");
+ FileTime modifiedTimeBeforeRead = Files.getLastModifiedTime(config.getIndexFile());
+
+ FileIndex index = FileIndex.read(config, log);
+ FileTime modifiedTimeAfterRead = Files.getLastModifiedTime(config.getIndexFile());
+
+ index.write();
+ FileTime modifiedTimeAfterWrite = Files.getLastModifiedTime(config.getIndexFile());
+
+ assertThat(modifiedTimeAfterRead).isEqualTo(modifiedTimeBeforeRead);
+ assertThat(modifiedTimeAfterWrite).isEqualTo(modifiedTimeAfterRead);
+ }
+
+ @Test
+ void writeIndexContainingUpdates() throws Exception {
+ createSourceFilesAndWriteIndexFile(FINGERPRINT, "source1.txt", "source2.txt");
+ Path sourceFile3 = createSourceFile("source3.txt");
+ Path sourceFile4 = createSourceFile("source4.txt");
+ Instant modifiedTime3 = Instant.now();
+ Instant modifiedTime4 = Instant.now().plusSeconds(42);
+
+ FileIndex index1 = FileIndex.read(config, log);
+ index1.setLastModifiedTime(sourceFile3, modifiedTime3);
+ index1.setLastModifiedTime(sourceFile4, modifiedTime4);
+ index1.write();
+
+ FileIndex index2 = FileIndex.read(config, log);
+ assertThat(index2.getLastModifiedTime(sourceFile3)).isEqualTo(modifiedTime3);
+ assertThat(index2.getLastModifiedTime(sourceFile4)).isEqualTo(modifiedTime4);
+ }
+
+ @Test
+ void writeIndexWhenParentDirDoesNotExist() throws Exception {
+ assertThat(config.getIndexFile().getParent()).doesNotExist();
+ FileIndex index1 = FileIndex.read(config, log);
+ Path sourceFile = createSourceFile("source.txt");
+ Instant modifiedTime = Instant.now();
+ index1.setLastModifiedTime(sourceFile, modifiedTime);
+
+ index1.write();
+
+ assertThat(config.getIndexFile().getParent()).exists();
+ FileIndex index2 = FileIndex.read(config, log);
+ assertThat(index2.getLastModifiedTime(sourceFile)).isEqualTo(modifiedTime);
+ }
+
+ @Test
+ void deleteNonExistingIndex() {
+ FileIndex.delete(config, log);
+
+ verifyNoInteractions(log);
+ }
+
+ @Test
+ void deleteExistingIndex() throws Exception {
+ createSourceFilesAndWriteIndexFile(FINGERPRINT, "source1.txt", "source2.txt");
+ assertThat(config.getIndexFile()).exists();
+
+ FileIndex.delete(config, log);
+
+ verify(log).info(contains("Deleted the index file"));
+ assertThat(config.getIndexFile()).doesNotExist();
+ }
+
+ @Test
+ void getLastModifiedTimeReturnsEmptyOptionalForNonProjectFile() throws Exception {
+ createSourceFilesAndWriteIndexFile(FINGERPRINT, "source.txt");
+ Path nonProjectDir = tempDir.resolve("some-other-project");
+ Files.createDirectory(nonProjectDir);
+ Path nonProjectFile = Files.createFile(nonProjectDir.resolve("some-other-source.txt"));
+
+ FileIndex index = FileIndex.read(config, log);
+
+ assertThat(index.getLastModifiedTime(nonProjectFile)).isNull();
+ }
+
+ @Test
+ void getLastModifiedTimeReturnsEmptyOptionalForUnknownFile() throws Exception {
+ createSourceFilesAndWriteIndexFile(FINGERPRINT, "source.txt");
+ Path unknownSourceFile = createSourceFile("unknown-source.txt");
+
+ FileIndex index = FileIndex.read(config, log);
+
+ assertThat(index.getLastModifiedTime(unknownSourceFile)).isNull();
+ }
+
+ @Test
+ void setLastModifiedTimeThrowsForNonProjectFile() {
+ FileIndex index = FileIndex.read(config, log);
+ Path nonProjectFile = Paths.get("non-project-file");
+
+ assertThatThrownBy(() -> index.setLastModifiedTime(nonProjectFile, Instant.now())).isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ void setLastModifiedTimeUpdatesModifiedTime() throws Exception {
+ Path sourceFile = createSourceFilesAndWriteIndexFile(FINGERPRINT, "source.txt").get(0);
+ FileIndex index = FileIndex.read(config, log);
+
+ Instant oldTime = index.getLastModifiedTime(sourceFile);
+ assertThat(oldTime).isNotNull();
+
+ Instant newTime = Instant.now().plusSeconds(42);
+ assertThat(oldTime).isNotEqualTo(newTime);
+
+ index.setLastModifiedTime(sourceFile, newTime);
+ assertThat(index.getLastModifiedTime(sourceFile)).isEqualTo(newTime);
+ }
+
+ @Test
+ void rewritesIndexFileThatReferencesNonExistingFile() throws Exception {
+ createSourceFilesAndWriteIndexFile(FINGERPRINT, "source1.txt", "source2.txt");
+ Path nonExistingSourceFile = config.getProjectDir().resolve("non-existing-source.txt");
+ FileIndex index1 = FileIndex.read(config, log);
+ assertThat(index1.size()).isEqualTo(2);
+
+ index1.setLastModifiedTime(nonExistingSourceFile, Instant.now());
+ assertThat(index1.size()).isEqualTo(3);
+ index1.write();
+
+ FileIndex index2 = FileIndex.read(config, log);
+ verify(log).info("File stored in the index does not exist: " + nonExistingSourceFile.getFileName());
+ assertThat(index2.size()).isEqualTo(2);
+ index2.write();
+
+ FileIndex index3 = FileIndex.read(config, log);
+ assertThat(index3.size()).isEqualTo(2);
+ }
+
+ @Test
+ void writeFailsWhenIndexFilesDoesNotHaveParentDir() {
+ when(config.getIndexFile()).thenReturn(Paths.get("file-without-parent"));
+ FileIndex index = FileIndex.read(config, log);
+ assertThat(index.size()).isZero();
+
+ assertThatThrownBy(index::write).isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("Index file does not have a parent dir");
+ }
+}
diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/IndexBasedCheckerTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/IndexBasedCheckerTest.java
new file mode 100644
index 0000000000..7137a32e1e
--- /dev/null
+++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/IndexBasedCheckerTest.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright 2021 DiffPlug
+ *
+ * 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.diffplug.spotless.maven.incremental;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Instant;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+class IndexBasedCheckerTest extends FileIndexHarness {
+
+ private FileIndex index;
+ private IndexBasedChecker checker;
+
+ @BeforeEach
+ void beforeEach() {
+ index = FileIndex.read(config, log);
+ checker = new IndexBasedChecker(index, log);
+ }
+
+ @Test
+ void isUpToDateReturnsFalseForUnknownFile() throws Exception {
+ Path sourceFile = createSourceFile("source.txt");
+ assertThat(checker.isUpToDate(sourceFile)).isFalse();
+ }
+
+ @Test
+ void isUpToDateReturnsTrueWhenOnDiskFileIsSameAsInTheIndex() throws Exception {
+ Path sourceFile = createSourceFile("source.txt");
+ Instant modifiedTime = Files.getLastModifiedTime(sourceFile).toInstant();
+ index.setLastModifiedTime(sourceFile, modifiedTime);
+
+ assertThat(checker.isUpToDate(sourceFile)).isTrue();
+ }
+
+ @Test
+ void isUpToDateReturnsFalseWhenOnDiskFileIsNewerThanInTheIndex() throws Exception {
+ Path sourceFile = createSourceFile("source.txt");
+ Instant modifiedTime = Files.getLastModifiedTime(sourceFile).toInstant().minusSeconds(42);
+ index.setLastModifiedTime(sourceFile, modifiedTime);
+
+ assertThat(checker.isUpToDate(sourceFile)).isFalse();
+ }
+
+ /**
+ * This test checks a bit of a weird case when file's last modified time in the index is greater
+ * than file's last modified time on-disk. This should not happen because of how the index is
+ * used. To be on the safe side, we consider the file to be out of date if this ever happens.
+ */
+ @Test
+ void isUpToDateReturnsFalseWhenOnDiskFileIsOlderThanInTheIndex() throws Exception {
+ Path sourceFile = createSourceFile("source.txt");
+ Instant modifiedTime = Files.getLastModifiedTime(sourceFile).toInstant().plusSeconds(42);
+ index.setLastModifiedTime(sourceFile, modifiedTime);
+
+ assertThat(checker.isUpToDate(sourceFile)).isFalse();
+ }
+
+ @Test
+ void setUpToDateUpdatesTheIndex() throws Exception {
+ Path sourceFile = createSourceFile("source.txt");
+ assertThat(index.getLastModifiedTime(sourceFile)).isNull();
+ assertThat(checker.isUpToDate(sourceFile)).isFalse();
+
+ checker.setUpToDate(sourceFile);
+
+ assertThat(index.getLastModifiedTime(sourceFile)).isEqualTo(Files.getLastModifiedTime(sourceFile).toInstant());
+ assertThat(checker.isUpToDate(sourceFile)).isTrue();
+ }
+
+ @Test
+ void closeWritesTheIndex() throws Exception {
+ Path sourceFile = createSourceFile("source.txt");
+ assertThat(index.getLastModifiedTime(sourceFile)).isNull();
+
+ checker.setUpToDate(sourceFile);
+ checker.close();
+
+ FileIndex newIndex = FileIndex.read(config, log);
+ assertThat(newIndex.getLastModifiedTime(sourceFile)).isEqualTo(Files.getLastModifiedTime(sourceFile).toInstant());
+ }
+}
diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/NoopCheckerTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/NoopCheckerTest.java
new file mode 100644
index 0000000000..ae719273e1
--- /dev/null
+++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/NoopCheckerTest.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright 2021 DiffPlug
+ *
+ * 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.diffplug.spotless.maven.incremental;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static java.nio.file.StandardOpenOption.CREATE_NEW;
+import static java.util.Collections.singletonList;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.withSettings;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+import org.apache.maven.model.Build;
+import org.apache.maven.plugin.logging.Log;
+import org.apache.maven.project.MavenProject;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import com.diffplug.spotless.FormatExceptionPolicyStrict;
+import com.diffplug.spotless.Formatter;
+import com.diffplug.spotless.FormatterStep;
+import com.diffplug.spotless.LineEnding;
+import com.diffplug.spotless.ResourceHarness;
+
+class NoopCheckerTest extends ResourceHarness {
+
+ private MavenProject project;
+ private Path indexFile;
+ private Path existingSourceFile;
+ private Path nonExistingSourceFile;
+
+ @BeforeEach
+ void beforeEach() throws Exception {
+ project = buildMavenProject();
+ indexFile = new FileIndexConfig(project).getIndexFile();
+ existingSourceFile = project.getBasedir().toPath().resolve("existing.txt");
+ Files.write(existingSourceFile, "foo".getBytes(UTF_8), CREATE_NEW);
+ nonExistingSourceFile = project.getBasedir().toPath().resolve("non-existing.txt");
+ }
+
+ @Test
+ void deletesExistingIndexFileWhenCreated() {
+ Log log = mock(Log.class);
+ try (UpToDateChecker realChecker = UpToDateChecker.forProject(project, singletonList(dummyFormatter()), log)) {
+ realChecker.setUpToDate(existingSourceFile);
+ }
+ assertThat(indexFile).exists();
+
+ try (UpToDateChecker noopChecker = UpToDateChecker.noop(project, log)) {
+ assertThat(noopChecker).isNotNull();
+ }
+ assertThat(indexFile).doesNotExist();
+ verify(log).info("Deleted the index file: " + indexFile);
+ }
+
+ @Test
+ void doesNothingWhenIndexFileDoesNotExist() {
+ assertThat(indexFile).doesNotExist();
+
+ Log log = mock(Log.class);
+ try (UpToDateChecker noopChecker = UpToDateChecker.noop(project, log)) {
+ assertThat(noopChecker).isNotNull();
+ }
+ assertThat(indexFile).doesNotExist();
+ verifyNoInteractions(log);
+ }
+
+ @Test
+ void neverUpToDate() {
+ try (UpToDateChecker noopChecker = UpToDateChecker.noop(project, mock(Log.class))) {
+ assertThat(noopChecker.isUpToDate(existingSourceFile)).isFalse();
+ assertThat(noopChecker.isUpToDate(nonExistingSourceFile)).isFalse();
+ }
+ }
+
+ private MavenProject buildMavenProject() throws IOException {
+ File projectDir = newFolder("project");
+ File targetDir = new File(projectDir, "target");
+ File pomFile = new File(projectDir, "pom.xml");
+
+ assertThat(targetDir.mkdir()).isTrue();
+ assertThat(pomFile.createNewFile()).isTrue();
+
+ MavenProject project = new MavenProject();
+ project.setFile(pomFile);
+ Build build = new Build();
+ build.setDirectory(targetDir.getName());
+ project.setBuild(build);
+ return project;
+ }
+
+ private static Formatter dummyFormatter() {
+ return Formatter.builder()
+ .rootDir(Paths.get(""))
+ .lineEndingsPolicy(LineEnding.UNIX.createPolicy())
+ .encoding(UTF_8)
+ .steps(singletonList(mock(FormatterStep.class, withSettings().serializable())))
+ .exceptionPolicy(new FormatExceptionPolicyStrict())
+ .build();
+ }
+}
diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/PluginFingerprintTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/PluginFingerprintTest.java
new file mode 100644
index 0000000000..f0e8a0e0f0
--- /dev/null
+++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/PluginFingerprintTest.java
@@ -0,0 +1,199 @@
+/*
+ * Copyright 2021 DiffPlug
+ *
+ * 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.diffplug.spotless.maven.incremental;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static java.util.Collections.singletonList;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.io.ByteArrayInputStream;
+import java.nio.file.Paths;
+import java.util.Arrays;
+import java.util.List;
+
+import org.apache.maven.model.Model;
+import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
+import org.apache.maven.project.MavenProject;
+import org.codehaus.plexus.util.ReaderFactory;
+import org.codehaus.plexus.util.xml.XmlStreamReader;
+import org.junit.jupiter.api.Test;
+
+import com.diffplug.spotless.FormatExceptionPolicyStrict;
+import com.diffplug.spotless.Formatter;
+import com.diffplug.spotless.FormatterStep;
+import com.diffplug.spotless.LineEnding;
+import com.diffplug.spotless.maven.MavenIntegrationHarness;
+
+class PluginFingerprintTest extends MavenIntegrationHarness {
+
+ private static final String VERSION_1 = "1.0.0";
+ private static final String VERSION_2 = "2.0.0";
+
+ private static final String[] EXECUTION_1 = {
+ "",
+ " check",
+ " ",
+ " check",
+ " ",
+ ""
+ };
+ private static final String[] EXECUTION_2 = {};
+
+ private static final String[] CONFIGURATION_1 = {
+ "",
+ " 1.2",
+ ""
+ };
+ private static final String[] CONFIGURATION_2 = {
+ "",
+ " 1.8",
+ " true",
+ ""
+ };
+
+ private static final List FORMATTERS = singletonList(formatter(formatterStep("default")));
+
+ @Test
+ void sameFingerprint() throws Exception {
+ String xml1 = createPomXmlContent(VERSION_1, EXECUTION_1, CONFIGURATION_1);
+ String xml2 = createPomXmlContent(VERSION_1, EXECUTION_1, CONFIGURATION_1);
+
+ MavenProject project1 = mavenProject(xml1);
+ MavenProject project2 = mavenProject(xml2);
+
+ PluginFingerprint fingerprint1 = PluginFingerprint.from(project1, FORMATTERS);
+ PluginFingerprint fingerprint2 = PluginFingerprint.from(project2, FORMATTERS);
+
+ assertThat(fingerprint1).isEqualTo(fingerprint2);
+ }
+
+ @Test
+ void differentFingerprintForDifferentPluginVersion() throws Exception {
+ String xml1 = createPomXmlContent(VERSION_1, EXECUTION_1, CONFIGURATION_1);
+ String xml2 = createPomXmlContent(VERSION_2, EXECUTION_1, CONFIGURATION_1);
+
+ MavenProject project1 = mavenProject(xml1);
+ MavenProject project2 = mavenProject(xml2);
+
+ PluginFingerprint fingerprint1 = PluginFingerprint.from(project1, FORMATTERS);
+ PluginFingerprint fingerprint2 = PluginFingerprint.from(project2, FORMATTERS);
+
+ assertThat(fingerprint1).isNotEqualTo(fingerprint2);
+ }
+
+ @Test
+ void differentFingerprintForDifferentExecution() throws Exception {
+ String xml1 = createPomXmlContent(VERSION_2, EXECUTION_1, CONFIGURATION_1);
+ String xml2 = createPomXmlContent(VERSION_2, EXECUTION_2, CONFIGURATION_1);
+
+ MavenProject project1 = mavenProject(xml1);
+ MavenProject project2 = mavenProject(xml2);
+
+ PluginFingerprint fingerprint1 = PluginFingerprint.from(project1, FORMATTERS);
+ PluginFingerprint fingerprint2 = PluginFingerprint.from(project2, FORMATTERS);
+
+ assertThat(fingerprint1).isNotEqualTo(fingerprint2);
+ }
+
+ @Test
+ void differentFingerprintForDifferentConfiguration() throws Exception {
+ String xml1 = createPomXmlContent(VERSION_1, EXECUTION_2, CONFIGURATION_2);
+ String xml2 = createPomXmlContent(VERSION_1, EXECUTION_2, CONFIGURATION_1);
+
+ MavenProject project1 = mavenProject(xml1);
+ MavenProject project2 = mavenProject(xml2);
+
+ PluginFingerprint fingerprint1 = PluginFingerprint.from(project1, FORMATTERS);
+ PluginFingerprint fingerprint2 = PluginFingerprint.from(project2, FORMATTERS);
+
+ assertThat(fingerprint1).isNotEqualTo(fingerprint2);
+ }
+
+ @Test
+ void differentFingerprintForFormattersWithDifferentSteps() throws Exception {
+ String xml1 = createPomXmlContent(VERSION_1, EXECUTION_1, CONFIGURATION_1);
+ String xml2 = createPomXmlContent(VERSION_1, EXECUTION_1, CONFIGURATION_1);
+
+ MavenProject project1 = mavenProject(xml1);
+ MavenProject project2 = mavenProject(xml2);
+
+ FormatterStep step1 = formatterStep("step1");
+ FormatterStep step2 = formatterStep("step2");
+ FormatterStep step3 = formatterStep("step3");
+ List formatters1 = singletonList(formatter(step1, step2));
+ List formatters2 = singletonList(formatter(step2, step3));
+
+ PluginFingerprint fingerprint1 = PluginFingerprint.from(project1, formatters1);
+ PluginFingerprint fingerprint2 = PluginFingerprint.from(project2, formatters2);
+
+ assertThat(fingerprint1).isNotEqualTo(fingerprint2);
+ }
+
+ @Test
+ void differentFingerprintForFormattersWithDifferentLineEndings() throws Exception {
+ String xml1 = createPomXmlContent(VERSION_1, EXECUTION_1, CONFIGURATION_1);
+ String xml2 = createPomXmlContent(VERSION_1, EXECUTION_1, CONFIGURATION_1);
+
+ MavenProject project1 = mavenProject(xml1);
+ MavenProject project2 = mavenProject(xml2);
+
+ FormatterStep step = formatterStep("step");
+ List formatters1 = singletonList(formatter(LineEnding.UNIX, step));
+ List formatters2 = singletonList(formatter(LineEnding.WINDOWS, step));
+
+ PluginFingerprint fingerprint1 = PluginFingerprint.from(project1, formatters1);
+ PluginFingerprint fingerprint2 = PluginFingerprint.from(project2, formatters2);
+
+ assertThat(fingerprint1).isNotEqualTo(fingerprint2);
+ }
+
+ @Test
+ void emptyFingerprint() {
+ PluginFingerprint fingerprint = PluginFingerprint.empty();
+
+ assertThat(fingerprint.value()).isEmpty();
+ }
+
+ private static MavenProject mavenProject(String xml) throws Exception {
+ return new MavenProject(readPom(xml));
+ }
+
+ private static Model readPom(String xml) throws Exception {
+ byte[] bytes = xml.getBytes(UTF_8);
+ try (XmlStreamReader xmlReader = ReaderFactory.newXmlReader(new ByteArrayInputStream(bytes))) {
+ MavenXpp3Reader pomReader = new MavenXpp3Reader();
+ return pomReader.read(xmlReader);
+ }
+ }
+
+ private static FormatterStep formatterStep(String name) {
+ return FormatterStep.createNeverUpToDate(name, input -> input);
+ }
+
+ private static Formatter formatter(FormatterStep... steps) {
+ return formatter(LineEnding.UNIX, steps);
+ }
+
+ private static Formatter formatter(LineEnding lineEnding, FormatterStep... steps) {
+ return Formatter.builder()
+ .rootDir(Paths.get(""))
+ .lineEndingsPolicy(lineEnding.createPolicy())
+ .encoding(UTF_8)
+ .steps(Arrays.asList(steps))
+ .exceptionPolicy(new FormatExceptionPolicyStrict())
+ .build();
+ }
+}
diff --git a/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/UpToDateCheckingTest.java b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/UpToDateCheckingTest.java
new file mode 100644
index 0000000000..ffcd87c1fe
--- /dev/null
+++ b/plugin-maven/src/test/java/com/diffplug/spotless/maven/incremental/UpToDateCheckingTest.java
@@ -0,0 +1,204 @@
+/*
+ * Copyright 2021 DiffPlug
+ *
+ * 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.diffplug.spotless.maven.incremental;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.jupiter.api.Test;
+
+import com.diffplug.spotless.maven.MavenIntegrationHarness;
+import com.diffplug.spotless.maven.MavenRunner;
+
+class UpToDateCheckingTest extends MavenIntegrationHarness {
+
+ @Test
+ void upToDateCheckingDisabledByDefault() throws Exception {
+ writePom(
+ "",
+ " ",
+ "");
+
+ List files = writeUnformattedFiles(1);
+ String output = runSpotlessApply();
+
+ assertThat(output).doesNotContain("Up-to-date checking enabled");
+ assertFormatted(files);
+ }
+
+ @Test
+ void enableUpToDateChecking() throws Exception {
+ writePomWithUpToDateCheckingEnabled(true);
+
+ List files = writeUnformattedFiles(1);
+ String output = runSpotlessApply();
+
+ assertThat(output).contains("Up-to-date checking enabled");
+ assertFormatted(files);
+ }
+
+ @Test
+ void disableUpToDateChecking() throws Exception {
+ writePomWithUpToDateCheckingEnabled(false);
+
+ List files = writeUnformattedFiles(1);
+ String output = runSpotlessApply();
+
+ assertThat(output).doesNotContain("Up-to-date checking enabled");
+ assertFormatted(files);
+ }
+
+ @Test
+ void spotlessApplyRecordsCorrectlyFormattedFiles() throws Exception {
+ writePomWithUpToDateCheckingEnabled(true);
+ List files = writeFormattedFiles(5);
+
+ String applyOutput1 = runSpotlessApply();
+ assertSpotlessApplyDidNotSkipAnyFiles(applyOutput1);
+ assertFormatted(files);
+
+ String applyOutput2 = runSpotlessApply();
+ assertSpotlessApplySkipped(files, applyOutput2);
+
+ String checkOutput = runSpotlessCheck();
+ assertSpotlessCheckSkipped(files, checkOutput);
+ }
+
+ @Test
+ void spotlessApplyRecordsUnformattedFiles() throws Exception {
+ writePomWithUpToDateCheckingEnabled(true);
+ List files = writeUnformattedFiles(4);
+
+ String applyOutput1 = runSpotlessApply();
+ assertSpotlessApplyDidNotSkipAnyFiles(applyOutput1);
+ assertFormatted(files);
+
+ String applyOutput2 = runSpotlessApply();
+ assertSpotlessApplySkipped(files, applyOutput2);
+
+ String checkOutput = runSpotlessCheck();
+ assertSpotlessCheckSkipped(files, checkOutput);
+ }
+
+ @Test
+ void spotlessCheckRecordsCorrectlyFormattedFiles() throws Exception {
+ writePomWithUpToDateCheckingEnabled(true);
+ List files = writeFormattedFiles(7);
+
+ String checkOutput1 = runSpotlessCheck();
+ assertSpotlessCheckDidNotSkipAnyFiles(checkOutput1);
+
+ String checkOutput2 = runSpotlessCheck();
+ assertSpotlessCheckSkipped(files, checkOutput2);
+
+ String applyOutput = runSpotlessApply();
+ assertSpotlessApplySkipped(files, applyOutput);
+ }
+
+ @Test
+ void spotlessCheckRecordsUnformattedFiles() throws Exception {
+ writePomWithUpToDateCheckingEnabled(true);
+ List files = writeUnformattedFiles(6);
+
+ String checkOutput1 = runSpotlessCheckOnUnformattedFiles();
+ assertSpotlessCheckDidNotSkipAnyFiles(checkOutput1);
+
+ String checkOutput2 = runSpotlessCheckOnUnformattedFiles();
+ assertSpotlessCheckDidNotSkipAnyFiles(checkOutput2);
+
+ String applyOutput = runSpotlessApply();
+ assertSpotlessApplyDidNotSkipAnyFiles(applyOutput);
+ assertFormatted(files);
+
+ String checkOutput3 = runSpotlessCheck();
+ assertSpotlessCheckSkipped(files, checkOutput3);
+ }
+
+ private void writePomWithUpToDateCheckingEnabled(boolean enabled) throws IOException {
+ writePom(
+ "",
+ " ",
+ "",
+ "",
+ " " + enabled + "",
+ "");
+ }
+
+ private List writeFormattedFiles(int count) throws IOException {
+ return writeFiles("java/googlejavaformat/JavaCodeFormatted18.test", "formatted", count);
+ }
+
+ private List writeUnformattedFiles(int count) throws IOException {
+ return writeFiles("java/googlejavaformat/JavaCodeUnformatted.test", "unformatted", count);
+ }
+
+ private List writeFiles(String resource, String suffix, int count) throws IOException {
+ List result = new ArrayList<>(count);
+ for (int i = 0; i < count; i++) {
+ String path = "src/main/java/test_" + suffix + "_" + i + ".java";
+ File file = setFile(path).toResource(resource);
+ result.add(file);
+ }
+ return result;
+ }
+
+ private String runSpotlessApply() throws Exception {
+ return mavenRunnerForGoal("apply").runNoError().output();
+ }
+
+ private String runSpotlessCheck() throws Exception {
+ return mavenRunnerForGoal("check").runNoError().output();
+ }
+
+ private String runSpotlessCheckOnUnformattedFiles() throws Exception {
+ return mavenRunnerForGoal("check").runHasError().output();
+ }
+
+ private MavenRunner mavenRunnerForGoal(String goal) throws IOException {
+ // -X enables debug logging
+ return mavenRunner().withArguments("-X", "spotless:" + goal);
+ }
+
+ private void assertFormatted(List files) throws IOException {
+ for (File file : files) {
+ assertFile(file).sameAsResource("java/googlejavaformat/JavaCodeFormatted18.test");
+ }
+ }
+
+ private void assertSpotlessApplyDidNotSkipAnyFiles(String applyOutput) {
+ assertThat(applyOutput).doesNotContain("Spotless will not format");
+ }
+
+ private void assertSpotlessCheckDidNotSkipAnyFiles(String checkOutput) {
+ assertThat(checkOutput).doesNotContain("Spotless will not format");
+ }
+
+ private void assertSpotlessApplySkipped(List files, String applyOutput) {
+ for (File file : files) {
+ assertThat(applyOutput).contains("Spotless will not format an up-to-date file: " + file);
+ }
+ }
+
+ private void assertSpotlessCheckSkipped(List files, String checkOutput) {
+ for (File file : files) {
+ assertThat(checkOutput).contains("Spotless will not check an up-to-date file: " + file);
+ }
+ }
+}
diff --git a/plugin-maven/src/test/resources/pom-build.xml.mustache b/plugin-maven/src/test/resources/pom-build.xml.mustache
index 3b0c1c2778..3c1d1a7d5b 100644
--- a/plugin-maven/src/test/resources/pom-build.xml.mustache
+++ b/plugin-maven/src/test/resources/pom-build.xml.mustache
@@ -23,9 +23,16 @@
{{mavenApiVersion}}
{{eclipseAetherVersion}}
{{spotlessLibVersion}}
+ {{jsr305Version}}
+
+ org.apache.maven
+ maven-core
+ ${maven.api.version}
+ provided
+
org.apache.maven
maven-plugin-api
@@ -50,6 +57,12 @@
${eclipse.aether.version}
provided
+
+ com.google.code.findbugs
+ jsr305
+ ${jsr305.version}
+ provided
+
com.diffplug.spotless