diff --git a/lib/src/main/java/com/diffplug/spotless/PaddedCellBulk.java b/lib/src/main/java/com/diffplug/spotless/PaddedCellBulk.java index 1d37ea72dc..6f9a06069a 100644 --- a/lib/src/main/java/com/diffplug/spotless/PaddedCellBulk.java +++ b/lib/src/main/java/com/diffplug/spotless/PaddedCellBulk.java @@ -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"); @@ -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 @@ -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; } } diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/PaddedCellGradle.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/PaddedCellGradle.java index 6c69487054..2bb373489c 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/PaddedCellGradle.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/PaddedCellGradle.java @@ -16,7 +16,6 @@ package com.diffplug.gradle.spotless; import java.io.File; -import java.io.IOException; import java.nio.file.Path; import java.util.List; @@ -24,9 +23,6 @@ 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(). @@ -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 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 stillFailing = PaddedCellBulk.check(rootDir, diagnoseDir, formatter, problemFiles); - if (!stillFailing.isEmpty()) { - throw task.formatViolationsFor(formatter, problemFiles); - } - } } 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 new file mode 100644 index 0000000000..73a4c645b7 --- /dev/null +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessApply.java @@ -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); + } + } + }); + } + } +} diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessCheck.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessCheck.java new file mode 100644 index 0000000000..f814af8569 --- /dev/null +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessCheck.java @@ -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()); + */ + } + } +} diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtension.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtension.java index 4503317d97..ac61795461 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtension.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessExtension.java @@ -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; @@ -234,7 +230,7 @@ private T maybeCreate(String name, Class clazz) { Constructor 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); @@ -244,8 +240,14 @@ private T maybeCreate(String name, Class 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); @@ -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 -> { diff --git a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTask.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTask.java index 1cca30ec5e..2f50c12a06 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTask.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTask.java @@ -16,10 +16,9 @@ package com.diffplug.gradle.spotless; import java.io.File; -import java.io.Serializable; +import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; -import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -34,19 +33,16 @@ import org.gradle.api.GradleException; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.InputFiles; -import org.gradle.api.tasks.Internal; -import org.gradle.api.tasks.OutputFiles; +import org.gradle.api.tasks.OutputDirectory; import org.gradle.api.tasks.TaskAction; import org.gradle.api.tasks.incremental.IncrementalTaskInputs; -import com.diffplug.common.collect.ImmutableList; -import com.diffplug.common.collect.Iterables; +import com.diffplug.common.base.Errors; import com.diffplug.spotless.FormatExceptionPolicy; import com.diffplug.spotless.FormatExceptionPolicyStrict; import com.diffplug.spotless.Formatter; import com.diffplug.spotless.FormatterStep; import com.diffplug.spotless.LineEnding; -import com.diffplug.spotless.PaddedCell; import com.diffplug.spotless.PaddedCellBulk; import com.diffplug.spotless.extra.integration.DiffMessageFormatter; @@ -110,7 +106,7 @@ public FormatExceptionPolicy getExceptionPolicy() { protected Iterable target; - @Internal + @InputFiles public Iterable getTarget() { return target; } @@ -119,27 +115,11 @@ public void setTarget(Iterable target) { this.target = Objects.requireNonNull(target); } - /** Internal use only. */ - @InputFiles - @Deprecated - public Iterable getInternalTargetInput() { - return getInternalTarget(); - } - - /** Internal use only. */ - @OutputFiles - @Deprecated - public Iterable getInternalTargetOutput() { - return getInternalTarget(); - } - - private Iterable getInternalTarget() { - // used to combine the special cache file and the real target - return Iterables.concat(ImmutableList.of(getCacheFile()), target); - } + private File outputDirectory = new File(getProject().getBuildDir(), "spotless/" + getName()); - private File getCacheFile() { - return new File(getProject().getBuildDir(), getName()); + @OutputDirectory + public File getOutputDirectory() { + return outputDirectory; } protected List steps = new ArrayList<>(); @@ -157,17 +137,6 @@ public boolean addStep(FormatterStep step) { return this.steps.add(Objects.requireNonNull(step)); } - private boolean check = false; - private boolean apply = false; - - public void setCheck() { - this.check = true; - } - - public void setApply() { - this.apply = true; - } - /** Returns the name of this format. */ String formatName() { String name = getName(); @@ -183,8 +152,10 @@ public void performAction(IncrementalTaskInputs inputs) throws Exception { if (target == null) { throw new GradleException("You must specify 'Iterable target'"); } - if (!check && !apply) { - throw new GradleException("Don't call " + getName() + " directly, call " + getName() + SpotlessExtension.CHECK + " or " + getName() + SpotlessExtension.APPLY); + + if (!inputs.isIncremental()) { + getLogger().info("Not incremental: removing prior outputs"); + getProject().delete(outputDirectory); } Predicate shouldInclude; @@ -201,133 +172,69 @@ public void performAction(IncrementalTaskInputs inputs) throws Exception { .anyMatch(filePattern -> filePattern.matcher(file.getAbsolutePath()) .matches()); } - // find the outOfDate files - List outOfDate = new ArrayList<>(); - inputs.outOfDate(inputDetails -> { - File file = inputDetails.getFile(); - if (shouldInclude.test(file) && file.isFile() && !file.equals(getCacheFile())) { - outOfDate.add(file); + + inputs.removed(removedDetails -> { + File input = removedDetails.getFile(); + if (shouldInclude.test(input)) { + try { + deletePreviousResult(input); + } catch (IOException e) { + throw Errors.asRuntime(e); + } } }); - // load the files that were changed by the last run - // because it's possible the user changed them back to their - // unformatted form, so we need to treat them as dirty - // (see bug #144) - if (getCacheFile().exists()) { - LastApply lastApply = SerializableMisc.fromFile(LastApply.class, getCacheFile()); - for (File file : lastApply.changedFiles) { - if (shouldInclude.test(file) && !outOfDate.contains(file) && file.exists() && Iterables.contains(target, file)) { - outOfDate.add(file); + // accumulate the outOfDate files + try (Formatter formatter = buildFormatter()) { + inputs.outOfDate(inputDetails -> { + File input = inputDetails.getFile(); + if (shouldInclude.test(input) && input.isFile()) { + try { + getLogger().debug("Applying format to " + input); + byte[] canonical = PaddedCellBulk.getCanonicalOrNullIfClean(formatter, input); + if (canonical == null) { + deletePreviousResult(input); + } else { + writeResult(input, canonical); + } + } catch (IOException e) { + throw Errors.asRuntime(e); + } } - } + }); } + } - if (outOfDate.isEmpty()) { - // no work to do - return; - } + private void writeResult(File input, byte[] result) throws IOException { + File output = getOutputFile(input); + Files.createDirectories(output.getParentFile().toPath()); + Files.write(output.toPath(), result); + } - // create the formatter - try (Formatter formatter = Formatter.builder() + private void deletePreviousResult(File input) throws IOException { + File output = getOutputFile(input); + Files.deleteIfExists(output.toPath()); + } + + private Formatter buildFormatter() { + return Formatter.builder() .lineEndingsPolicy(lineEndingsPolicy) .encoding(Charset.forName(encoding)) .rootDir(getProject().getRootDir().toPath()) .steps(steps) .exceptionPolicy(exceptionPolicy) - .build()) { - - if (apply) { - List changedFiles = applyAnyChanged(formatter, outOfDate); - if (!changedFiles.isEmpty()) { - // If any file changed, we need to mark the task as dirty - // next time to avoid bug #144. - LastApply lastApply = new LastApply(); - lastApply.timestamp = System.currentTimeMillis(); - lastApply.changedFiles = changedFiles; - - SerializableMisc.toFile(lastApply, getCacheFile()); - } - } - if (check) { - check(formatter, outOfDate); - } - } - } - - static class LastApply implements Serializable { - private static final long serialVersionUID = 6245070824310295090L; - - long timestamp; - List changedFiles; - } - - private List applyAnyChanged(Formatter formatter, List outOfDate) throws Exception { - List changed = new ArrayList<>(outOfDate.size()); - if (isPaddedCell()) { - for (File file : outOfDate) { - getLogger().debug("Applying format to " + file); - if (PaddedCellBulk.applyAnyChanged(formatter, file)) { - changed.add(file); - } - } - } else { - boolean anyMisbehave = false; - for (File file : outOfDate) { - getLogger().debug("Applying format to " + file); - String unixResultIfDirty = formatter.applyToAndReturnResultIfDirty(file); - if (unixResultIfDirty != null) { - changed.add(file); - } - // because apply will count as up-to-date, it's important - // that every call to apply will get a PaddedCell check - if (!anyMisbehave && unixResultIfDirty != null) { - String onceMore = formatter.compute(unixResultIfDirty, file); - // f(f(input) == f(input) for an idempotent function - if (!onceMore.equals(unixResultIfDirty)) { - // it's not idempotent. but, if it converges, then it's likely a glitch that won't reoccur, - // so there's no need to make a bunch of noise for the user - PaddedCell result = PaddedCell.check(formatter, file, onceMore); - if (result.type() == PaddedCell.Type.CONVERGE) { - String finalResult = formatter.computeLineEndings(result.canonical(), file); - Files.write(file.toPath(), finalResult.getBytes(formatter.getEncoding()), StandardOpenOption.TRUNCATE_EXISTING); - } else { - // it didn't converge, so the user is going to need padded cell mode - anyMisbehave = true; - } - } - } - } - if (anyMisbehave) { - throw PaddedCellGradle.youShouldTurnOnPaddedCell(this); - } - } - return changed; + .build(); } - private void check(Formatter formatter, List outOfDate) throws Exception { - List problemFiles = new ArrayList<>(); - for (File file : outOfDate) { - getLogger().debug("Checking format on " + file); - if (!formatter.isClean(file)) { - problemFiles.add(file); - } - } - if (paddedCell) { - PaddedCellGradle.check(this, formatter, problemFiles); - } else { - if (!problemFiles.isEmpty()) { - // if we're not in paddedCell mode, we'll check if maybe we should be - if (PaddedCellBulk.anyMisbehave(formatter, problemFiles)) { - throw PaddedCellGradle.youShouldTurnOnPaddedCell(this); - } else { - throw formatViolationsFor(formatter, problemFiles); - } - } + private File getOutputFile(File input) { + String outputFileName = FormatExtension.relativize(getProject().getProjectDir(), input); + if (outputFileName == null) { + outputFileName = input.getAbsolutePath(); } + return new File(outputDirectory, outputFileName); } /** Returns an exception which indicates problem files nicely. */ - GradleException formatViolationsFor(Formatter formatter, List problemFiles) { + GradleException formatViolationsFor(List problemFiles, Formatter formatter) { return new GradleException(DiffMessageFormatter.builder() .runToFix("Run 'gradlew spotlessApply' to fix these violations.") .isPaddedCell(paddedCell)