Skip to content

Commit 03493f4

Browse files
committed
Replace FormatExceptionPolicyStrict with List<LintSuppresion>
1 parent 955ed77 commit 03493f4

File tree

11 files changed

+319
-159
lines changed

11 files changed

+319
-159
lines changed

lib/src/main/java/com/diffplug/spotless/FormatExceptionPolicyStrict.java

Lines changed: 0 additions & 57 deletions
This file was deleted.

lib/src/main/java/com/diffplug/spotless/Lint.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,4 +189,28 @@ private static String msgFrom(String message) {
189189
}
190190

191191
public static final int LINE_UNDEFINED = -1;
192+
193+
public void addWarningMessageTo(StringBuilder buffer, String stepName, boolean oneLine) {
194+
if (lineStart == Lint.LINE_UNDEFINED) {
195+
buffer.append("LINE_UNDEFINED");
196+
} else {
197+
buffer.append("L");
198+
buffer.append(lineStart);
199+
if (lineEnd != lineStart) {
200+
buffer.append("-").append(lineEnd);
201+
}
202+
}
203+
buffer.append(" ");
204+
buffer.append(stepName).append("(").append(ruleId).append(") ");
205+
206+
int firstNewline = detail.indexOf('\n');
207+
if (firstNewline == -1) {
208+
buffer.append(detail);
209+
} else if (oneLine) {
210+
buffer.append(detail, 0, firstNewline);
211+
buffer.append(" (...)");
212+
} else {
213+
buffer.append(detail);
214+
}
215+
}
192216
}

lib/src/main/java/com/diffplug/spotless/LintPolicy.java

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -21,23 +21,15 @@
2121
import org.slf4j.LoggerFactory;
2222

2323
class LintPolicy {
24-
private static final Logger logger = LoggerFactory.getLogger(Formatter.class);
25-
26-
static void error(Throwable e, FormatterStep step, String relativePath) {
27-
logger.error("Step '{}' found problem in '{}':\n{}", step.getName(), relativePath, e.getMessage(), e);
28-
}
29-
30-
static void warning(Throwable e, FormatterStep step, String relativePath) {
31-
logger.warn("Unable to apply step '{}' to '{}'", step.getName(), relativePath, e);
32-
}
33-
3424
static void legacyBehavior(Formatter formatter, File file, ValuePerStep<Throwable> exceptionPerStep) {
3525
for (int i = 0; i < formatter.getSteps().size(); ++i) {
3626
Throwable exception = exceptionPerStep.get(i);
3727
if (exception != null && exception != LintState.formatStepCausedNoChange()) {
38-
LintPolicy.error(exception, formatter.getSteps().get(i), file.getName());
28+
logger.error("Step '{}' found problem in '{}':\n{}", formatter.getSteps().get(i), file.getName(), exception.getMessage(), exception);
3929
throw ThrowingEx.asRuntimeRethrowError(exception);
4030
}
4131
}
4232
}
33+
34+
private static final Logger logger = LoggerFactory.getLogger(Formatter.class);
4335
}

lib/src/main/java/com/diffplug/spotless/LintState.java

Lines changed: 31 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@
1818
import java.io.File;
1919
import java.io.IOException;
2020
import java.nio.file.Files;
21+
import java.util.Iterator;
2122
import java.util.LinkedHashMap;
2223
import java.util.List;
23-
import java.util.Map;
2424

2525
import javax.annotation.Nullable;
2626

@@ -45,23 +45,49 @@ public boolean isClean() {
4545
return dirtyState.isClean() && !isHasLints();
4646
}
4747

