Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions plugin-gradle/CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<taskName>-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
- GrEclipse no longer leaves a `file%3A...` directory in the working directory. ([#2019](https://github.com/diffplug/spotless/issues/2019))

Expand Down
19 changes: 19 additions & 0 deletions plugin-gradle/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2142,6 +2142,25 @@ 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/<taskName>-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)
}
}
}
```

`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:
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -17,48 +17,107 @@

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.OutputFile;
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.
* <p>
* Defaults to {@code build/spotless/<taskName>-changed-files.txt}.
* <p>
* 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.
*/
@OutputFile
public abstract RegularFileProperty getChangedFilesReport();

@Override
void init(TaskProvider<SpotlessTaskImpl> 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
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<String> 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<String> 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;
}
}
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -93,7 +93,7 @@ void unlessBumpThisNumberIfACustomStepChanges() throws IOException {
writeBuildFile("bumpThisNumberIfACustomStepChanges(1)");
writeContentWithBadFormatting();
applyIsUpToDate(false);
applyIsUpToDate(false);
applyOnlyRerunsFormatTask(":spotlessMisc");
applyIsUpToDate(true);
checkIsUpToDate(true);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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() {
Expand Down
Loading
Loading