Skip to content

Commit dd5165f

Browse files
committed
Replace FormatExceptionPolicy with LintPolicy inside the Gradle plugin.
1 parent 0049661 commit dd5165f

File tree

5 files changed

+90
-37
lines changed

5 files changed

+90
-37
lines changed

plugin-gradle/src/main/java/com/diffplug/gradle/spotless/FormatExtension.java

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2016-2021 DiffPlug
2+
* Copyright 2016-2022 DiffPlug
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -39,7 +39,6 @@
3939
import org.gradle.api.file.FileCollection;
4040

4141
import com.diffplug.common.base.Preconditions;
42-
import com.diffplug.spotless.FormatExceptionPolicyStrict;
4342
import com.diffplug.spotless.FormatterFunc;
4443
import com.diffplug.spotless.FormatterStep;
4544
import com.diffplug.spotless.LazyForwardingEquality;
@@ -137,16 +136,20 @@ public void setEncoding(Charset charset) {
137136
encoding = Objects.requireNonNull(charset);
138137
}
139138

140-
final FormatExceptionPolicyStrict exceptionPolicy = new FormatExceptionPolicyStrict();
139+
final LintPolicy lintPolicy = new LintPolicy();
141140

142141
/** Ignores errors in the given step. */
142+
@Deprecated
143143
public void ignoreErrorForStep(String stepName) {
144-
exceptionPolicy.excludeStep(Objects.requireNonNull(stepName));
144+
// TODO: deprecation message
145+
lintPolicy.excludeStep(Objects.requireNonNull(stepName));
145146
}
146147

147148
/** Ignores errors for the given relative path. */
149+
@Deprecated
148150
public void ignoreErrorForPath(String relativePath) {
149-
exceptionPolicy.excludePath(Objects.requireNonNull(relativePath));
151+
// TODO: deprecation message
152+
lintPolicy.excludePath(Objects.requireNonNull(relativePath));
150153
}
151154