48-
public Map<FormatterStep, List<Lint>> getLints(Formatter formatter) {
48+
public LinkedHashMap<String, List<Lint>> getLintsByStep(Formatter formatter) {
4949
if (lintsPerStep == null) {
5050
throw new IllegalStateException("Check `isHasLints` first!");
5151
}
5252
if (lintsPerStep.size() != formatter.getSteps().size()) {
5353
throw new IllegalStateException("LintState was created with a different formatter!");
5454
}
55-
Map<FormatterStep, List<Lint>> result = new LinkedHashMap<>();
55+
LinkedHashMap<String, List<Lint>> result = new LinkedHashMap<>();
5656
for (int i = 0; i < lintsPerStep.size(); i++) {
57+
FormatterStep step = formatter.getSteps().get(i);
5758
List<Lint> lints = lintsPerStep.get(i);
5859
if (lints != null) {
59-
result.put(formatter.getSteps().get(i), lints);
60+
result.put(step.getName(), lints);
6061
}
6162
}
6263
return result;
6364
}
6465

66+
public void removeSuppressedLints(Formatter formatter, String relativePath, List<LintSuppression> suppressions) {
67+
if (lintsPerStep == null) {
68+
return;
69+
}
70+
for (int i = 0; i < lintsPerStep.size(); i++) {
71+
FormatterStep step = formatter.getSteps().get(i);
72+
List<Lint> lints = lintsPerStep.get(i);
73+
if (lints != null) {
74+
Iterator<Lint> iter = lints.iterator();
75+
while (iter.hasNext()) {
76+
Lint lint = iter.next();
77+
for (LintSuppression suppression : suppressions) {
78+
if (suppression.suppresses(relativePath, step, lint)) {
79+
iter.remove();
80+
break;
81+
}
82+
}
83+
}
84+
if (lints.isEmpty()) {
85+
lintsPerStep.set(i, null);
86+
}
87+
}
88+
}
89+
}
90+
6591
public String asStringDetailed(File file, Formatter formatter) {
6692
return asString(file, formatter, false);
6793
}
@@ -81,27 +107,7 @@ private String asString(File file, Formatter formatter, boolean oneLine) {
81107
FormatterStep step = formatter.getSteps().get(i);
82108
for (Lint lint : lints) {
83109
result.append(file.getName()).append(":");
84-
if (lint.getLineStart() == Lint.LINE_UNDEFINED) {
85-
result.append("LINE_UNDEFINED");
86-
} else {
87-
result.append("L");
88-
result.append(lint.getLineStart());
89-
if (lint.getLineEnd() != lint.getLineStart()) {
90-
result.append("-").append(lint.getLineEnd());
91-
}
92-
}
93-
result.append(" ");
94-
result.append(step.getName()).append("(").append(lint.getRuleId()).append(") ");
95-
96-
int firstNewline = lint.getDetail().indexOf('\n');
97-
if (firstNewline == -1) {
98-
result.append(lint.getDetail());
99-
} else if (oneLine) {
100-
result.append(lint.getDetail(), 0, firstNewline);
101-
result.append(" (...)");
102-
} else {
103-
result.append(lint.getDetail());
104-
}
110+
lint.addWarningMessageTo(result, step.getName(), oneLine);
105111
result.append("\n");
106112
}
107113
}
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
/*
2+
* Copyright 2024 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.spotless;
17+
18+
import java.util.Objects;
19+
20+
public class LintSuppression implements java.io.Serializable {
21+
private static final long serialVersionUID = 1L;
22+
23+
private static final String ALL = "*";
24+
private String file = ALL;
25+
private String step = ALL;
26+
private String shortCode = ALL;
27+
28+
public String getFile() {
29+
return file;
30+
}
31+
32+
public void setFile(String file) {
33+
this.file = Objects.requireNonNull(file);
34+
}
35+
36+
public String getStep() {
37+
return step;
38+
}
39+
40+
public void setStep(String step) {
41+
this.step = Objects.requireNonNull(step);
42+
}
43+
44+
public String getShortCode() {
45+
return shortCode;
46+
}
47+
48+
public void setShortCode(String shortCode) {
49+
this.shortCode = Objects.requireNonNull(shortCode);
50+
}
51+
52+
public boolean suppresses(String relativePath, FormatterStep step, Lint lint) {
53+
return !allows(relativePath, step, lint);
54+
}
55+
56+
private boolean allows(String relativePath, FormatterStep step, Lint lint) {
57+
if (!file.equals(ALL) && !file.equals(relativePath)) {
58+
return false;
59+
}
60+
if (!this.step.equals(ALL) && !this.step.equals(step.getName())) {
61+
return false;
62+
}
63+
if (!this.shortCode.equals(ALL) && !this.shortCode.equals(lint.getRuleId())) {
64+
return false;
65+
}
66+
return true;
67+
}
68+
69+
public void ensureDoesNotSuppressAll() {
70+
boolean suppressAll = file.equals(ALL) && step.equals(ALL) && shortCode.equals(ALL);
71+
if (suppressAll) {
72+
throw new IllegalArgumentException("You must specify a specific `file`, `step`, or `shortCode`.");
73+
}
74+
}
75+
76+
@Override
77+
public boolean equals(Object o) {
78+
if (this == o)
79+
return true;
80+
if (o == null || getClass() != o.getClass())
81+
return false;
82+
LintSuppression that = (LintSuppression) o;
83+
return Objects.equals(file, that.file) && Objects.equals(step, that.step) && Objects.equals(shortCode, that.shortCode);
84+
}
85+
86+
@Override
87+
public int hashCode() {
88+
return Objects.hash(file, step, shortCode);
89+
}
90+
91+
@Override
92+
public String toString() {
93+
return "LintSuppression{" +
94+
"file='" + file + '\'' +
95+
", step='" + step + '\'' +
96+
", code='" + shortCode + '\'' +
97+
'}';
98+
}
99+
}

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

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,11 @@
4949
import org.gradle.util.GradleVersion;
5050

5151
import com.diffplug.common.base.Preconditions;
52-
import com.diffplug.spotless.FormatExceptionPolicyStrict;
5352
import com.diffplug.spotless.FormatterFunc;
5453
import com.diffplug.spotless.FormatterStep;
5554
import com.diffplug.spotless.LazyForwardingEquality;
5655
import com.diffplug.spotless.LineEnding;
56+
import com.diffplug.spotless.LintSuppression;
5757
import com.diffplug.spotless.OnMatch;
5858
import com.diffplug.spotless.Provisioner;
5959
import com.diffplug.spotless.SerializedFunction;
@@ -168,16 +168,25 @@ public void setEncoding(Charset charset) {
168168
encoding = requireNonNull(charset);
169169
}
170170

171-
final FormatExceptionPolicyStrict exceptionPolicy = new FormatExceptionPolicyStrict();
171+
final List<LintSuppression> lintSuppressions = new ArrayList<>();
172+
173+
public void suppressLintsFor(Action<LintSuppression> lintSuppression) {
174+
LintSuppression suppression = new LintSuppression();
175+
lintSuppression.execute(suppression);
176+
suppression.ensureDoesNotSuppressAll();
177+
lintSuppressions.add(suppression);
178+
}
172179

173180
/** Ignores errors in the given step. */
181+
@Deprecated
174182
public void ignoreErrorForStep(String stepName) {
175-
exceptionPolicy.excludeStep(requireNonNull(stepName));
183+
suppressLintsFor(it -> it.setStep(stepName));
176184
}
177185

178186
/** Ignores errors for the given relative path. */
187+
@Deprecated
179188
public void ignoreErrorForPath(String relativePath) {
180-
exceptionPolicy.excludePath(requireNonNull(relativePath));
189+
suppressLintsFor(it -> it.setFile(relativePath));
181190
}
182191

183192
/**
@@ -996,7 +1005,7 @@ public void toggleOffOnDisable() {
9961005
/** Sets up a format task according to the values in this extension. */
9971006
protected void setupTask(SpotlessTask task) {
9981007
task.setEncoding(getEncoding().name());
999-
task.setExceptionPolicy(exceptionPolicy);
1008+
task.setLintSuppressions(lintSuppressions);
10001009
FileCollection totalTarget = targetExclude == null ? target : target.minus(targetExclude);
10011010
task.setTarget(totalTarget);
10021011
List<FormatterStep> steps;

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

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import java.nio.file.Files;
2121
import java.nio.file.StandardCopyOption;
2222

23+
import org.gradle.api.GradleException;
2324
import org.gradle.api.file.ConfigurableFileTree;
2425
import org.gradle.api.file.FileVisitDetails;
2526
import org.gradle.api.file.FileVisitor;
@@ -30,7 +31,8 @@ public abstract class SpotlessApply extends SpotlessTaskService.ClientTask {
3031
public void performAction() {
3132
getTaskService().get().registerApplyAlreadyRan(this);
3233
ConfigurableFileTree cleanFiles = getConfigCacheWorkaround().fileTree().from(getSpotlessCleanDirectory().get());
33-
if (cleanFiles.isEmpty()) {
34+
ConfigurableFileTree lintsFiles = getConfigCacheWorkaround().fileTree().from(getSpotlessLintsDirectory().get());
35+
if (cleanFiles.isEmpty() && lintsFiles.isEmpty()) {
3436
getState().setDidWork(sourceDidWork());
3537
} else {
3638
cleanFiles.visit(new FileVisitor() {
@@ -51,6 +53,10 @@ public void visitFile(FileVisitDetails fileVisitDetails) {
5153
}
5254
}
5355
});
56+
if (!lintsFiles.isEmpty()) {
57+
boolean detailed = false;
58+
throw new GradleException(super.allLintsErrorMsgDetailed(lintsFiles, detailed));
59+
}
5460
}
5561
}
5662
}

0 commit comments

Comments
 (0)