From 9991e30663527c8634ed811825f384085fb2e570 Mon Sep 17 00:00:00 2001 From: Daz DeBoer Date: Wed, 29 Apr 2020 16:37:21 -0600 Subject: [PATCH 1/5] Simple spike at separating the core `SpotlessTask` from check and apply - SpotlessTask runs the formatter for each source file, and generates an output file with the formatted results (if different) - If the task is not incremental, all prior outputs are removed - For each added file, the formatter is run, and the output is written if different from the original - For each removed file, the previous output is removed, if present - SpotlessCheck will fail if there are any outputs from SpotlessTask - SpotlessApply will copy any formatted outputs back over the original source This mechanism has a number of benefits and makes things a lot simpler: - The spotless cache is not required - SpotlessTask is now a simple incremental task and benefits from the usual up-to-date checking. It should also support being made cacheable. Note that a number of things were ignored for this spike: - Anything to do with `PaddedCell` - Check does not print out the actual formatting issues - I didn't run any of the tests --- .../java/com/diffplug/spotless/Formatter.java | 27 +++ .../gradle/spotless/SpotlessApply.java | 70 ++++++ .../gradle/spotless/SpotlessCheck.java | 49 +++++ .../gradle/spotless/SpotlessExtension.java | 35 ++- .../gradle/spotless/SpotlessTask.java | 207 +++++------------- 5 files changed, 216 insertions(+), 172 deletions(-) create mode 100644 plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessApply.java create mode 100644 plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessCheck.java diff --git a/lib/src/main/java/com/diffplug/spotless/Formatter.java b/lib/src/main/java/com/diffplug/spotless/Formatter.java index 038e77fa64..937553bd90 100644 --- a/lib/src/main/java/com/diffplug/spotless/Formatter.java +++ b/lib/src/main/java/com/diffplug/spotless/Formatter.java @@ -203,6 +203,33 @@ public void applyTo(File file) throws IOException { } } + /** + * Applies formatting to the given file, writing to the output file if the result is different. + * If the result of formatting is the same as the input, the output file is deleted. + */ + public void applyToAndWriteResultIfDirty(File input, File output) throws IOException { + Objects.requireNonNull(input); + Objects.requireNonNull(output); + + byte[] rawBytes = Files.readAllBytes(input.toPath()); + String raw = new String(rawBytes, encoding); + String rawUnix = LineEnding.toUnix(raw); + + // enforce the format + String formattedUnix = compute(rawUnix, input); + // enforce the line endings + String formatted = computeLineEndings(formattedUnix, input); + + // write out the file iff it has changed + byte[] formattedBytes = formatted.getBytes(encoding); + if (!Arrays.equals(rawBytes, formattedBytes)) { + Files.createDirectories(output.getParentFile().toPath()); + Files.write(output.toPath(), formattedBytes); + } else { + Files.deleteIfExists(output.toPath()); + } + } + /** Applies the appropriate line endings to the given unix content. */ public String computeLineEndings(String unix, File file) { Objects.requireNonNull(unix, "unix"); 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..7f3c341804 --- /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 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; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; + +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..655b9baab1 --- /dev/null +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessCheck.java @@ -0,0 +1,49 @@ +/* + * 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 com.diffplug.common.collect.Lists; +import org.gradle.api.DefaultTask; +import org.gradle.api.file.ConfigurableFileTree; +import org.gradle.api.tasks.InputDirectory; +import org.gradle.api.tasks.SkipWhenEmpty; +import org.gradle.api.tasks.TaskAction; + +import java.io.File; + +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 formatTask.formatViolationsFor(Lists.newArrayList(files.getFiles())); + } + } +} 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..1d2787aaa9 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 @@ -234,7 +234,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 +244,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 +262,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..6913053b4a 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,20 +33,15 @@ 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.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; public class SpotlessTask extends DefaultTask { @@ -110,7 +104,7 @@ public FormatExceptionPolicy getExceptionPolicy() { protected Iterable target; - @Internal + @InputFiles public Iterable getTarget() { return target; } @@ -119,27 +113,10 @@ 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 getCacheFile() { - return new File(getProject().getBuildDir(), getName()); + private File outputDirectory = new File(getProject().getBuildDir(), "spotless/" + getName()); + @OutputDirectory + public File getOutputDirectory() { + return outputDirectory; } protected List steps = new ArrayList<>(); @@ -157,17 +134,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 +149,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,129 +169,66 @@ 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); - } - }); - // 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); + + // create the formatter + try (Formatter formatter = buildFormatter()) { + inputs.outOfDate(inputDetails -> { + File input = inputDetails.getFile(); + if (shouldInclude.test(input) && input.isFile()) { + formatAndWriteResult(formatter, input); + } + }); + inputs.removed(removedDetails -> { + File input = removedDetails.getFile(); + if (shouldInclude.test(input)) { + deletePreviousResult(input); } - } + }); } + } - if (outOfDate.isEmpty()) { - // no work to do - return; + private void formatAndWriteResult(Formatter formatter, File input) { + File output = getOutputFile(input); + getLogger().info("Applying format to " + input + " and writing to " + output); + try { + formatter.applyToAndWriteResultIfDirty(input, output); + } catch (IOException e) { + throw new GradleException("Failed to apply format for " + input, e); } + } - // create the formatter - try (Formatter formatter = Formatter.builder() + private void deletePreviousResult(File input) { + File output = getOutputFile(input); + getLogger().info("Removing previous result for removed file: " + input); + + try { + Files.deleteIfExists(output.toPath()); + } catch (IOException e) { + throw new GradleException("Failed to remove previous result " + output, e); + } + } + + 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; + .build(); } - 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); - } + private File getOutputFile(File input) { + String outputFileName = FormatExtension.relativize(getProject().getProjectDir(), input); + if (outputFileName == null) { + outputFileName = input.getAbsolutePath(); } - return changed; + return new File(outputDirectory, outputFileName); } - 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); - } - } - } + GradleException formatViolationsFor(List problemFiles) { + Formatter formatter = buildFormatter(); + return formatViolationsFor(formatter, problemFiles); } /** Returns an exception which indicates problem files nicely. */ From 2f40b472f9b67b61a04850bd9a57713c20889b03 Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Thu, 30 Apr 2020 02:19:29 -0700 Subject: [PATCH 2/5] spotless apply ;-) --- .../com/diffplug/gradle/spotless/SpotlessApply.java | 10 +++++----- .../com/diffplug/gradle/spotless/SpotlessCheck.java | 5 +++-- .../diffplug/gradle/spotless/SpotlessExtension.java | 4 ---- .../com/diffplug/gradle/spotless/SpotlessTask.java | 1 + 4 files changed, 9 insertions(+), 11 deletions(-) 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 7f3c341804..73a4c645b7 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 @@ -15,6 +15,11 @@ */ 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; @@ -23,11 +28,6 @@ import org.gradle.api.tasks.SkipWhenEmpty; import org.gradle.api.tasks.TaskAction; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.StandardCopyOption; - public class SpotlessApply extends DefaultTask { private File spotlessOutDirectory; 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 index 655b9baab1..e3c8b39dbf 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessCheck.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessCheck.java @@ -15,14 +15,15 @@ */ package com.diffplug.gradle.spotless; -import com.diffplug.common.collect.Lists; +import java.io.File; + import org.gradle.api.DefaultTask; import org.gradle.api.file.ConfigurableFileTree; import org.gradle.api.tasks.InputDirectory; import org.gradle.api.tasks.SkipWhenEmpty; import org.gradle.api.tasks.TaskAction; -import java.io.File; +import com.diffplug.common.collect.Lists; public class SpotlessCheck extends DefaultTask { public SpotlessTask formatTask; 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 1d2787aaa9..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; 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 6913053b4a..b2e6b99493 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 @@ -114,6 +114,7 @@ public void setTarget(Iterable target) { } private File outputDirectory = new File(getProject().getBuildDir(), "spotless/" + getName()); + @OutputDirectory public File getOutputDirectory() { return outputDirectory; From 811d3144d5f4774e80cf07d61fb09b407609dbe2 Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Thu, 30 Apr 2020 02:33:46 -0700 Subject: [PATCH 3/5] Restore padded cell. --- .../java/com/diffplug/spotless/Formatter.java | 27 ---- .../com/diffplug/spotless/PaddedCellBulk.java | 22 +++- .../gradle/spotless/SpotlessTask.java | 118 ++++++++++++------ 3 files changed, 97 insertions(+), 70 deletions(-) diff --git a/lib/src/main/java/com/diffplug/spotless/Formatter.java b/lib/src/main/java/com/diffplug/spotless/Formatter.java index 937553bd90..038e77fa64 100644 --- a/lib/src/main/java/com/diffplug/spotless/Formatter.java +++ b/lib/src/main/java/com/diffplug/spotless/Formatter.java @@ -203,33 +203,6 @@ public void applyTo(File file) throws IOException { } } - /** - * Applies formatting to the given file, writing to the output file if the result is different. - * If the result of formatting is the same as the input, the output file is deleted. - */ - public void applyToAndWriteResultIfDirty(File input, File output) throws IOException { - Objects.requireNonNull(input); - Objects.requireNonNull(output); - - byte[] rawBytes = Files.readAllBytes(input.toPath()); - String raw = new String(rawBytes, encoding); - String rawUnix = LineEnding.toUnix(raw); - - // enforce the format - String formattedUnix = compute(rawUnix, input); - // enforce the line endings - String formatted = computeLineEndings(formattedUnix, input); - - // write out the file iff it has changed - byte[] formattedBytes = formatted.getBytes(encoding); - if (!Arrays.equals(rawBytes, formattedBytes)) { - Files.createDirectories(output.getParentFile().toPath()); - Files.write(output.toPath(), formattedBytes); - } else { - Files.deleteIfExists(output.toPath()); - } - } - /** Applies the appropriate line endings to the given unix content. */ public String computeLineEndings(String unix, File file) { Objects.requireNonNull(unix, "unix"); diff --git a/lib/src/main/java/com/diffplug/spotless/PaddedCellBulk.java b/lib/src/main/java/com/diffplug/spotless/PaddedCellBulk.java index 1d37ea72dc..7980b047f8 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,15 @@ 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 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 +241,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/SpotlessTask.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTask.java index b2e6b99493..39886afac8 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 @@ -37,11 +37,14 @@ import org.gradle.api.tasks.TaskAction; import org.gradle.api.tasks.incremental.IncrementalTaskInputs; +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; public class SpotlessTask extends DefaultTask { @@ -171,42 +174,84 @@ public void performAction(IncrementalTaskInputs inputs) throws Exception { .matches()); } - // create the formatter + inputs.removed(removedDetails -> { + File input = removedDetails.getFile(); + if (shouldInclude.test(input)) { + try { + deletePreviousResult(input); + } catch (IOException e) { + throw Errors.asRuntime(e); + } + } + }); + // accumulate the outOfDate files + List outOfDate = new ArrayList<>(); + inputs.outOfDate(inputDetails -> { + File input = inputDetails.getFile(); + if (shouldInclude.test(input) && input.isFile()) { + outOfDate.add(input); + } + }); try (Formatter formatter = buildFormatter()) { - inputs.outOfDate(inputDetails -> { - File input = inputDetails.getFile(); - if (shouldInclude.test(input) && input.isFile()) { - formatAndWriteResult(formatter, input); + if (isPaddedCell()) { + for (File file : outOfDate) { + getLogger().debug("Applying format to " + file); + byte[] canonical = PaddedCellBulk.getCanonicalOrNullIfClean(formatter, file); + if (canonical == null) { + deletePreviousResult(file); + } else { + writeResult(file, canonical); + } } - }); - inputs.removed(removedDetails -> { - File input = removedDetails.getFile(); - if (shouldInclude.test(input)) { - deletePreviousResult(input); + } else { + for (File file : outOfDate) { + getLogger().debug("Applying format to " + file); + String unixResultIfDirty = formatter.applyToAndReturnResultIfDirty(file); + if (unixResultIfDirty == null) { + // Users expect apply to be idempotent, but formatter functions are frequently not. + // If you find that `f(file) = file`, then you already have a guarantee that your formatter + // is idempotent (at least for your input). + deletePreviousResult(file); + } else { + // If `f(file) != file`, that means your file is definitely dirty, but you don't know + // anything yet about whether the formatter is idempotent or not. + String onceMore = formatter.compute(unixResultIfDirty, file); + if (onceMore.equals(unixResultIfDirty)) { + // f(f(input) == f(input), so it's idempotent, and this is plain-old dirty file + writeResult(file, formatter.computeLineEndings(unixResultIfDirty, file).getBytes(formatter.getEncoding())); + } else { + // 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. We only need to make noise for + // cycles and divergence. + PaddedCell result = PaddedCell.check(formatter, file, onceMore); + if (result.type() == PaddedCell.Type.CONVERGE) { + byte[] canonical = formatter.computeLineEndings(result.canonical(), file).getBytes(formatter.getEncoding()); + byte[] current = Files.readAllBytes(file.toPath()); + if (Arrays.equals(canonical, current)) { + deletePreviousResult(file); + } else { + writeResult(file, canonical); + } + } else { + // it didn't converge, so the user is going to need padded cell mode + throw PaddedCellGradle.youShouldTurnOnPaddedCell(this); + } + } + } } - }); + } } } - private void formatAndWriteResult(Formatter formatter, File input) { + private void writeResult(File input, byte[] result) throws IOException { File output = getOutputFile(input); - getLogger().info("Applying format to " + input + " and writing to " + output); - try { - formatter.applyToAndWriteResultIfDirty(input, output); - } catch (IOException e) { - throw new GradleException("Failed to apply format for " + input, e); - } + Files.createDirectories(output.getParentFile().toPath()); + Files.write(output.toPath(), result); } - private void deletePreviousResult(File input) { + private void deletePreviousResult(File input) throws IOException { File output = getOutputFile(input); - getLogger().info("Removing previous result for removed file: " + input); - - try { - Files.deleteIfExists(output.toPath()); - } catch (IOException e) { - throw new GradleException("Failed to remove previous result " + output, e); - } + Files.deleteIfExists(output.toPath()); } private Formatter buildFormatter() { @@ -227,18 +272,15 @@ private File getOutputFile(File input) { return new File(outputDirectory, outputFileName); } - GradleException formatViolationsFor(List problemFiles) { - Formatter formatter = buildFormatter(); - return formatViolationsFor(formatter, problemFiles); - } - /** Returns an exception which indicates problem files nicely. */ - GradleException formatViolationsFor(Formatter formatter, List problemFiles) { - return new GradleException(DiffMessageFormatter.builder() - .runToFix("Run 'gradlew spotlessApply' to fix these violations.") - .isPaddedCell(paddedCell) - .formatter(formatter) - .problemFiles(problemFiles) - .getMessage()); + GradleException formatViolationsFor(List problemFiles) { + try (Formatter formatter = buildFormatter()) { + return new GradleException(DiffMessageFormatter.builder() + .runToFix("Run 'gradlew spotlessApply' to fix these violations.") + .isPaddedCell(paddedCell) + .formatter(formatter) + .problemFiles(problemFiles) + .getMessage()); + } } } From db355d57c09dac70d05e1e9acd88e6f66444edae Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Thu, 30 Apr 2020 03:23:24 -0700 Subject: [PATCH 4/5] It's a lot simpler to just leave padded-cell on all the time, and it's no slower on clean files. --- .../gradle/spotless/PaddedCellGradle.java | 22 ------ .../gradle/spotless/SpotlessCheck.java | 16 +++- .../gradle/spotless/SpotlessTask.java | 79 +++++-------------- 3 files changed, 32 insertions(+), 85 deletions(-) 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/SpotlessCheck.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessCheck.java index e3c8b39dbf..f814af8569 100644 --- a/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessCheck.java +++ b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessCheck.java @@ -18,13 +18,12 @@ 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; -import com.diffplug.common.collect.Lists; - public class SpotlessCheck extends DefaultTask { public SpotlessTask formatTask; @@ -44,7 +43,18 @@ public void setSpotlessOutDirectory(File spotlessOutDirectory) { public void performAction() throws Exception { ConfigurableFileTree files = getProject().fileTree(spotlessOutDirectory); if (!files.isEmpty()) { - throw formatTask.formatViolationsFor(Lists.newArrayList(files.getFiles())); + 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/SpotlessTask.java b/plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTask.java index 39886afac8..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 @@ -43,7 +43,6 @@ 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; @@ -185,61 +184,23 @@ public void performAction(IncrementalTaskInputs inputs) throws Exception { } }); // accumulate the outOfDate files - List outOfDate = new ArrayList<>(); - inputs.outOfDate(inputDetails -> { - File input = inputDetails.getFile(); - if (shouldInclude.test(input) && input.isFile()) { - outOfDate.add(input); - } - }); try (Formatter formatter = buildFormatter()) { - if (isPaddedCell()) { - for (File file : outOfDate) { - getLogger().debug("Applying format to " + file); - byte[] canonical = PaddedCellBulk.getCanonicalOrNullIfClean(formatter, file); - if (canonical == null) { - deletePreviousResult(file); - } else { - writeResult(file, canonical); - } - } - } else { - for (File file : outOfDate) { - getLogger().debug("Applying format to " + file); - String unixResultIfDirty = formatter.applyToAndReturnResultIfDirty(file); - if (unixResultIfDirty == null) { - // Users expect apply to be idempotent, but formatter functions are frequently not. - // If you find that `f(file) = file`, then you already have a guarantee that your formatter - // is idempotent (at least for your input). - deletePreviousResult(file); - } else { - // If `f(file) != file`, that means your file is definitely dirty, but you don't know - // anything yet about whether the formatter is idempotent or not. - String onceMore = formatter.compute(unixResultIfDirty, file); - if (onceMore.equals(unixResultIfDirty)) { - // f(f(input) == f(input), so it's idempotent, and this is plain-old dirty file - writeResult(file, formatter.computeLineEndings(unixResultIfDirty, file).getBytes(formatter.getEncoding())); + 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 { - // 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. We only need to make noise for - // cycles and divergence. - PaddedCell result = PaddedCell.check(formatter, file, onceMore); - if (result.type() == PaddedCell.Type.CONVERGE) { - byte[] canonical = formatter.computeLineEndings(result.canonical(), file).getBytes(formatter.getEncoding()); - byte[] current = Files.readAllBytes(file.toPath()); - if (Arrays.equals(canonical, current)) { - deletePreviousResult(file); - } else { - writeResult(file, canonical); - } - } else { - // it didn't converge, so the user is going to need padded cell mode - throw PaddedCellGradle.youShouldTurnOnPaddedCell(this); - } + writeResult(input, canonical); } + } catch (IOException e) { + throw Errors.asRuntime(e); } } - } + }); } } @@ -273,14 +234,12 @@ private File getOutputFile(File input) { } /** Returns an exception which indicates problem files nicely. */ - GradleException formatViolationsFor(List problemFiles) { - try (Formatter formatter = buildFormatter()) { - return new GradleException(DiffMessageFormatter.builder() - .runToFix("Run 'gradlew spotlessApply' to fix these violations.") - .isPaddedCell(paddedCell) - .formatter(formatter) - .problemFiles(problemFiles) - .getMessage()); - } + GradleException formatViolationsFor(List problemFiles, Formatter formatter) { + return new GradleException(DiffMessageFormatter.builder() + .runToFix("Run 'gradlew spotlessApply' to fix these violations.") + .isPaddedCell(paddedCell) + .formatter(formatter) + .problemFiles(problemFiles) + .getMessage()); } } From 048bbb99cfba59e6747a24ec997ba3cf8f509402 Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Thu, 30 Apr 2020 03:27:07 -0700 Subject: [PATCH 5/5] And with this little tweak, it's now the same speed as the old fancy logic was. --- lib/src/main/java/com/diffplug/spotless/PaddedCellBulk.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/lib/src/main/java/com/diffplug/spotless/PaddedCellBulk.java b/lib/src/main/java/com/diffplug/spotless/PaddedCellBulk.java index 7980b047f8..6f9a06069a 100644 --- a/lib/src/main/java/com/diffplug/spotless/PaddedCellBulk.java +++ b/lib/src/main/java/com/diffplug/spotless/PaddedCellBulk.java @@ -228,6 +228,12 @@ public static byte[] getCanonicalOrNullIfClean(Formatter formatter, File file) t } // 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