Skip to content
Closed
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
28 changes: 23 additions & 5 deletions lib/src/main/java/com/diffplug/spotless/PaddedCellBulk.java
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,18 @@ public static void apply(Formatter formatter, File file) throws IOException {

/** Performs the typical spotlessApply, but with PaddedCell handling of misbehaving FormatterSteps. */
public static boolean applyAnyChanged(Formatter formatter, File file) throws IOException {
byte[] bytes = getCanonicalOrNullIfClean(formatter, file);
if (bytes != null) {
// and write them to disk if needed
Files.write(file.toPath(), bytes, StandardOpenOption.TRUNCATE_EXISTING);
return true;
} else {
return false;
}
}

/** Returns the canonical form of the given file if it is dirty, or null if its clean. */
public static byte[] getCanonicalOrNullIfClean(Formatter formatter, File file) throws IOException {
Objects.requireNonNull(formatter, "formatter");
Objects.requireNonNull(file, "file");

Expand All @@ -212,14 +224,21 @@ public static boolean applyAnyChanged(Formatter formatter, File file) throws IOE
// if F(input) == input, then the formatter is well-behaving and the input is clean
byte[] formattedBytes = formatted.getBytes(formatter.getEncoding());
if (Arrays.equals(rawBytes, formattedBytes)) {
return false;
return null;
}

// F(input) != input, so we'll do a padded check
String doubleFormattedUnix = formatter.compute(formattedUnix, file);
if (doubleFormattedUnix.equals(formattedUnix)) {
// most dirty files are idempotent-dirty, so this is a quick-short circuit for that common case
return formattedBytes;
}

PaddedCell cell = PaddedCell.check(formatter, file, rawUnix);
if (!cell.isResolvable()) {
// nothing we can do, but check will warn and dump out the divergence path
return false;
// TODO: where to put warnings?
return null;
}

// get the canonical bytes
Expand All @@ -228,10 +247,9 @@ public static boolean applyAnyChanged(Formatter formatter, File file) throws IOE
byte[] canonicalBytes = canonical.getBytes(formatter.getEncoding());
if (!Arrays.equals(rawBytes, canonicalBytes)) {
// and write them to disk if needed
Files.write(file.toPath(), canonicalBytes, StandardOpenOption.TRUNCATE_EXISTING);
return true;
return canonicalBytes;
} else {
return false;
return null;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,13 @@
package com.diffplug.gradle.spotless;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;

import org.gradle.api.GradleException;

import com.diffplug.common.base.StringPrinter;
import com.diffplug.spotless.Formatter;
import com.diffplug.spotless.PaddedCellBulk;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

/**
* Incorporates the PaddedCell machinery into SpotlessTask.apply() and SpotlessTask.check().
Expand Down Expand Up @@ -82,22 +78,4 @@ static GradleException youShouldTurnOnPaddedCell(SpotlessTask task) {
private static File diagnoseDir(SpotlessTask task) {
return new File(task.getProject().getBuildDir(), "spotless-diagnose-" + task.formatName());
}

@SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
static void check(SpotlessTask task, Formatter formatter, List<File> problemFiles) throws IOException {
if (problemFiles.isEmpty()) {
// if the first pass was successful, then paddedCell() mode is unnecessary
task.getLogger().info(StringPrinter.buildStringFromLines(
task.getName() + " is in paddedCell() mode, but it doesn't need to be.",
"If you remove that option, spotless will run ~2x faster.",
"For details see " + URL));
}

File diagnoseDir = diagnoseDir(task);
File rootDir = task.getProject().getRootDir();
List<File> stillFailing = PaddedCellBulk.check(rootDir, diagnoseDir, formatter, problemFiles);
if (!stillFailing.isEmpty()) {
throw task.formatViolationsFor(formatter, problemFiles);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* Copyright 2016 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 java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

import org.gradle.api.DefaultTask;
import org.gradle.api.file.ConfigurableFileTree;
import org.gradle.api.file.FileVisitDetails;
import org.gradle.api.file.FileVisitor;
import org.gradle.api.tasks.InputDirectory;
import org.gradle.api.tasks.SkipWhenEmpty;
import org.gradle.api.tasks.TaskAction;

public class SpotlessApply extends DefaultTask {
private File spotlessOutDirectory;

@InputDirectory
@SkipWhenEmpty
public File getSpotlessOutDirectory() {
return spotlessOutDirectory;
}

public void setSpotlessOutDirectory(File spotlessOutDirectory) {
this.spotlessOutDirectory = spotlessOutDirectory;
}

@TaskAction
public void performAction() {
ConfigurableFileTree files = getProject().fileTree(spotlessOutDirectory);
if (files.isEmpty()) {
System.out.println("NOTHING TO DO");
} else {
files.visit(new FileVisitor() {
@Override
public void visitDir(FileVisitDetails fileVisitDetails) {

}

@Override
public void visitFile(FileVisitDetails fileVisitDetails) {
String path = fileVisitDetails.getPath();
File originalSource = new File(getProject().getProjectDir(), path);
try {
System.out.println("Copying " + fileVisitDetails.getFile() + " to " + originalSource);
Files.copy(fileVisitDetails.getFile().toPath(), originalSource.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* Copyright 2016 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 java.io.File;

import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.file.ConfigurableFileTree;
import org.gradle.api.tasks.InputDirectory;
import org.gradle.api.tasks.SkipWhenEmpty;
import org.gradle.api.tasks.TaskAction;

public class SpotlessCheck extends DefaultTask {
public SpotlessTask formatTask;

private File spotlessOutDirectory;

@InputDirectory
@SkipWhenEmpty
public File getSpotlessOutDirectory() {
return spotlessOutDirectory;
}

public void setSpotlessOutDirectory(File spotlessOutDirectory) {
this.spotlessOutDirectory = spotlessOutDirectory;
}

@TaskAction
public void performAction() throws Exception {
ConfigurableFileTree files = getProject().fileTree(spotlessOutDirectory);
if (!files.isEmpty()) {
throw new GradleException("Run 'gradlew spotlessApply' to fix these violations.");
/*
* TODO: problemFiles is expected to be the "real files"
* This error message should now take the "real files" and "error files" as the inputs, rather than
* the "real files" and the formatter.
DiffMessageFormatter.builder()
.runToFix("Run 'gradlew spotlessApply' to fix these violations.")
.isPaddedCell(paddedCell)
.formatter(formatter)
.problemFiles(problemFiles)
.getMessage());
*/
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,11 @@
import org.gradle.api.GradleException;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.execution.TaskExecutionGraph;
import org.gradle.api.plugins.BasePlugin;

import com.diffplug.common.base.Errors;
import com.diffplug.spotless.LineEnding;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import groovy.lang.Closure;

public class SpotlessExtension {
final Project project;
final Task rootCheckTask, rootApplyTask;
Expand Down Expand Up @@ -234,7 +230,7 @@ private <T extends FormatExtension> T maybeCreate(String name, Class<T> clazz) {
Constructor<T> constructor = clazz.getConstructor(SpotlessExtension.class);
T formatExtension = constructor.newInstance(this);
formats.put(name, formatExtension);
createFormatTask(name, formatExtension);
createFormatTasks(name, formatExtension);
return formatExtension;
} catch (NoSuchMethodException e) {
throw new GradleException("Must have a constructor " + clazz.getSimpleName() + "(SpotlessExtension root)", e);
Expand All @@ -244,8 +240,14 @@ private <T extends FormatExtension> T maybeCreate(String name, Class<T> clazz) {
}
}

/**
* Creates 3 tasks for the supplied format:
* - "spotless{FormatName}" is the main `SpotlessTask` that does the work for this format
* - "spotless{FormatName}Check" will depend on the main spotless task in `check` mode
* - "spotless{FormatName}Apply" will depend on the main spotless task in `apply` mode
*/
@SuppressWarnings("rawtypes")
private void createFormatTask(String name, FormatExtension formatExtension) {
private void createFormatTasks(String name, FormatExtension formatExtension) {
// create the SpotlessTask
String taskName = EXTENSION + SpotlessPlugin.capitalize(name);
SpotlessTask spotlessTask = project.getTasks().create(taskName, SpotlessTask.class);
Expand All @@ -256,27 +258,14 @@ private void createFormatTask(String name, FormatExtension formatExtension) {
spotlessTask.mustRunAfter(clean);

// create the check and apply control tasks
Task checkTask = project.getTasks().create(taskName + CHECK);
Task applyTask = project.getTasks().create(taskName + APPLY);

SpotlessCheck checkTask = project.getTasks().create(taskName + CHECK, SpotlessCheck.class);
checkTask.setSpotlessOutDirectory(spotlessTask.getOutputDirectory());
checkTask.formatTask = spotlessTask;
checkTask.dependsOn(spotlessTask);

SpotlessApply applyTask = project.getTasks().create(taskName + APPLY, SpotlessApply.class);
applyTask.setSpotlessOutDirectory(spotlessTask.getOutputDirectory());
applyTask.dependsOn(spotlessTask);
// when the task graph is ready, we'll configure the spotlessTask appropriately
project.getGradle().getTaskGraph().whenReady(new Closure(null) {
private static final long serialVersionUID = 1L;

// called by gradle
@SuppressFBWarnings("UMAC_UNCALLABLE_METHOD_OF_ANONYMOUS_CLASS")
public Object doCall(TaskExecutionGraph graph) {
if (graph.hasTask(checkTask)) {
spotlessTask.setCheck();
}
if (graph.hasTask(applyTask)) {
spotlessTask.setApply();
}
return Closure.DONE;
}
});

// set the filePatterns property
project.afterEvaluate(unused -> {
Expand Down
Loading