152155
/** Sets encoding to use (defaults to {@link SpotlessExtensionImpl#getEncoding()}). */
@@ -745,7 +748,7 @@ public void toggleOffOnDisable() {
745748
/** Sets up a format task according to the values in this extension. */
746749
protected void setupTask(SpotlessTask task) {
747750
task.setEncoding(getEncoding().name());
748-
task.setExceptionPolicy(exceptionPolicy);
751+
task.setLintPolicy(lintPolicy);
749752
FileCollection totalTarget = targetExclude == null ? target : target.minus(targetExclude);
750753
task.setTarget(totalTarget);
751754
List<FormatterStep> steps;
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
* Copyright 2022 DiffPlug
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package com.diffplug.gradle.spotless;
17+
18+
import java.util.Objects;
19+
import java.util.Set;
20+
import java.util.TreeSet;
21+
22+
import com.diffplug.spotless.Lint;
23+
import com.diffplug.spotless.NoLambda;
24+
25+
public class LintPolicy extends NoLambda.EqualityBasedOnSerialization {
26+
private final Set<String> excludeSteps = new TreeSet<>();
27+
private final Set<String> excludePaths = new TreeSet<>();
28+
29+
/** Adds a step name to exclude. */
30+
public void excludeStep(String stepName) {
31+
excludeSteps.add(Objects.requireNonNull(stepName));
32+
}
33+
34+
/** Adds a relative path to exclude. */
35+
public void excludePath(String relativePath) {
36+
excludePaths.add(Objects.requireNonNull(relativePath));
37+
}
38+
39+
public boolean runLintOn(String path) {
40+
return !excludePaths.contains(path);
41+
}
42+
43+
public boolean includeLint(String path, Lint lint) {
44+
return runLintOn(path) && !excludeSteps.contains(lint.getCode());
45+
}
46+
}

plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessCheck.java

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
import org.gradle.api.file.FileVisitDetails;
3030
import org.gradle.api.file.FileVisitor;
3131
import org.gradle.api.provider.Property;
32+
import org.gradle.api.tasks.Input;
3233
import org.gradle.api.tasks.Internal;
3334
import org.gradle.api.tasks.TaskAction;
3435

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

45+
@Input
46+
public abstract Property<LintPolicy> getLintPolicy();
47+
4448
public void performActionTest() throws IOException {
4549
performAction(true);
4650
}
@@ -122,6 +126,7 @@ void init(SpotlessTaskImpl impl) {
122126
super.init(impl);
123127
getProjectPath().set(getProject().getPath());
124128
getEncoding().set(impl.getEncoding());
129+
getLintPolicy().set(impl.getLintPolicy());
125130
}
126131

127132
private String getTaskPathPrefix() {
@@ -134,27 +139,37 @@ private static String calculateGradleCommand() {
134139
}
135140

136141
private void checkForLint() {
142+
LintPolicy lintPolicy = getLintPolicy().get();
137143
File lintDir = applyHasRun() ? lintApplyDir() : lintCheckDir();
138144
ConfigurableFileTree lintFiles = getConfigCacheWorkaround().fileTree().from(lintDir);
139145
List<File> withLint = new ArrayList<>();
146+
StringBuilder errorMsg = new StringBuilder();
140147
lintFiles.visit(fileVisitDetails -> {
141148
if (fileVisitDetails.isDirectory()) {
142149
return;
143150
}
144151
try {
145152
String path = fileVisitDetails.getPath();
146-
File originalSource = new File(getProjectDir().get().getAsFile(), path);
147-
List<Lint> lints = Lint.fromFile(fileVisitDetails.getFile());
148-
for (Lint lint : lints) {
149-
System.err.println(path + ":" + lint.toString());
153+
if (lintPolicy.runLintOn(path)) {
154+
File originalSource = new File(getProjectDir().get().getAsFile(), path);
155+
List<Lint> lints = Lint.fromFile(fileVisitDetails.getFile());
156+
boolean hasLints = false;
157+
for (Lint lint : lints) {
158+
if (lintPolicy.includeLint(path, lint)) {
159+
hasLints = true;
160+
errorMsg.append(path + ":" + lint.toString() + "\n");
161+
}
162+
}
163+
if (hasLints) {
164+
withLint.add(originalSource);
165+
}
150166
}
151-
withLint.add(originalSource);
152167
} catch (IOException e) {
153168
throw new RuntimeException(e);
154169
}
155170
});
156171
if (!withLint.isEmpty()) {
157-
throw new GradleException("The files above cannot be fixed by spotlessApply");
172+
throw new GradleException("The files below cannot be fixed by spotlessApply\n" + errorMsg);
158173
}
159174
}
160175
}

plugin-gradle/src/main/java/com/diffplug/gradle/spotless/SpotlessTask.java

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,6 @@
3737
import org.gradle.work.Incremental;
3838

3939
import com.diffplug.gradle.spotless.JvmLocalCache.LiveCache;
40-
import com.diffplug.spotless.FormatExceptionPolicy;
41-
import com.diffplug.spotless.FormatExceptionPolicyStrict;
4240
import com.diffplug.spotless.Formatter;
4341
import com.diffplug.spotless.FormatterStep;
4442
import com.diffplug.spotless.LineEnding;
@@ -119,15 +117,15 @@ public ObjectId getRatchetSha() {
119117
return subtreeSha;
120118
}
121119

122-
protected FormatExceptionPolicy exceptionPolicy = new FormatExceptionPolicyStrict();
120+
protected LintPolicy lintPolicy = new LintPolicy();
123121

124-
public void setExceptionPolicy(FormatExceptionPolicy exceptionPolicy) {
125-
this.exceptionPolicy = Objects.requireNonNull(exceptionPolicy);
122+
public void setLintPolicy(LintPolicy lintPolicy) {
123+
this.lintPolicy = Objects.requireNonNull(lintPolicy);
126124
}
127125

128126
@Input
129-
public FormatExceptionPolicy getExceptionPolicy() {
130-
return exceptionPolicy;
127+
public LintPolicy getLintPolicy() {
128+
return lintPolicy;
131129
}
132130

133131
protected FileCollection target;
@@ -204,7 +202,6 @@ Formatter buildFormatter() {
204202
.encoding(Charset.forName(encoding))
205203
.rootDir(getProjectDir().get().getAsFile().toPath())
206204
.steps(steps.get())
207-
.exceptionPolicy(exceptionPolicy)
208205
.build();
209206
}
210207
}

plugin-gradle/src/test/java/com/diffplug/gradle/spotless/ErrorShouldRethrowTest.java

Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2016-2021 DiffPlug
2+
* Copyright 2016-2022 DiffPlug
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -66,10 +66,8 @@ void anyExceptionShouldFail() throws Exception {
6666
"} // spotless");
6767
setFile("README.md").toContent("This code is fubar.");
6868
runWithFailure(
69-
"> Task :spotlessMisc FAILED\n" +
70-
"Step 'no swearing' found problem in 'README.md':\n" +
71-
"No swearing!\n" +
72-
"java.lang.RuntimeException: No swearing!");
69+
"> The files below cannot be fixed by spotlessApply\n" +
70+
" README.md:1: (no swearing) java.lang.RuntimeException: No swearing!");
7371
}
7472

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

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

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

121115
private void runWithSuccess(String expectedToStartWith) throws Exception {
@@ -124,21 +118,19 @@ private void runWithSuccess(String expectedToStartWith) throws Exception {
124118
}
125119

126120
private void runWithFailure(String expectedToStartWith) throws Exception {
127-
BuildResult result = gradleRunner().withArguments("check").buildAndFail();
121+
BuildResult result = gradleRunner().forwardOutput().withArguments("check").buildAndFail();
128122
assertResultAndMessages(result, TaskOutcome.FAILED, expectedToStartWith);
129123
}
130124

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

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

0 commit comments

Comments
 (0)