diff --git a/CHANGES.md b/CHANGES.md index 5a3c98ad78..e7602d9f2d 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -11,6 +11,7 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( ## [Unreleased] ### Fixed +- Ensure `LazyForwardingEquality.unlazy()` initializes roundtrip formatter steps and their nested formatter state. ([#3211](https://github.com/diffplug/spotless/pull/3211)) - Fix npm/node executable discovery treating a directory (e.g. an `npm` folder inside `NODE_PATH`) as an executable. ([#3190](https://github.com/diffplug/spotless/issues/3190)) ## [4.12.0] - 2026-11-21 diff --git a/lib/src/main/java/com/diffplug/spotless/LazyForwardingEquality.java b/lib/src/main/java/com/diffplug/spotless/LazyForwardingEquality.java index 443deb7ac3..1e00ebc8e3 100644 --- a/lib/src/main/java/com/diffplug/spotless/LazyForwardingEquality.java +++ b/lib/src/main/java/com/diffplug/spotless/LazyForwardingEquality.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2025 DiffPlug + * Copyright 2016-2026 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -127,6 +127,8 @@ static Object fromBytes(byte[] bytes) { public static void unlazy(Object in) { if (in instanceof LazyForwardingEquality equality) { equality.state(); + } else if (in instanceof FormatterStepSerializationRoundtrip step) { + ThrowingEx.run(step::stateSupplier); } else if (in instanceof DelegateFormatterStep step) { unlazy(step.delegateStep); } else if (in instanceof Iterable) { diff --git a/lib/src/main/java/com/diffplug/spotless/generic/FenceStep.java b/lib/src/main/java/com/diffplug/spotless/generic/FenceStep.java index 2ba1b52e35..515e6a4801 100644 --- a/lib/src/main/java/com/diffplug/spotless/generic/FenceStep.java +++ b/lib/src/main/java/com/diffplug/spotless/generic/FenceStep.java @@ -28,6 +28,7 @@ import com.diffplug.spotless.Formatter; import com.diffplug.spotless.FormatterFunc; import com.diffplug.spotless.FormatterStep; +import com.diffplug.spotless.LazyForwardingEquality; import com.diffplug.spotless.LineEnding; import com.diffplug.spotless.Lint; @@ -125,7 +126,10 @@ private List steps() { } public RoundtripAndEqualityState toEqualityState() { - return new RoundtripAndEqualityState(kind, regex(), steps(), true); + List nestedSteps = steps(); + // Evaluate nested step state together with the fence. + LazyForwardingEquality.unlazy(nestedSteps); + return new RoundtripAndEqualityState(kind, regex(), nestedSteps, true); } public BaseFormatter toFormatterFunc() { diff --git a/plugin-gradle/CHANGES.md b/plugin-gradle/CHANGES.md index 67e6658fad..7733970c07 100644 --- a/plugin-gradle/CHANGES.md +++ b/plugin-gradle/CHANGES.md @@ -4,6 +4,7 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( ## [Unreleased] ### Fixed +- Fix `spotlessPredeclare` with configuration cache for Maven/P2 formatter dependencies, including `googleJavaFormat()`, `greclipse()` and steps nested in `withinBlocks`, and skip provisioning for unrelated tasks. ([#2459](https://github.com/diffplug/spotless/issues/2459), [#3211](https://github.com/diffplug/spotless/pull/3211)) - Fix npm/node executable discovery treating a directory (e.g. an `npm` folder inside `NODE_PATH`) as an executable. ([#3190](https://github.com/diffplug/spotless/issues/3190)) - Fix `Cannot set the value of task ... property 'taskService'` when Spotless is applied to sibling projects but not to their parent, a regression since `8.3.0`. Applying it to the root project with `apply false` is no longer necessary. ([#2877](https://github.com/diffplug/spotless/issues/2877)) ### Changes diff --git a/plugin-gradle/README.md b/plugin-gradle/README.md index 82c9dc377c..5ed8cd5172 100644 --- a/plugin-gradle/README.md +++ b/plugin-gradle/README.md @@ -2200,6 +2200,8 @@ spotlessPredeclare { } ``` +Predeclaration initializes formatter steps that use Spotless's Maven or Eclipse P2 provisioners, including steps inside `withinBlocks`. Format configuration closures run when the task graph is ready and only when a Spotless task is scheduled. Configuration-cache hits reuse the initialized formatter state. + The older `spotless { predeclareDeps() }` and `spotless { predeclareDepsFromBuildscript() }` APIs are still supported. If you use this feature, you will get an error if you use a formatter in a subproject which is not declared in the `spotlessPredeclare` block. diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/RegisterDependenciesTask.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/RegisterDependenciesTask.java index e9ab1dc244..d3c2ea08fd 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/RegisterDependenciesTask.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/RegisterDependenciesTask.java @@ -44,8 +44,8 @@ * - Gradle wants us to resolve all our dependencies in the root project - no new dependencies in subprojects * - So, whenever a SpotlessTask in a subproject gets configured, we call {@link #hookSubprojectTask(SpotlessTask)}, * which makes this task a dependency of the SpotlessTask - * - When this "registerDependencies" task does its up-to-date check, it queries the task execution graph to see which - * SpotlessTasks are at risk of being executed, and causes them all to be evaluated safely in the root buildscript. + * - When this task is scheduled, {@link SpotlessExtensionPredeclare} resolves predeclared dependencies in its + * {@code taskGraph.whenReady} callback, before subproject Spotless tasks use them. */ @DisableCachingByDefault(because = "This task coordinates the setup and execution of other tasks, and should not be cached") public abstract class RegisterDependenciesTask extends DefaultTask { diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtensionPredeclare.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtensionPredeclare.java index ad3f69e848..6493181ca1 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtensionPredeclare.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtensionPredeclare.java @@ -35,7 +35,7 @@ public class SpotlessExtensionPredeclare extends SpotlessExtension { public SpotlessExtensionPredeclare(Project project) { super(project); - project.afterEvaluate(unused -> { + project.getGradle().getTaskGraph().whenReady(graph -> { if (policy == null) { return; } @@ -43,14 +43,17 @@ public SpotlessExtensionPredeclare(Project project) { if (task == null) { throw new IllegalStateException("spotlessPredeclare was enabled without a register dependencies task."); } + if (!graph.hasTask(task)) { + return; + } toSetup.forEach((name, formatExtension) -> { for (Action lazyAction : formatExtension.lazyActions) { lazyAction.execute(formatExtension); } task.steps.addAll(formatExtension.steps); - // needed to fix Deemon memory leaks (#1194), but this line came from https://github.com/diffplug/spotless/pull/1206 - LazyForwardingEquality.unlazy(task.steps); }); + // Resolve root steps before subproject serialization and prevent daemon leaks (#1194, #1206). + LazyForwardingEquality.unlazy(task.steps); }); } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessPredeclareIntegrationTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessPredeclareIntegrationTest.java index c765d46fd1..14b4f1d099 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessPredeclareIntegrationTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessPredeclareIntegrationTest.java @@ -18,10 +18,15 @@ import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; +import java.util.ArrayList; +import java.util.List; import org.gradle.testkit.runner.BuildResult; +import org.gradle.testkit.runner.GradleRunner; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import com.diffplug.spotless.java.GoogleJavaFormatStep; @@ -31,11 +36,72 @@ * OutOfMemoryErrors when multiple projects resolve the same dependencies concurrently. */ class SpotlessPredeclareIntegrationTest extends GradleIntegrationHarness { + private static final String GRADLE_VERSION = "9.5.1"; + + /** Creates a runner and enables parallel caching through gradle.properties when requested. */ + private GradleRunner runner(boolean configurationCache, String... arguments) throws IOException { + GradleRunner runner = gradleRunner(); + if (configurationCache) { + setFile("gradle.properties").toContent("org.gradle.configuration-cache.parallel=true"); + runner.withGradleVersion(GRADLE_VERSION); + } + List args = new ArrayList<>(List.of(arguments)); + args.add(configurationCache ? "--configuration-cache" : "--no-configuration-cache"); + return runner.withArguments(args); + } @Nested class MavenDependencies { @Test - void predeclareSucceedsWithMavenDependencies() throws IOException { + void predeclareSupportsNestedFormattersWithConfigurationCache() throws IOException { + setFile("build.gradle").toContent(""" + import com.diffplug.gradle.spotless.JavaExtension + plugins { id 'com.diffplug.spotless' } + repositories { mavenCentral() } + spotlessPredeclare { + format('docs') { + withinBlocks('java', 'BEGIN', 'END', JavaExtension) { + googleJavaFormat() + custom('identity') { input -> input } + } + } + } + // Resolution must finish in Spotless's earlier graph-ready callback. + gradle.taskGraph.whenReady { repositories.clear() } + """); + setFile("settings.gradle").toContent("include 'sub'"); + setFile("sub/build.gradle").toContent(""" + import com.diffplug.gradle.spotless.JavaExtension + plugins { id 'com.diffplug.spotless' } + spotless { + format('docs') { + target 'test.md' + toggleOffOn() + withinBlocks('java', 'BEGIN', 'END', JavaExtension) { + googleJavaFormat() + custom('identity') { input -> input } + } + } + } + """); + String unformatted = "Header\nBEGIN\nclass Foo{void bar(){}}\nEND\nFooter\n"; + setFile("sub/test.md").toContent(unformatted); + + GradleRunner runner = runner(true, ":sub:spotlessDocsApply"); + BuildResult result = runner.build(); + assertThat(result.getOutput()).contains("Configuration cache entry stored"); + String formatted = read("sub/test.md"); + assertThat(formatted).isNotEqualTo(unformatted).contains("Header", "Footer", "class Foo {", "void bar() {}"); + + setFile("sub/test.md").toContent(unformatted); + BuildResult reused = runner.build(); + assertThat(reused.getOutput()).contains("Configuration cache entry reused"); + assertThat(read("sub/test.md")).isEqualTo(formatted); + } + + @ParameterizedTest(name = "configurationCache={0}") + @ValueSource(booleans = {false, true}) + void predeclareSucceedsWithMavenDependencies(boolean configurationCache) throws IOException { setFile("build.gradle").toContent(""" plugins { id 'com.diffplug.spotless' @@ -44,6 +110,7 @@ void predeclareSucceedsWithMavenDependencies() throws IOException { spotless { predeclareDeps() } spotlessPredeclare { java { googleJavaFormat() } + kotlin { ktfmt('0.56') } } """); setFile("settings.gradle").toContent("include 'sub'"); @@ -57,17 +124,35 @@ void predeclareSucceedsWithMavenDependencies() throws IOException { target file('test.java') googleJavaFormat() } + kotlin { + target file('test.kt') + ktfmt('0.56') + } } """); setFile("sub/test.java").toResource("java/googlejavaformat/JavaCodeUnformatted.test"); + setFile("sub/test.kt").toResource("kotlin/ktfmt/basic.dirty"); - BuildResult result = gradleRunner().withArguments("spotlessApply").build(); + GradleRunner runner = runner(configurationCache, "spotlessApply"); + BuildResult result = runner.build(); assertThat(result.getOutput()).contains("BUILD SUCCESSFUL"); assertFile("sub/test.java").sameAsResource("java/googlejavaformat/JavaCodeFormatted.test"); + assertFile("sub/test.kt").sameAsResource("kotlin/ktfmt/basic.clean"); + + if (configurationCache) { + assertThat(result.getOutput()).contains("Configuration cache entry stored"); + setFile("sub/test.java").toResource("java/googlejavaformat/JavaCodeUnformatted.test"); + setFile("sub/test.kt").toResource("kotlin/ktfmt/basic.dirty"); + BuildResult reused = runner.build(); + assertThat(reused.getOutput()).contains("Configuration cache entry reused"); + assertFile("sub/test.java").sameAsResource("java/googlejavaformat/JavaCodeFormatted.test"); + assertFile("sub/test.kt").sameAsResource("kotlin/ktfmt/basic.clean"); + } } - @Test - void predeclareFailsWhenDependencyNotPredeclared() throws IOException { + @ParameterizedTest(name = "configurationCache={0}") + @ValueSource(booleans = {false, true}) + void predeclareFailsWhenDependencyNotPredeclared(boolean configurationCache) throws IOException { setFile("build.gradle").toContent(""" plugins { id 'com.diffplug.spotless' @@ -93,14 +178,15 @@ target file('test.java') """); setFile("sub/test.java").toResource("java/googlejavaformat/JavaCodeUnformatted.test"); - BuildResult result = gradleRunner().withArguments("spotlessApply").buildAndFail(); + BuildResult result = runner(configurationCache, "spotlessApply").buildAndFail(); assertThat(result.getOutput()) .contains("Add a step with [com.google.googlejavaformat:google-java-format:" + GoogleJavaFormatStep.defaultVersion() + "]") .contains("into the `spotlessPredeclare` block in the root project"); } - @Test - void predeclareWorksWithMultipleVersions() throws IOException { + @ParameterizedTest(name = "configurationCache={0}") + @ValueSource(booleans = {false, true}) + void predeclareWorksWithMultipleVersions(boolean configurationCache) throws IOException { setFile("build.gradle").toContent(""" plugins { id 'com.diffplug.spotless' @@ -139,17 +225,21 @@ target file('test.java') """); setFile("sub2/test.java").toResource("java/googlejavaformat/JavaCodeUnformatted.test"); - BuildResult result = gradleRunner().withArguments("spotlessApply").build(); + BuildResult result = runner(configurationCache, "spotlessApply").build(); assertThat(result.getOutput()).contains("BUILD SUCCESSFUL"); assertFile("sub1/test.java").sameAsResource("java/googlejavaformat/JavaCodeFormatted.test"); assertFile("sub2/test.java").sameAsResource("java/googlejavaformat/JavaCodeFormatted.test"); + if (configurationCache) { + assertThat(result.getOutput()).contains("Configuration cache entry stored"); + } } } @Nested class P2Dependencies { - @Test - void predeclareSucceedsWithEclipseFormatter() throws IOException { + @ParameterizedTest(name = "configurationCache={0}") + @ValueSource(booleans = {false, true}) + void predeclareSucceedsWithEclipseFormatter(boolean configurationCache) throws IOException { setFile("build.gradle").toContent(""" plugins { id 'com.diffplug.spotless' @@ -175,16 +265,26 @@ target file('test.java') """); setFile("sub/test.java").toResource("java/eclipse/JavaCodeUnformatted.test"); - BuildResult result = gradleRunner().withArguments("spotlessApply").build(); + GradleRunner runner = runner(configurationCache, "spotlessApply"); + BuildResult result = runner.build(); assertThat(result.getOutput()).contains("BUILD SUCCESSFUL"); // Verify the file was formatted (has proper indentation now) String formatted = read("sub/test.java"); assertThat(formatted).contains("main(String[] args)"); assertThat(formatted).as("Should be indented").doesNotStartWith("public static void main"); + + if (configurationCache) { + assertThat(result.getOutput()).contains("Configuration cache entry stored"); + setFile("sub/test.java").toResource("java/eclipse/JavaCodeUnformatted.test"); + BuildResult reused = runner.build(); + assertThat(reused.getOutput()).contains("Configuration cache entry reused"); + assertThat(read("sub/test.java")).isEqualTo(formatted); + } } - @Test - void predeclareFailsWhenEclipseFormatterNotPredeclared() throws IOException { + @ParameterizedTest(name = "configurationCache={0}") + @ValueSource(booleans = {false, true}) + void predeclareFailsWhenEclipseFormatterNotPredeclared(boolean configurationCache) throws IOException { setFile("build.gradle").toContent(""" plugins { id 'com.diffplug.spotless' @@ -210,7 +310,7 @@ target file('test.java') """); setFile("sub/test.java").toResource("java/eclipse/JavaCodeUnformatted.test"); - BuildResult result = gradleRunner().withArguments("spotlessApply").buildAndFail(); + BuildResult result = runner(configurationCache, "spotlessApply").buildAndFail(); // Eclipse JDT resolves from an embedded lockfile rather than a P2 query, so an // un-predeclared subproject fails on the Maven coordinates instead of on P2. // greclipse still has no lockfile, so it keeps the P2 message - see @@ -220,8 +320,9 @@ target file('test.java') .contains("org.eclipse.jdt:org.eclipse.jdt.core"); } - @Test - void predeclareWorksWithEclipseConfigFile() throws IOException { + @ParameterizedTest(name = "configurationCache={0}") + @ValueSource(booleans = {false, true}) + void predeclareWorksWithEclipseConfigFile(boolean configurationCache) throws IOException { setFile("eclipse-formatter.xml").toResource("java/eclipse/formatter.xml"); setFile("build.gradle").toContent(""" plugins { @@ -248,12 +349,16 @@ target file('test.java') """); setFile("sub/test.java").toResource("java/eclipse/JavaCodeUnformatted.test"); - BuildResult result = gradleRunner().withArguments("spotlessApply").build(); + BuildResult result = runner(configurationCache, "spotlessApply").build(); assertThat(result.getOutput()).contains("BUILD SUCCESSFUL"); + if (configurationCache) { + assertThat(result.getOutput()).contains("Configuration cache entry stored"); + } } - @Test - void predeclareWorksWithMultipleEclipseProjects() throws IOException { + @ParameterizedTest(name = "configurationCache={0}") + @ValueSource(booleans = {false, true}) + void predeclareWorksWithMultipleEclipseProjects(boolean configurationCache) throws IOException { setFile("build.gradle").toContent(""" plugins { id 'com.diffplug.spotless' @@ -281,8 +386,11 @@ target file('test.java') setFile("sub" + i + "/test.java").toResource("java/eclipse/JavaCodeUnformatted.test"); } - BuildResult result = gradleRunner().withArguments("spotlessApply").build(); + BuildResult result = runner(configurationCache, "spotlessApply").build(); assertThat(result.getOutput()).contains("BUILD SUCCESSFUL"); + if (configurationCache) { + assertThat(result.getOutput()).contains("Configuration cache entry stored"); + } // Verify all files were formatted for (int i = 1; i <= 3; i++) { String formatted = read("sub" + i + "/test.java"); @@ -294,8 +402,9 @@ target file('test.java') @Nested class GroovyDependencies { - @Test - void predeclareSucceedsWithGroovyGrEclipseFormatter() throws IOException { + @ParameterizedTest(name = "configurationCache={0}") + @ValueSource(booleans = {false, true}) + void predeclareSucceedsWithGroovyGrEclipseFormatter(boolean configurationCache) throws IOException { setFile("build.gradle").toContent(""" plugins { id 'com.diffplug.spotless' @@ -321,17 +430,26 @@ target file('test.groovy') } """); setFile("sub/test.groovy").toResource("groovy/greclipse/format/unformatted.test"); + String unformatted = read("sub/test.groovy"); - BuildResult result = gradleRunner().withArguments("spotlessApply").build(); + GradleRunner runner = runner(configurationCache, ":sub:spotlessGroovyApply"); + BuildResult result = runner.build(); assertThat(result.getOutput()).contains("BUILD SUCCESSFUL"); - // Verify the file was formatted String formatted = read("sub/test.groovy"); - assertThat(formatted).contains("class Foo"); - assertThat(formatted).contains("def callBar()"); + assertThat(formatted).isNotEqualTo(unformatted).contains("class Foo", "def callBar()"); + + if (configurationCache) { + assertThat(result.getOutput()).contains("Configuration cache entry stored"); + setFile("sub/test.groovy").toContent(unformatted); + BuildResult reused = runner.build(); + assertThat(reused.getOutput()).contains("Configuration cache entry reused"); + assertThat(read("sub/test.groovy")).isEqualTo(formatted); + } } - @Test - void predeclareFailsWhenGroovyGrEclipseNotPredeclared() throws IOException { + @ParameterizedTest(name = "configurationCache={0}") + @ValueSource(booleans = {false, true}) + void predeclareFailsWhenGroovyGrEclipseNotPredeclared(boolean configurationCache) throws IOException { setFile("build.gradle").toContent(""" plugins { id 'com.diffplug.spotless' @@ -358,14 +476,15 @@ target file('test.groovy') """); setFile("sub/test.groovy").toResource("groovy/greclipse/format/unformatted.test"); - BuildResult result = gradleRunner().withArguments("spotlessApply").buildAndFail(); + BuildResult result = runner(configurationCache, "spotlessApply").buildAndFail(); assertThat(result.getOutput()) .contains("P2 dependencies not predeclared") .contains("Add Eclipse formatter configuration to the `spotlessPredeclare` block in the root project"); } - @Test - void predeclareWorksWithMultipleGroovyProjects() throws IOException { + @ParameterizedTest(name = "configurationCache={0}") + @ValueSource(booleans = {false, true}) + void predeclareWorksWithMultipleGroovyProjects(boolean configurationCache) throws IOException { setFile("build.gradle").toContent(""" plugins { id 'com.diffplug.spotless' @@ -377,6 +496,7 @@ void predeclareWorksWithMultipleGroovyProjects() throws IOException { } """); setFile("settings.gradle").toContent("include 'sub1', 'sub2'"); + String unformatted = getTestResource("groovy/greclipse/format/unformatted.test"); for (int i = 1; i <= 2; i++) { setFile("sub" + i + "/build.gradle").toContent(""" plugins { @@ -391,24 +511,28 @@ target file('test.groovy') } } """); - setFile("sub" + i + "/test.groovy").toResource("groovy/greclipse/format/unformatted.test"); + setFile("sub" + i + "/test.groovy").toContent(unformatted); } - BuildResult result = gradleRunner().withArguments("spotlessApply").build(); + BuildResult result = runner(configurationCache, "spotlessApply").build(); assertThat(result.getOutput()).contains("BUILD SUCCESSFUL"); + if (configurationCache) { + assertThat(result.getOutput()).contains("Configuration cache entry stored"); + } // Verify all files were formatted for (int i = 1; i <= 2; i++) { String formatted = read("sub" + i + "/test.groovy"); - assertThat(formatted).contains("class Foo"); - assertThat(formatted).contains("def callBar()"); + assertThat(formatted).isNotEqualTo(unformatted).contains("class Foo", "def callBar()"); } } + } @Nested class MixedDependencies { - @Test - void predeclareWorksWithJavaAndGroovyFormatters() throws IOException { + @ParameterizedTest(name = "configurationCache={0}") + @ValueSource(booleans = {false, true}) + void predeclareWorksWithJavaAndGroovyFormatters(boolean configurationCache) throws IOException { setFile("build.gradle").toContent(""" plugins { id 'com.diffplug.spotless' @@ -449,8 +573,11 @@ target file('test.groovy') """); setFile("sub2/test.groovy").toResource("groovy/greclipse/format/unformatted.test"); - BuildResult result = gradleRunner().withArguments("spotlessApply").build(); + BuildResult result = runner(configurationCache, "spotlessApply").build(); assertThat(result.getOutput()).contains("BUILD SUCCESSFUL"); + if (configurationCache) { + assertThat(result.getOutput()).contains("Configuration cache entry stored"); + } // Verify Java file was formatted String javaFormatted = read("sub1/test.java"); assertThat(javaFormatted).contains("main(String[] args)"); @@ -461,8 +588,9 @@ target file('test.groovy') assertThat(groovyFormatted).contains("def callBar()"); } - @Test - void predeclareWorksWithBothMavenAndP2Dependencies() throws IOException { + @ParameterizedTest(name = "configurationCache={0}") + @ValueSource(booleans = {false, true}) + void predeclareWorksWithBothMavenAndP2Dependencies(boolean configurationCache) throws IOException { setFile("build.gradle").toContent(""" plugins { id 'com.diffplug.spotless' @@ -504,9 +632,12 @@ target file('test.java') """); setFile("sub2/test.java").toResource("java/eclipse/JavaCodeUnformatted.test"); - BuildResult result = gradleRunner().withArguments("spotlessApply").build(); + BuildResult result = runner(configurationCache, "spotlessApply").build(); assertThat(result.getOutput()).contains("BUILD SUCCESSFUL"); assertFile("sub1/test.java").sameAsResource("java/googlejavaformat/JavaCodeFormatted.test"); + if (configurationCache) { + assertThat(result.getOutput()).contains("Configuration cache entry stored"); + } // Verify Eclipse formatted file has proper indentation String eclipseFormatted = read("sub2/test.java"); assertThat(eclipseFormatted).contains("main(String[] args)"); @@ -516,8 +647,9 @@ target file('test.java') @Nested class Gradle9Compatibility { - @Test - void issue2599_Gradle951_CanUsePredeclareDepsFromBuildscript() throws IOException { + @ParameterizedTest(name = "configurationCache={0}") + @ValueSource(booleans = {false, true}) + void issue2599_Gradle951_CanUsePredeclareDepsFromBuildscript(boolean configurationCache) throws IOException { setFile("build.gradle.kts").toContent(""" import com.diffplug.gradle.spotless.SpotlessExtensionPredeclare @@ -542,17 +674,24 @@ void issue2599_Gradle951_CanUsePredeclareDepsFromBuildscript() throws IOExceptio """); setFile("src/main/kotlin/basic.kt").toResource("kotlin/ktfmt/basic.dirty"); - BuildResult result = gradleRunner() - .withGradleVersion("9.5.1") - .withArguments("spotlessApply", "--stacktrace") - .build(); + GradleRunner runner = runner(configurationCache, "spotlessApply", "--stacktrace").withGradleVersion(GRADLE_VERSION); + BuildResult result = runner.build(); assertThat(result.getOutput()).contains("BUILD SUCCESSFUL"); assertFile("src/main/kotlin/basic.kt").sameAsResource("kotlin/ktfmt/basic.clean"); + + if (configurationCache) { + assertThat(result.getOutput()).contains("Configuration cache entry stored"); + setFile("src/main/kotlin/basic.kt").toResource("kotlin/ktfmt/basic.dirty"); + BuildResult reused = runner.build(); + assertThat(reused.getOutput()).contains("Configuration cache entry reused"); + assertFile("src/main/kotlin/basic.kt").sameAsResource("kotlin/ktfmt/basic.clean"); + } } - @Test - void gradle951CanUsePredeclareWithProjectRepositories() throws IOException { + @ParameterizedTest(name = "configurationCache={0}") + @ValueSource(booleans = {false, true}) + void gradle951CanUsePredeclareWithProjectRepositories(boolean configurationCache) throws IOException { setFile("build.gradle.kts").toContent(""" import com.diffplug.gradle.spotless.SpotlessExtensionPredeclare @@ -575,25 +714,48 @@ void gradle951CanUsePredeclareWithProjectRepositories() throws IOException { """); setFile("src/main/kotlin/basic.kt").toResource("kotlin/ktfmt/basic.dirty"); - BuildResult withoutConfigurationCache = gradleRunner() - .withGradleVersion("9.5.1") - .withArguments("spotlessApply", "--stacktrace") - .build(); - assertThat(withoutConfigurationCache.getOutput()).contains("BUILD SUCCESSFUL"); + GradleRunner runner = runner(configurationCache, "spotlessApply", "--stacktrace").withGradleVersion(GRADLE_VERSION); + BuildResult result = runner.build(); + assertThat(result.getOutput()).contains("BUILD SUCCESSFUL"); assertFile("src/main/kotlin/basic.kt").sameAsResource("kotlin/ktfmt/basic.clean"); - setFile("src/main/kotlin/basic.kt").toResource("kotlin/ktfmt/basic.dirty"); - BuildResult withConfigurationCache = gradleRunner() - .withGradleVersion("9.5.1") - .withArguments("spotlessApply", "--configuration-cache", "--stacktrace") - .build(); - assertThat(withConfigurationCache.getOutput()).contains("BUILD SUCCESSFUL"); - assertFile("src/main/kotlin/basic.kt").sameAsResource("kotlin/ktfmt/basic.clean"); + if (configurationCache) { + assertThat(result.getOutput()).contains("Configuration cache entry stored"); + setFile("src/main/kotlin/basic.kt").toResource("kotlin/ktfmt/basic.dirty"); + BuildResult reused = runner.build(); + assertThat(reused.getOutput()).contains("Configuration cache entry reused"); + assertFile("src/main/kotlin/basic.kt").sameAsResource("kotlin/ktfmt/basic.clean"); + } } } @Nested class EdgeCases { + @ParameterizedTest(name = "configurationCache={0}") + @ValueSource(booleans = {false, true}) + void unrelatedTasksDoNotResolvePredeclaredDependencies(boolean configurationCache) throws IOException { + // Omitting repositories makes any formatter dependency resolution fail. + setFile("build.gradle").toContent(""" + plugins { + id 'com.diffplug.spotless' + } + spotlessPredeclare { + java { googleJavaFormat() } + } + """); + + GradleRunner runner = runner(configurationCache, "help"); + BuildResult result = runner.build(); + assertThat(result.getOutput()).contains("BUILD SUCCESSFUL"); + if (configurationCache) { + assertThat(result.getOutput()).contains("Configuration cache entry stored"); + assertThat(runner.build().getOutput()).contains("Configuration cache entry reused"); + } + + BuildResult provisioning = runner(configurationCache, RegisterDependenciesTask.TASK_NAME).buildAndFail(); + assertThat(provisioning.getOutput()).contains("com.google.googlejavaformat:google-java-format:", "because no repositories are defined"); + } + @Test void predeclareBlockEnablesPredeclareDeps() throws IOException { setFile("build.gradle").toContent(""" @@ -606,7 +768,7 @@ void predeclareBlockEnablesPredeclareDeps() throws IOException { } """); - BuildResult result = gradleRunner().withArguments("help").build(); + BuildResult result = gradleRunner().withArguments(RegisterDependenciesTask.TASK_NAME).build(); assertThat(result.getOutput()).contains("BUILD SUCCESSFUL"); } @@ -623,7 +785,7 @@ void predeclareBlockCanComeBeforePredeclareDeps() throws IOException { spotless { predeclareDeps() } """); - BuildResult result = gradleRunner().withArguments("help").build(); + BuildResult result = gradleRunner().withArguments(RegisterDependenciesTask.TASK_NAME).build(); assertThat(result.getOutput()).contains("BUILD SUCCESSFUL"); } @@ -639,24 +801,34 @@ void predeclareBlockHasKotlinDslAccessor() throws IOException { } """); - BuildResult result = gradleRunner().withArguments("help").build(); + BuildResult result = gradleRunner().withArguments(RegisterDependenciesTask.TASK_NAME).build(); assertThat(result.getOutput()).contains("BUILD SUCCESSFUL"); } - @Test - void predeclareBlockCanSelectBuildscriptRepositories() throws IOException { + @ParameterizedTest(name = "configurationCache={0}") + @ValueSource(booleans = {false, true}) + void predeclareBlockCanSelectBuildscriptRepositories(boolean configurationCache) throws IOException { setFile("build.gradle.kts").toContent(""" + buildscript { + repositories { mavenCentral() } + } plugins { id("com.diffplug.spotless") } spotlessPredeclare { format("misc") { trimTrailingWhitespace() } + java { googleJavaFormat() } fromBuildscriptRepositories() } """); - BuildResult result = gradleRunner().withArguments("help").build(); + GradleRunner runner = runner(configurationCache, RegisterDependenciesTask.TASK_NAME); + BuildResult result = runner.build(); assertThat(result.getOutput()).contains("BUILD SUCCESSFUL"); + if (configurationCache) { + assertThat(result.getOutput()).contains("Configuration cache entry stored"); + assertThat(runner.build().getOutput()).contains("Configuration cache entry reused"); + } } @Test @@ -671,7 +843,7 @@ void emptyPredeclareBlockIsValid() throws IOException { } """); - BuildResult result = gradleRunner().withArguments("help").build(); + BuildResult result = gradleRunner().withArguments(RegisterDependenciesTask.TASK_NAME).build(); assertThat(result.getOutput()).contains("BUILD SUCCESSFUL"); } } diff --git a/testlib/src/test/java/com/diffplug/spotless/LazyForwardingEqualityTest.java b/testlib/src/test/java/com/diffplug/spotless/LazyForwardingEqualityTest.java index d15eeb2773..ea09901336 100644 --- a/testlib/src/test/java/com/diffplug/spotless/LazyForwardingEqualityTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/LazyForwardingEqualityTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2021 DiffPlug + * Copyright 2016-2026 DiffPlug * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,10 +16,15 @@ package com.diffplug.spotless; import static com.diffplug.common.testing.SerializableTester.reserializeAndAssert; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; import com.diffplug.common.testing.EqualsTester; +import com.diffplug.spotless.generic.FenceStep; @SuppressWarnings("serial") class LazyForwardingEqualityTest { @@ -50,6 +55,46 @@ static class Other extends Str { } } + @Test + void unlazyEvaluatesRoundtripStepState() { + AtomicInteger stateCalculations = new AtomicInteger(); + FormatterStep step = countingStep(stateCalculations); + + LazyForwardingEquality.unlazy(step); + + assertThat(stateCalculations).hasValue(1); + } + + @Test + void unlazyEvaluatesFilteredSteps() { + AtomicInteger stateCalculations = new AtomicInteger(); + FormatterStep step = countingStep(stateCalculations) + .filterByFile(SerializableFileFilter.skipFilesNamed("skip")) + .filterByContent(OnMatch.INCLUDE, ".*"); + + LazyForwardingEquality.unlazy(List.of(step)); + + assertThat(stateCalculations).hasValue(1); + } + + @Test + void unlazyEvaluatesFencedSteps() { + AtomicInteger stateCalculations = new AtomicInteger(); + FormatterStep step = FenceStep.named("nested").openClose("begin", "end") + .applyWithin(List.of(countingStep(stateCalculations))); + + LazyForwardingEquality.unlazy(List.of(step)); + + assertThat(stateCalculations).hasValue(1); + } + + private static FormatterStep countingStep(AtomicInteger stateCalculations) { + return FormatterStep.create("test", "state", state -> { + stateCalculations.incrementAndGet(); + return state; + }, state -> input -> input); + } + @Test void testEquality() { new EqualsTester()