From c24b518464bdb86c4854dc9f1cc0b83841a84e7e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 18:14:25 +0000 Subject: [PATCH 1/4] Add failing tests for SpotlessApply changed-files report and didWork (#2715) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MTr23z6ccMd2shvyTaTFVY --- .../SpotlessApplyChangedFilesTest.java | 157 ++++++++++++++++++ 1 file changed, 157 insertions(+) create mode 100644 plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessApplyChangedFilesTest.java diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessApplyChangedFilesTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessApplyChangedFilesTest.java new file mode 100644 index 0000000000..bce0587292 --- /dev/null +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessApplyChangedFilesTest.java @@ -0,0 +1,157 @@ +/* + * Copyright 2026 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.gradle.spotless; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; + +import org.gradle.testkit.runner.BuildResult; +import org.gradle.testkit.runner.TaskOutcome; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** Tests the behavior requested in https://github.com/diffplug/spotless/issues/2715. */ +class SpotlessApplyChangedFilesTest extends GradleIntegrationHarness { + private static final String DEFAULT_REPORT = "build/spotless/spotlessMiscApply-changed-files.txt"; + + /** Lowercases every targeted file, and fails with a lint on any file containing "fubar". */ + private void writeBuildFile(String... extraLines) throws IOException { + StringBuilder build = new StringBuilder(); + build.append("plugins {\n") + .append(" id 'com.diffplug.spotless'\n") + .append("}\n") + .append("spotless {\n") + .append(" format 'misc', {\n") + .append(" target 'src/*.md'\n") + .append(" custom 'lowercase', { str -> str.toLowerCase(Locale.ROOT) }\n") + .append(" custom 'noSwearingStep', {\n") + .append(" if (it.contains('fubar')) {\n") + .append(" throw com.diffplug.spotless.Lint.atUndefinedLine('swearing', 'No swearing!').shortcut()\n") + .append(" }\n") + .append(" }\n") + .append(" bumpThisNumberIfACustomStepChanges(1)\n") + .append(" }\n") + .append("}\n"); + for (String line : extraLines) { + build.append(line).append('\n'); + } + setFile("build.gradle").toContent(build.toString()); + } + + private String report(String path) throws IOException { + File report = rootFolder().toPath().resolve(path).toFile(); + assertThat(report).as("report " + path).exists(); + return new String(Files.readAllBytes(report.toPath()), StandardCharsets.UTF_8); + } + + @Test + @DisplayName("given unformatted files, when spotlessApply runs, then it does work and the report lists exactly the rewritten files") + void reportsRewrittenFiles() throws IOException { + // given + writeBuildFile(); + setFile("src/b.md").toContent("BBB"); + setFile("src/a.md").toContent("AAA"); + setFile("src/clean.md").toContent("already clean"); + + // when + BuildResult result = gradleRunner().withArguments("spotlessApply").build(); + + // then + assertThat(result.task(":spotlessMiscApply").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertFile("src/a.md").hasContent("aaa"); + assertFile("src/b.md").hasContent("bbb"); + assertThat(report(DEFAULT_REPORT)).isEqualTo("src/a.md\nsrc/b.md\n"); + } + + @Test + @DisplayName("given only clean files, when spotlessApply runs, then it reports UP-TO-DATE and writes an empty report") + void noChangesMeansNoWork() throws IOException { + // given + writeBuildFile(); + setFile("src/clean.md").toContent("already clean"); + + // when + BuildResult result = gradleRunner().withArguments("spotlessApply").build(); + + // then the format task did run, but apply wrote nothing + assertThat(result.task(":spotlessMisc").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertThat(result.task(":spotlessMiscApply").getOutcome()).isEqualTo(TaskOutcome.UP_TO_DATE); + assertThat(report(DEFAULT_REPORT)).isEmpty(); + } + + @Test + @DisplayName("given a previous run rewrote files, when spotlessApply runs again with nothing to fix, then the report is reset to empty") + void reportReflectsMostRecentRunOnly() throws IOException { + // given + writeBuildFile(); + setFile("src/a.md").toContent("AAA"); + gradleRunner().withArguments("spotlessApply").build(); + assertThat(report(DEFAULT_REPORT)).isEqualTo("src/a.md\n"); + + // when + pauseForFilesystem(); + BuildResult result = gradleRunner().withArguments("spotlessApply").build(); + + // then + assertThat(result.task(":spotlessMiscApply").getOutcome()).isEqualTo(TaskOutcome.UP_TO_DATE); + assertThat(report(DEFAULT_REPORT)).isEmpty(); + } + + @Test + @DisplayName("given one fixable file and one file with a lint, when spotlessApply fails on the lint, then the report still lists the fixed file") + void reportIsWrittenEvenWhenLintsFail() throws IOException { + // given + writeBuildFile(); + setFile("src/a.md").toContent("AAA"); + setFile("src/swear.md").toContent("fubar"); + + // when + gradleRunner().withArguments("spotlessApply").buildAndFail(); + + // then + assertFile("src/a.md").hasContent("aaa"); + assertThat(report(DEFAULT_REPORT)).isEqualTo("src/a.md\n"); + } + + @Test + @DisplayName("given a build script that reads a custom report location in doLast, when spotlessApply rewrites files, then the build can print them") + void customReportLocationIsReadableFromBuildScript() throws IOException { + // given + writeBuildFile( + "tasks.named('spotlessMiscApply') {", + " changedFilesReport = layout.buildDirectory.file('custom/changed.txt')", + " def report = changedFilesReport", + " doLast {", + " if (didWork) {", + " report.get().asFile.readLines().each { println \"spotless fixed: $it\" }", + " }", + " }", + "}"); + setFile("src/a.md").toContent("AAA"); + + // when + BuildResult result = gradleRunner().withArguments("spotlessApply").build(); + + // then + assertThat(report("build/custom/changed.txt")).isEqualTo("src/a.md\n"); + assertThat(result.getOutput()).contains("spotless fixed: src/a.md"); + assertThat(rootFolder().toPath().resolve(DEFAULT_REPORT).toFile()).doesNotExist(); + } +} From caa1f6a7b705e6673390e9e6805cb6b2897169f5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 18:29:55 +0000 Subject: [PATCH 2/4] SpotlessApply: report changed files and only set didWork when files changed (#2715) - Each SpotlessApply writes the files its most recent run rewrote to build/spotless/-changed-files.txt (configurable via changedFilesReport). The report is empty if nothing changed and is written even when the task then fails on lints. - didWork is now true only if a source file was actually rewritten. Clean files that are byte-identical to the source are no longer copied. - UpToDateTest: the run after a fix now shows the apply tasks UP-TO-DATE while the format task still runs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MTr23z6ccMd2shvyTaTFVY --- plugin-gradle/CHANGES.md | 4 + plugin-gradle/README.md | 17 ++++ .../gradle/spotless/SpotlessApply.java | 98 +++++++++++++++---- .../gradle/spotless/UpToDateTest.java | 19 +++- 4 files changed, 113 insertions(+), 25 deletions(-) diff --git a/plugin-gradle/CHANGES.md b/plugin-gradle/CHANGES.md index 5aaef36403..df987335d0 100644 --- a/plugin-gradle/CHANGES.md +++ b/plugin-gradle/CHANGES.md @@ -3,6 +3,10 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (starting after version `3.27.0`). ## [Unreleased] +### Added +- `SpotlessApply` writes a report of the files it rewrote to `build/spotless/-changed-files.txt`, configurable via `changedFilesReport`. ([#2715](https://github.com/diffplug/spotless/issues/2715)) +### Changes +- `SpotlessApply` now only reports that it did work (and is otherwise `UP-TO-DATE`) when it actually rewrote a file. ([#2715](https://github.com/diffplug/spotless/issues/2715)) ### Fixed - GrEclipse no longer leaves a `file%3A...` directory in the working directory. ([#2019](https://github.com/diffplug/spotless/issues/2019)) diff --git a/plugin-gradle/README.md b/plugin-gradle/README.md index 019abb7008..1d41683bd0 100644 --- a/plugin-gradle/README.md +++ b/plugin-gradle/README.md @@ -2142,6 +2142,23 @@ Note that this feature is also incompatible with Isolated projects, because ever - If you don't like what spotless did, `git reset --hard` - If you'd like to remove the "checkpoint" commit, `git reset --soft head~1` will make the checkpoint commit "disappear" from history, but keeps the changes in your working directory. +### Which files did `spotlessApply` change? + +Every `SpotlessApply` task (e.g. `spotlessJavaApply`) writes the files its most recent run rewrote to `build/spotless/-changed-files.txt` (one project-relative path per line, empty if nothing changed). The task only reports that it did work when it actually rewrote a file, so you can use this to tell developers what was fixed: + +```gradle +tasks.withType(com.diffplug.gradle.spotless.SpotlessApply).configureEach { + // optional, this is the default location + changedFilesReport = layout.buildDirectory.file("spotless/${name}-changed-files.txt") + def report = changedFilesReport + doLast { + if (didWork) { + logger.lifecycle("Spotless fixed:\n" + report.get().asFile.text) + } + } +} +``` + ## Can I apply Spotless to specific files? You can target specific files by setting the `spotlessFiles` project property to a comma-separated list of file patterns: diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessApply.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessApply.java index c623669ab1..0c5aa0a9c6 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessApply.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessApply.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. @@ -17,48 +17,104 @@ import java.io.File; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.nio.file.Path; import java.nio.file.StandardCopyOption; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import org.gradle.api.GradleException; import org.gradle.api.file.ConfigurableFileTree; import org.gradle.api.file.FileVisitDetails; import org.gradle.api.file.FileVisitor; +import org.gradle.api.file.RegularFileProperty; +import org.gradle.api.tasks.Internal; import org.gradle.api.tasks.TaskAction; +import org.gradle.api.tasks.TaskProvider; import org.gradle.work.DisableCachingByDefault; @DisableCachingByDefault(because = "not worth caching") public abstract class SpotlessApply extends SpotlessTaskService.ClientTask { + /** + * Plain-text report of the files which the most recent run of this task rewrote: + * one project-relative, {@code /}-separated path per line, sorted, UTF-8. + * The report is empty if nothing was rewritten, and it is written even if the task + * then fails because of lints. + *

+ * Defaults to {@code build/spotless/-changed-files.txt}. + *

+ * Deliberately {@link Internal} rather than an output: a task which declares outputs + * but no inputs can be considered up-to-date by Gradle, and apply must always run. + */ + @Internal + public abstract RegularFileProperty getChangedFilesReport(); + + @Override + void init(TaskProvider impl) { + super.init(impl); + getChangedFilesReport().convention(getProject().getLayout().getBuildDirectory() + .file("spotless/" + getName() + "-changed-files.txt")); + } + @TaskAction public void performAction() { getTaskService().get().registerApplyAlreadyRan(this); ConfigurableFileTree cleanFiles = getConfigCacheWorkaround().fileTree().from(getSpotlessCleanDirectory().get()); ConfigurableFileTree lintsFiles = getConfigCacheWorkaround().fileTree().from(getSpotlessLintsDirectory().get()); - if (cleanFiles.isEmpty() && lintsFiles.isEmpty()) { - getState().setDidWork(sourceDidWork()); - } else { - cleanFiles.visit(new FileVisitor() { - @Override - public void visitDir(FileVisitDetails fileVisitDetails) { + List changedFiles = new ArrayList<>(); + cleanFiles.visit(new FileVisitor() { + @Override + public void visitDir(FileVisitDetails fileVisitDetails) { - } + } - @Override - public void visitFile(FileVisitDetails fileVisitDetails) { - String path = fileVisitDetails.getPath(); - File originalSource = new File(getProjectDir().get().getAsFile(), path); - try { - getLogger().debug("Copying " + fileVisitDetails.getFile() + " to " + originalSource); - Files.copy(fileVisitDetails.getFile().toPath(), originalSource.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); - } catch (IOException e) { - throw new RuntimeException(e); + @Override + public void visitFile(FileVisitDetails fileVisitDetails) { + String path = fileVisitDetails.getPath(); + File originalSource = new File(getProjectDir().get().getAsFile(), path); + try { + if (sameContent(fileVisitDetails.getFile(), originalSource)) { + // the clean file is stale (see SpotlessCheck#getUncleanFiles), nothing to apply + return; } + getLogger().debug("Copying " + fileVisitDetails.getFile() + " to " + originalSource); + Files.copy(fileVisitDetails.getFile().toPath(), originalSource.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); + changedFiles.add(path); + } catch (IOException e) { + throw new RuntimeException(e); } - }); - if (!lintsFiles.isEmpty()) { - boolean detailed = false; - throw new GradleException(super.allLintsErrorMsgDetailed(lintsFiles, detailed)); } + }); + Collections.sort(changedFiles); + writeChangedFilesReport(changedFiles); + // only report work if a source file was actually rewritten (#2715) + getState().setDidWork(!changedFiles.isEmpty()); + if (!lintsFiles.isEmpty()) { + boolean detailed = false; + throw new GradleException(super.allLintsErrorMsgDetailed(lintsFiles, detailed)); + } + } + + private void writeChangedFilesReport(List changedFiles) { + Path report = getChangedFilesReport().get().getAsFile().toPath().toAbsolutePath(); + StringBuilder content = new StringBuilder(); + for (String changedFile : changedFiles) { + content.append(changedFile).append('\n'); + } + try { + Path parent = report.getParent(); + if (parent != null) { + Files.createDirectories(parent); + } + Files.write(report, content.toString().getBytes(StandardCharsets.UTF_8)); + } catch (IOException e) { + throw new RuntimeException(e); } } + + private static boolean sameContent(File clean, File original) throws IOException { + return original.isFile() && Files.mismatch(clean.toPath(), original.toPath()) == -1L; + } } diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/UpToDateTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/UpToDateTest.java index 1c06374e9f..12a7274e4c 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/UpToDateTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/UpToDateTest.java @@ -46,11 +46,11 @@ void testNormalCase() throws IOException { applyIsUpToDate(false); assertFile("README.md").hasContent("abc"); // because a file was changed (by spotless), - // up-to-date is false, even though nothing is + // the format task runs again, even though nothing is // going to change during this run. This second // run is very fast though, because it will // only run on the few files that were changed. - applyIsUpToDate(false); + onlyFormatTaskDidWork(); // it's not until the third run that everything // is totally up-to-date applyIsUpToDate(true); @@ -70,7 +70,7 @@ void testNearPathologicalCase() throws IOException { applyIsUpToDate(false); assertFile("README.md").hasContent("ab"); // and it'll take two more runs to get to up-to-date - applyIsUpToDate(false); + onlyFormatTaskDidWork(); applyIsUpToDate(true); } @@ -93,10 +93,21 @@ void testPathologicalCase() throws IOException { assertFile("README.md").hasContent("abc"); // and it'll take two more runs to get to fully UP-TO-DATE - applyIsUpToDate(false); + onlyFormatTaskDidWork(); applyIsUpToDate(true); } + /** + * The format task runs again (its input was rewritten by the previous apply), + * but there is nothing left to apply, so the apply tasks report no work (#2715). + */ + private void onlyFormatTaskDidWork() throws IOException { + pauseForFilesystem(); + BuildResult buildResult = gradleRunner().withArguments("spotlessApply").build(); + Assertions.assertThat(outcomes(buildResult, TaskOutcome.SUCCESS)).containsExactly(":spotlessMisc"); + Assertions.assertThat(outcomes(buildResult, TaskOutcome.UP_TO_DATE)).containsExactly(":spotlessMiscApply", ":spotlessApply"); + } + @Test void checkAndApply() throws IOException { writeBuildFile(); From dc3b6627821661b28087ca423a97b8646034e362 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 19:01:32 +0000 Subject: [PATCH 3/4] Fix BumpThisNumberIfACustomStepChangesTest for accurate apply didWork (#2715) The second apply after a fix re-runs the format task, but there is nothing left to apply, so the apply tasks are now UP-TO-DATE. Move the assertion for that step into GradleIntegrationHarness#applyOnlyRerunsFormatTask and use it from both UpToDateTest and BumpThisNumberIfACustomStepChangesTest. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MTr23z6ccMd2shvyTaTFVY --- .../BumpThisNumberIfACustomStepChangesTest.java | 4 ++-- .../spotless/GradleIntegrationHarness.java | 13 +++++++++++++ .../diffplug/gradle/spotless/UpToDateTest.java | 17 +++-------------- 3 files changed, 18 insertions(+), 16 deletions(-) diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/BumpThisNumberIfACustomStepChangesTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/BumpThisNumberIfACustomStepChangesTest.java index 016b85e9e0..fe916002d3 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/BumpThisNumberIfACustomStepChangesTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/BumpThisNumberIfACustomStepChangesTest.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. @@ -93,7 +93,7 @@ void unlessBumpThisNumberIfACustomStepChanges() throws IOException { writeBuildFile("bumpThisNumberIfACustomStepChanges(1)"); writeContentWithBadFormatting(); applyIsUpToDate(false); - applyIsUpToDate(false); + applyOnlyRerunsFormatTask(":spotlessMisc"); applyIsUpToDate(true); checkIsUpToDate(true); diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIntegrationHarness.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIntegrationHarness.java index c29d98329d..1c487f8cea 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIntegrationHarness.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/GradleIntegrationHarness.java @@ -16,6 +16,7 @@ package com.diffplug.gradle.spotless; import static com.diffplug.common.base.Strings.isNullOrEmpty; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.fail; import java.io.File; @@ -188,6 +189,18 @@ public void checkIsUpToDate(boolean upToDate) throws IOException { taskIsUpToDate("spotlessCheck", upToDate); } + /** + * Runs {@code spotlessApply} after a previous apply rewrote files: the format task runs again + * (its input was rewritten), but there is nothing left to apply, so the apply tasks report + * no work (#2715). + */ + public void applyOnlyRerunsFormatTask(String formatTaskPath) throws IOException { + pauseForFilesystem(); + BuildResult buildResult = gradleRunner().withArguments("spotlessApply").build(); + assertThat(outcomes(buildResult, TaskOutcome.SUCCESS)).containsExactly(formatTaskPath); + assertThat(outcomes(buildResult, TaskOutcome.UP_TO_DATE)).containsExactly(formatTaskPath + "Apply", ":spotlessApply"); + } + private static final int FILESYSTEM_RESOLUTION_MS = FileSignature.machineIsWin() ? 150 : 2000; void pauseForFilesystem() { diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/UpToDateTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/UpToDateTest.java index 12a7274e4c..ce79954ef2 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/UpToDateTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/UpToDateTest.java @@ -50,7 +50,7 @@ void testNormalCase() throws IOException { // going to change during this run. This second // run is very fast though, because it will // only run on the few files that were changed. - onlyFormatTaskDidWork(); + applyOnlyRerunsFormatTask(":spotlessMisc"); // it's not until the third run that everything // is totally up-to-date applyIsUpToDate(true); @@ -70,7 +70,7 @@ void testNearPathologicalCase() throws IOException { applyIsUpToDate(false); assertFile("README.md").hasContent("ab"); // and it'll take two more runs to get to up-to-date - onlyFormatTaskDidWork(); + applyOnlyRerunsFormatTask(":spotlessMisc"); applyIsUpToDate(true); } @@ -93,21 +93,10 @@ void testPathologicalCase() throws IOException { assertFile("README.md").hasContent("abc"); // and it'll take two more runs to get to fully UP-TO-DATE - onlyFormatTaskDidWork(); + applyOnlyRerunsFormatTask(":spotlessMisc"); applyIsUpToDate(true); } - /** - * The format task runs again (its input was rewritten by the previous apply), - * but there is nothing left to apply, so the apply tasks report no work (#2715). - */ - private void onlyFormatTaskDidWork() throws IOException { - pauseForFilesystem(); - BuildResult buildResult = gradleRunner().withArguments("spotlessApply").build(); - Assertions.assertThat(outcomes(buildResult, TaskOutcome.SUCCESS)).containsExactly(":spotlessMisc"); - Assertions.assertThat(outcomes(buildResult, TaskOutcome.UP_TO_DATE)).containsExactly(":spotlessMiscApply", ":spotlessApply"); - } - @Test void checkAndApply() throws IOException { writeBuildFile(); From 20ac74851b9c95d30614f3d77e95aa82b0312922 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 19:57:57 +0000 Subject: [PATCH 4/4] SpotlessApply: declare changedFilesReport as an output (#2715) Addresses review feedback on #2715: the changed-files report should be a proper task output, so tasks that consume it work with Gradle's task graph and caching. - changedFilesReport is now @OutputFile instead of @Internal, so a task that uses the provider as an input gets an implicit dependency on the apply task (no manual dependsOn). - Since apply declares outputs but no inputs, Gradle would otherwise mark it UP-TO-DATE whenever the report is unchanged and skip rewriting sources; outputs.upToDateWhen { false } keeps it always running (same approach as the IDE hook). Apply stays @DisableCachingByDefault. - Tests: consumer gets implicit dependency, consumer works with the configuration cache, and apply is never skipped because its report is unchanged (fails without upToDateWhen). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MTr23wUKk2wLNAcmdt8aq3 --- plugin-gradle/CHANGES.md | 2 +- plugin-gradle/README.md | 2 + .../gradle/spotless/SpotlessApply.java | 11 +-- .../SpotlessApplyChangedFilesTest.java | 67 +++++++++++++++++++ 4 files changed, 77 insertions(+), 5 deletions(-) diff --git a/plugin-gradle/CHANGES.md b/plugin-gradle/CHANGES.md index df987335d0..b0ca68494a 100644 --- a/plugin-gradle/CHANGES.md +++ b/plugin-gradle/CHANGES.md @@ -4,7 +4,7 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( ## [Unreleased] ### Added -- `SpotlessApply` writes a report of the files it rewrote to `build/spotless/-changed-files.txt`, configurable via `changedFilesReport`. ([#2715](https://github.com/diffplug/spotless/issues/2715)) +- `SpotlessApply` writes a report of the files it rewrote to `build/spotless/-changed-files.txt`, configurable via `changedFilesReport`. The report is a task output, so tasks which take it as an input automatically depend on the apply task. ([#2715](https://github.com/diffplug/spotless/issues/2715)) ### Changes - `SpotlessApply` now only reports that it did work (and is otherwise `UP-TO-DATE`) when it actually rewrote a file. ([#2715](https://github.com/diffplug/spotless/issues/2715)) ### Fixed diff --git a/plugin-gradle/README.md b/plugin-gradle/README.md index 1d41683bd0..a38dc6fc92 100644 --- a/plugin-gradle/README.md +++ b/plugin-gradle/README.md @@ -2159,6 +2159,8 @@ tasks.withType(com.diffplug.gradle.spotless.SpotlessApply).configureEach { } ``` +`changedFilesReport` is an output of the apply task, so another task can declare it as an input (e.g. `inputs.file(tasks.named('spotlessJavaApply').flatMap { it.changedFilesReport })`) and Gradle will run the apply task first, without an explicit `dependsOn`. + ## Can I apply Spotless to specific files? You can target specific files by setting the `spotlessFiles` project property to a comma-separated list of file patterns: diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessApply.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessApply.java index 0c5aa0a9c6..1648629a40 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessApply.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessApply.java @@ -30,7 +30,7 @@ import org.gradle.api.file.FileVisitDetails; import org.gradle.api.file.FileVisitor; import org.gradle.api.file.RegularFileProperty; -import org.gradle.api.tasks.Internal; +import org.gradle.api.tasks.OutputFile; import org.gradle.api.tasks.TaskAction; import org.gradle.api.tasks.TaskProvider; import org.gradle.work.DisableCachingByDefault; @@ -45,10 +45,11 @@ public abstract class SpotlessApply extends SpotlessTaskService.ClientTask { *

* Defaults to {@code build/spotless/-changed-files.txt}. *

- * Deliberately {@link Internal} rather than an output: a task which declares outputs - * but no inputs can be considered up-to-date by Gradle, and apply must always run. + * Declared as an output, so a task which uses this provider as an input automatically + * depends on this task. Because this task has no inputs, Gradle would otherwise consider + * it up-to-date whenever the report is unchanged, so the task is forced to always run. */ - @Internal + @OutputFile public abstract RegularFileProperty getChangedFilesReport(); @Override @@ -56,6 +57,8 @@ void init(TaskProvider impl) { super.init(impl); getChangedFilesReport().convention(getProject().getLayout().getBuildDirectory() .file("spotless/" + getName() + "-changed-files.txt")); + // apply rewrites sources in place, so it must never be skipped as up-to-date + getOutputs().upToDateWhen(t -> false); } @TaskAction diff --git a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessApplyChangedFilesTest.java b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessApplyChangedFilesTest.java index bce0587292..8996251a8c 100644 --- a/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessApplyChangedFilesTest.java +++ b/plugin-gradle/src/test/java/com/diffplug/gradle/spotless/SpotlessApplyChangedFilesTest.java @@ -154,4 +154,71 @@ void customReportLocationIsReadableFromBuildScript() throws IOException { assertThat(result.getOutput()).contains("spotless fixed: src/a.md"); assertThat(rootFolder().toPath().resolve(DEFAULT_REPORT).toFile()).doesNotExist(); } + + private static final String[] CONSUMER_TASK = { + "tasks.register('printSpotlessFixes') {", + " def report = tasks.named('spotlessMiscApply').flatMap { it.changedFilesReport }", + " inputs.file(report)", + " doLast {", + " report.get().asFile.readLines().each { println \"spotless fixed: $it\" }", + " }", + "}"}; + + @Test + @DisplayName("given a task that declares the report as its input, when only that task is run, then Gradle runs spotlessApply first and the task sees the rewritten files") + void consumerOfReportDependsOnApplyImplicitly() throws IOException { + // given + writeBuildFile(CONSUMER_TASK); + setFile("src/a.md").toContent("AAA"); + + // when + BuildResult result = gradleRunner().withArguments("printSpotlessFixes").build(); + + // then + assertThat(result.task(":spotlessMiscApply")).as("apply task ran via implicit dependency").isNotNull(); + assertThat(result.task(":spotlessMiscApply").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertFile("src/a.md").hasContent("aaa"); + assertThat(result.getOutput()).contains("spotless fixed: src/a.md"); + } + + @Test + @DisplayName("given the configuration cache is enabled and a task consumes the report, when it runs twice, then the cache entry is stored and each run sees its own apply result") + void consumerOfReportWorksWithConfigurationCache() throws IOException { + // given + setFile("gradle.properties").toContent("org.gradle.configuration-cache=true"); + writeBuildFile(CONSUMER_TASK); + setFile("src/a.md").toContent("AAA"); + setFile("src/b.md").toContent("bbb"); + + // when + BuildResult first = gradleRunner().withArguments("printSpotlessFixes").build(); + pauseForFilesystem(); + setFile("src/b.md").toContent("BBB"); + BuildResult second = gradleRunner().withArguments("printSpotlessFixes").build(); + + // then + assertThat(first.getOutput()).contains("Configuration cache entry stored.").contains("spotless fixed: src/a.md"); + assertThat(second.getOutput()).contains("spotless fixed: src/b.md").doesNotContain("spotless fixed: src/a.md"); + assertFile("src/b.md").hasContent("bbb"); + } + + @Test + @DisplayName("given a previous run had nothing to fix, when a file becomes unformatted, then spotlessApply still runs and fixes it although its report output is unchanged") + void applyIsNeverSkippedBecauseItsReportIsUnchanged() throws IOException { + // given + writeBuildFile(); + setFile("src/clean.md").toContent("already clean"); + gradleRunner().withArguments("spotlessApply").build(); + assertThat(report(DEFAULT_REPORT)).isEmpty(); + + // when + pauseForFilesystem(); + setFile("src/a.md").toContent("AAA"); + BuildResult result = gradleRunner().withArguments("spotlessApply").build(); + + // then + assertThat(result.task(":spotlessMiscApply").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + assertFile("src/a.md").hasContent("aaa"); + assertThat(report(DEFAULT_REPORT)).isEqualTo("src/a.md\n"); + } }