Skip to content

Commit

Permalink
Replace FormatExceptionPolicy with LintPolicy inside the Gradle p…
Browse files Browse the repository at this point in the history
…lugin.
  • Loading branch information
nedtwigg committed Jan 14, 2022
1 parent 0049661 commit dd5165f
Show file tree
Hide file tree
Showing 5 changed files with 90 additions and 37 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2016-2021 DiffPlug
* Copyright 2016-2022 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 @@ -39,7 +39,6 @@
import org.gradle.api.file.FileCollection;

import com.diffplug.common.base.Preconditions;
import com.diffplug.spotless.FormatExceptionPolicyStrict;
import com.diffplug.spotless.FormatterFunc;
import com.diffplug.spotless.FormatterStep;
import com.diffplug.spotless.LazyForwardingEquality;
Expand Down Expand Up @@ -137,16 +136,20 @@ public void setEncoding(Charset charset) {
encoding = Objects.requireNonNull(charset);
}

final FormatExceptionPolicyStrict exceptionPolicy = new FormatExceptionPolicyStrict();
final LintPolicy lintPolicy = new LintPolicy();

/** Ignores errors in the given step. */
@Deprecated
public void ignoreErrorForStep(String stepName) {
exceptionPolicy.excludeStep(Objects.requireNonNull(stepName));
// TODO: deprecation message
lintPolicy.excludeStep(Objects.requireNonNull(stepName));
}

/** Ignores errors for the given relative path. */
@Deprecated
public void ignoreErrorForPath(String relativePath) {
exceptionPolicy.excludePath(Objects.requireNonNull(relativePath));
// TODO: deprecation message
lintPolicy.excludePath(Objects.requireNonNull(relativePath));
}

/** Sets encoding to use (defaults to {@link SpotlessExtensionImpl#getEncoding()}). */
Expand Down Expand Up @@ -745,7 +748,7 @@ public void toggleOffOnDisable() {
/** Sets up a format task according to the values in this extension. */
protected void setupTask(SpotlessTask task) {
task.setEncoding(getEncoding().name());
task.setExceptionPolicy(exceptionPolicy);
task.setLintPolicy(lintPolicy);
FileCollection totalTarget = targetExclude == null ? target : target.minus(targetExclude);
task.setTarget(totalTarget);
List<FormatterStep> steps;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* Copyright 2022 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.util.Objects;
import java.util.Set;
import java.util.TreeSet;

import com.diffplug.spotless.Lint;
import com.diffplug.spotless.NoLambda;

public class LintPolicy extends NoLambda.EqualityBasedOnSerialization {
private final Set<String> excludeSteps = new TreeSet<>();
private final Set<String> excludePaths = new TreeSet<>();

/** Adds a step name to exclude. */
public void excludeStep(String stepName) {
excludeSteps.add(Objects.requireNonNull(stepName));
}

/** Adds a relative path to exclude. */
public void excludePath(String relativePath) {
excludePaths.add(Objects.requireNonNull(relativePath));
}

public boolean runLintOn(String path) {
return !excludePaths.contains(path);
}

public boolean includeLint(String path, Lint lint) {
return runLintOn(path) && !excludeSteps.contains(lint.getCode());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import org.gradle.api.file.FileVisitDetails;
import org.gradle.api.file.FileVisitor;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.TaskAction;

Expand All @@ -41,6 +42,9 @@ public abstract class SpotlessCheck extends SpotlessTaskService.ClientTask {
@Internal
public abstract Property<String> getEncoding();

@Input
public abstract Property<LintPolicy> getLintPolicy();

public void performActionTest() throws IOException {
performAction(true);
}
Expand Down Expand Up @@ -122,6 +126,7 @@ void init(SpotlessTaskImpl impl) {
super.init(impl);
getProjectPath().set(getProject().getPath());
getEncoding().set(impl.getEncoding());
getLintPolicy().set(impl.getLintPolicy());
}

private String getTaskPathPrefix() {
Expand All @@ -134,27 +139,37 @@ private static String calculateGradleCommand() {
}

private void checkForLint() {
LintPolicy lintPolicy = getLintPolicy().get();
File lintDir = applyHasRun() ? lintApplyDir() : lintCheckDir();
ConfigurableFileTree lintFiles = getConfigCacheWorkaround().fileTree().from(lintDir);
List<File> withLint = new ArrayList<>();
StringBuilder errorMsg = new StringBuilder();
lintFiles.visit(fileVisitDetails -> {
if (fileVisitDetails.isDirectory()) {
return;
}
try {
String path = fileVisitDetails.getPath();
File originalSource = new File(getProjectDir().get().getAsFile(), path);
List<Lint> lints = Lint.fromFile(fileVisitDetails.getFile());
for (Lint lint : lints) {
System.err.println(path + ":" + lint.toString());
if (lintPolicy.runLintOn(path)) {
File originalSource = new File(getProjectDir().get().getAsFile(), path);
List<Lint> lints = Lint.fromFile(fileVisitDetails.getFile());
boolean hasLints = false;
for (Lint lint : lints) {
if (lintPolicy.includeLint(path, lint)) {
hasLints = true;
errorMsg.append(path + ":" + lint.toString() + "\n");
}
}
if (hasLints) {
withLint.add(originalSource);
}
}
withLint.add(originalSource);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
if (!withLint.isEmpty()) {
throw new GradleException("The files above cannot be fixed by spotlessApply");
throw new GradleException("The files below cannot be fixed by spotlessApply\n" + errorMsg);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,6 @@
import org.gradle.work.Incremental;

import com.diffplug.gradle.spotless.JvmLocalCache.LiveCache;
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;
Expand Down Expand Up @@ -119,15 +117,15 @@ public ObjectId getRatchetSha() {
return subtreeSha;
}

protected FormatExceptionPolicy exceptionPolicy = new FormatExceptionPolicyStrict();
protected LintPolicy lintPolicy = new LintPolicy();

public void setExceptionPolicy(FormatExceptionPolicy exceptionPolicy) {
this.exceptionPolicy = Objects.requireNonNull(exceptionPolicy);
public void setLintPolicy(LintPolicy lintPolicy) {
this.lintPolicy = Objects.requireNonNull(lintPolicy);
}

@Input
public FormatExceptionPolicy getExceptionPolicy() {
return exceptionPolicy;
public LintPolicy getLintPolicy() {
return lintPolicy;
}

protected FileCollection target;
Expand Down Expand Up @@ -204,7 +202,6 @@ Formatter buildFormatter() {
.encoding(Charset.forName(encoding))
.rootDir(getProjectDir().get().getAsFile().toPath())
.steps(steps.get())
.exceptionPolicy(exceptionPolicy)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2016-2021 DiffPlug
* Copyright 2016-2022 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 @@ -66,10 +66,8 @@ void anyExceptionShouldFail() throws Exception {
"} // spotless");
setFile("README.md").toContent("This code is fubar.");
runWithFailure(
"> Task :spotlessMisc FAILED\n" +
"Step 'no swearing' found problem in 'README.md':\n" +
"No swearing!\n" +
"java.lang.RuntimeException: No swearing!");
"> The files below cannot be fixed by spotlessApply\n" +
" README.md:1: (no swearing) java.lang.RuntimeException: No swearing!");
}

@Test
Expand All @@ -89,8 +87,7 @@ void unlessExemptedByStep() throws Exception {
" } // format",
"} // spotless");
setFile("README.md").toContent("This code is fubar.");
runWithSuccess("> Task :spotlessMisc\n" +
"Unable to apply step 'no swearing' to 'README.md'");
runWithSuccess("> Task :spotlessMisc");
}

@Test
Expand All @@ -100,8 +97,7 @@ void unlessExemptedByPath() throws Exception {
" } // format",
"} // spotless");
setFile("README.md").toContent("This code is fubar.");
runWithSuccess("> Task :spotlessMisc\n" +
"Unable to apply step 'no swearing' to 'README.md'");
runWithSuccess("> Task :spotlessMisc");
}

@Test
Expand All @@ -112,10 +108,8 @@ void failsIfNeitherStepNorFileExempted() throws Exception {
" } // format",
"} // spotless");
setFile("README.md").toContent("This code is fubar.");
runWithFailure("> Task :spotlessMisc FAILED\n" +
"Step 'no swearing' found problem in 'README.md':\n" +
"No swearing!\n" +
"java.lang.RuntimeException: No swearing!");
runWithFailure("> The files below cannot be fixed by spotlessApply\n" +
" README.md:1: (no swearing) java.lang.RuntimeException: No swearing!");
}

private void runWithSuccess(String expectedToStartWith) throws Exception {
Expand All @@ -124,21 +118,19 @@ private void runWithSuccess(String expectedToStartWith) throws Exception {
}

private void runWithFailure(String expectedToStartWith) throws Exception {
BuildResult result = gradleRunner().withArguments("check").buildAndFail();
BuildResult result = gradleRunner().forwardOutput().withArguments("check").buildAndFail();
assertResultAndMessages(result, TaskOutcome.FAILED, expectedToStartWith);
}

private void assertResultAndMessages(BuildResult result, TaskOutcome outcome, String expectedToStartWith) {
String output = result.getOutput();
int register = output.indexOf(":spotlessInternalRegisterDependencies");
int register = output.indexOf("Execution failed for task ':spotlessMiscCheck'.");
int firstNewlineAfterThat = output.indexOf('\n', register + 1);
String useThisToMatch = output.substring(firstNewlineAfterThat);

int numNewlines = CharMatcher.is('\n').countIn(expectedToStartWith);
List<String> actualLines = Splitter.on('\n').splitToList(LineEnding.toUnix(useThisToMatch.trim()));
String actualStart = String.join("\n", actualLines.subList(0, numNewlines + 1));
Assertions.assertThat(actualStart).isEqualTo(expectedToStartWith);
Assertions.assertThat(outcomes(result, outcome).size() + outcomes(result, TaskOutcome.UP_TO_DATE).size() + outcomes(result, TaskOutcome.NO_SOURCE).size())
.isEqualTo(outcomes(result).size());
}
}

0 comments on commit dd5165f

Please sign in to comment.