Skip to content

Commit 2fddb87

Browse files
build(gradle): mirror the Maven analyzers in the Gradle plugin build
Run checkstyle, PMD, Error Prone with NullAway, SpotBugs with FindSecBugs, and forbidden-apis on the Gradle plugin's main and test sources, reading the rule files under config/ and the tool versions from the root pom so both builds run the same checks. Declare spring-javaformat's CheckFormat incompatible with the configuration cache instead of letting it fail there (spring-io/spring-javaformat#461). Fix what the analyzers found: parseFormat keeps the cause, logReport splits with String.lines like the Maven side, the tests declare the exception they throw and no longer pass a possibly-null parent to createDirectories. Two pinned SpotBugs exclusions document the two reports the detectors cannot see through.
1 parent 36eb11b commit 2fddb87

5 files changed

Lines changed: 120 additions & 27 deletions

File tree

‎config/spotbugs/exclude.xml‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,21 @@
4444
<Bug pattern="POTENTIAL_XML_INJECTION"/>
4545
</Match>
4646

47+
<!-- Gradle instantiates the abstract task type through a generated subclass that does
48+
not override getOutputs(); the constructor is the only place a task type can declare
49+
that it is never up to date. -->
50+
<Match>
51+
<Class name="com.patbaumgartner.prune.gradle.PruneBaselineTask"/>
52+
<Method name="&lt;init&gt;"/>
53+
<Bug pattern="MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR"/>
54+
</Match>
55+
56+
<!-- Every logged line comes out of String.lines(), which strips the line terminators
57+
the detector is looking for; the renderer escapes the other control characters. -->
58+
<Match>
59+
<Class name="com.patbaumgartner.prune.gradle.TaskSupport"/>
60+
<Method name="logReport"/>
61+
<Bug pattern="CRLF_INJECTION_LOGS"/>
62+
</Match>
63+
4764
</FindBugsFilter>

‎prune-gradle-plugin/build.gradle‎

Lines changed: 73 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,35 @@ plugins {
55
id 'maven-publish'
66
// Same source layout as the Maven modules: checkFormat runs with check, format rewrites.
77
id 'io.spring.javaformat' version '0.0.48'
8+
// The same analyzers as the Maven reactor, reading the same rule files under ../config.
9+
id 'checkstyle'
10+
id 'pmd'
11+
id 'net.ltgt.errorprone' version '5.1.1'
12+
id 'net.ltgt.nullaway' version '3.2.0'
13+
id 'com.github.spotbugs' version '6.5.11'
14+
id 'de.thetaphi.forbiddenapis' version '3.10'
815
}
916

17+
import com.github.spotbugs.snom.Confidence
18+
import com.github.spotbugs.snom.Effort
19+
1020
group = 'com.patbaumgartner'
1121
// The Maven reactor at the repository root owns the version; this build consumes
1222
// prune-core at exactly that version, so reading it from the pom keeps the two builds
1323
// from drifting apart. groovy.xml.XmlSlurper is spelled out: Groovy 4 no longer imports it by default.
14-
version = new groovy.xml.XmlSlurper(false, false).parse(file('../pom.xml')).version.text()
24+
def rootPom = new groovy.xml.XmlSlurper(false, false).parse(file('../pom.xml'))
25+
version = rootPom.version.text()
1526
if (!version) {
1627
throw new GradleException('Could not read the project version from ../pom.xml')
1728
}
29+
// The analyzer versions come from the same place, so both builds run the same tools.
30+
def pomProperty = { String name ->
31+
def value = rootPom.properties.children().find { it.name() == name }?.text()
32+
if (!value) {
33+
throw new GradleException("Could not read ${name} from ../pom.xml")
34+
}
35+
value
36+
}
1837

1938
repositories {
2039
// prune-core is built by the Maven reactor at the repository root; run
@@ -38,6 +57,54 @@ java {
3857

3958
tasks.withType(JavaCompile).configureEach {
4059
options.release = 17
60+
// Same NullAway settings as the Maven reactor; the errorprone plugin adds the javac
61+
// flags Error Prone needs on its own.
62+
options.errorprone.nullaway {
63+
error()
64+
excludedFieldAnnotations.add('org.junit.jupiter.api.io.TempDir')
65+
handleTestAssertionLibraries = true
66+
}
67+
}
68+
69+
nullaway {
70+
annotatedPackages.add('com.patbaumgartner')
71+
}
72+
73+
checkstyle {
74+
toolVersion = pomProperty('checkstyle.version')
75+
configFile = file('../config/checkstyle/checkstyle.xml')
76+
maxWarnings = 0
77+
}
78+
79+
pmd {
80+
toolVersion = pomProperty('pmd.version')
81+
ruleSets = []
82+
ruleSetFiles = files('../config/pmd/ruleset.xml')
83+
consoleOutput = true
84+
}
85+
86+
spotbugs {
87+
toolVersion = pomProperty('spotbugs.version')
88+
// Groovy resolves Effort.MAX to the constant's own class, which the property rejects.
89+
effort = Effort.valueOf('MAX')
90+
reportLevel = Confidence.valueOf('LOW')
91+
excludeFilter = file('../config/spotbugs/exclude.xml')
92+
}
93+
94+
tasks.withType(com.github.spotbugs.snom.SpotBugsTask).configureEach {
95+
reports.create('xml') { required = true }
96+
reports.create('html') { required = true }
97+
}
98+
99+
forbiddenApis {
100+
bundledSignatures = ['jdk-unsafe', 'jdk-deprecated', 'jdk-non-portable', 'jdk-reflection']
101+
signaturesFiles = files('../config/forbidden-apis/signatures.txt')
102+
}
103+
104+
// spring-javaformat 0.0.48 reads Task.project while checking (spring-io/spring-javaformat#461).
105+
// Declaring that keeps a build with the configuration cache enabled from failing on it.
106+
tasks.withType(io.spring.javaformat.gradle.tasks.CheckFormat).configureEach {
107+
notCompatibleWithConfigurationCache('spring-io/spring-javaformat#461: CheckFormat reads Task.project at execution time')
41108
}
42109

43110
// Same promise as project.build.outputTimestamp in the Maven build: rebuilding a tag yields
@@ -56,6 +123,11 @@ tasks.withType(Javadoc).configureEach {
56123

57124
dependencies {
58125
implementation "com.patbaumgartner:prune-core:${version}"
126+
compileOnly "org.jspecify:jspecify:${pomProperty('jspecify.version')}"
127+
128+
errorprone "com.google.errorprone:error_prone_core:${pomProperty('errorprone.version')}"
129+
errorprone "com.uber.nullaway:nullaway:${pomProperty('nullaway.version')}"
130+
spotbugsPlugins "com.h3xstream.findsecbugs:findsecbugs-plugin:${pomProperty('findsecbugs.version')}"
59131

60132
testImplementation platform('org.junit:junit-bom:6.1.3')
61133
testImplementation 'org.junit.jupiter:junit-jupiter'

‎prune-gradle-plugin/src/main/java/com/patbaumgartner/prune/gradle/TaskSupport.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ static OutputFormat parseFormat(String format) {
1919
return OutputFormat.parse(format);
2020
}
2121
catch (IllegalArgumentException exception) {
22-
throw new GradleException(exception.getMessage() + " (expected terminal, github, or json)");
22+
throw new GradleException(exception.getMessage() + " (expected terminal, github, or json)", exception);
2323
}
2424
}
2525

@@ -33,7 +33,7 @@ static AnalysisConfig configFor(DirectoryProperty projectRoot, ListProperty<Stri
3333
}
3434

3535
static void logReport(Logger logger, String rendered, boolean asWarning) {
36-
for (String line : rendered.split("\\R")) {
36+
for (String line : rendered.lines().toList()) {
3737
if (asWarning) {
3838
logger.warn(line);
3939
}

‎prune-gradle-plugin/src/test/java/com/patbaumgartner/prune/gradle/PruneGradlePluginTest.java‎

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,10 @@
1212
import java.nio.file.Files;
1313
import java.nio.file.Path;
1414
import java.util.List;
15+
import java.util.Objects;
1516

1617
import static org.junit.jupiter.api.Assertions.assertEquals;
18+
import static org.junit.jupiter.api.Assertions.assertFalse;
1719
import static org.junit.jupiter.api.Assertions.assertNotNull;
1820
import static org.junit.jupiter.api.Assertions.assertTrue;
1921

@@ -38,12 +40,12 @@ void checkTaskDefaultsItsProjectRootToTheApplyingProject() {
3840
var task = (PruneCheckTask) project.getTasks().getByName("pruneCheck");
3941

4042
assertEquals(project.getProjectDir(), task.getProjectRoot().get().getAsFile());
41-
assertEquals(Boolean.FALSE, task.getIgnoreFailures().get());
43+
assertFalse(task.getIgnoreFailures().get());
4244
assertEquals("terminal", task.getFormat().get());
4345
assertEquals(List.of(), task.getExcludes().get());
4446
assertEquals(new File(project.getProjectDir(), "prune-baseline.txt"), task.getBaseline().get().getAsFile());
45-
assertEquals(Boolean.TRUE, task.getTestReferences().get());
46-
assertEquals(Boolean.FALSE, task.getExplain().get());
47+
assertTrue(task.getTestReferences().get());
48+
assertFalse(task.getExplain().get());
4749
assertEquals("verification", task.getGroup());
4850
}
4951

@@ -58,7 +60,7 @@ void fixTaskDefaultsItsProjectRootAndFormat() {
5860
assertEquals("terminal", task.getFormat().get());
5961
assertEquals(List.of(), task.getExcludes().get());
6062
assertEquals(new File(project.getProjectDir(), "prune-baseline.txt"), task.getBaseline().get().getAsFile());
61-
assertEquals(Boolean.TRUE, task.getTestReferences().get());
63+
assertTrue(task.getTestReferences().get());
6264
}
6365

6466
@Test
@@ -71,11 +73,11 @@ void baselineTaskDefaultsItsFileAndTestReferences() {
7173
assertEquals(project.getProjectDir(), task.getProjectRoot().get().getAsFile());
7274
assertEquals(List.of(), task.getExcludes().get());
7375
assertEquals(new File(project.getProjectDir(), "prune-baseline.txt"), task.getBaseline().get().getAsFile());
74-
assertEquals(Boolean.TRUE, task.getTestReferences().get());
76+
assertTrue(task.getTestReferences().get());
7577
}
7678

7779
@Test
78-
void checkTaskRunsWithTheConfigurationCacheEnabled(@TempDir Path projectDir) throws Exception {
80+
void checkTaskRunsWithTheConfigurationCacheEnabled(@TempDir Path projectDir) throws IOException {
7981
Files.writeString(projectDir.resolve("settings.gradle"), "rootProject.name = 'cc-probe'\n",
8082
StandardCharsets.UTF_8);
8183
Files.writeString(projectDir.resolve("build.gradle"), "plugins { id 'com.patbaumgartner.prune-java' }\n",
@@ -92,7 +94,7 @@ void checkTaskRunsWithTheConfigurationCacheEnabled(@TempDir Path projectDir) thr
9294
}
9395

9496
@Test
95-
void checkTaskRejectsAnUnknownFormat(@TempDir Path projectDir) throws Exception {
97+
void checkTaskRejectsAnUnknownFormat(@TempDir Path projectDir) throws IOException {
9698
Files.writeString(projectDir.resolve("settings.gradle"), "rootProject.name = 'format-probe'\n",
9799
StandardCharsets.UTF_8);
98100
Files.writeString(projectDir.resolve("build.gradle"),
@@ -111,7 +113,8 @@ void checkTaskRejectsAnUnknownFormat(@TempDir Path projectDir) throws Exception
111113
}
112114

113115
@Test
114-
void baselineTaskRecordsTheFindingsAndCheckThenPassesWithThemSuppressed(@TempDir Path projectDir) throws Exception {
116+
void baselineTaskRecordsTheFindingsAndCheckThenPassesWithThemSuppressed(@TempDir Path projectDir)
117+
throws IOException {
115118
Files.writeString(projectDir.resolve("settings.gradle"), "rootProject.name = 'baseline-probe'\n",
116119
StandardCharsets.UTF_8);
117120
Files.writeString(projectDir.resolve("build.gradle"), "plugins { id 'com.patbaumgartner.prune-java' }\n",
@@ -140,7 +143,7 @@ void baselineTaskRecordsTheFindingsAndCheckThenPassesWithThemSuppressed(@TempDir
140143

141144
@Test
142145
void baselineTaskRunsAgainWhenTheSourcesChangeEvenThoughItsOnlyDeclaredInputsDidNot(@TempDir Path projectDir)
143-
throws Exception {
146+
throws IOException {
144147
Files.writeString(projectDir.resolve("settings.gradle"), "rootProject.name = 'rerun-probe'\n",
145148
StandardCharsets.UTF_8);
146149
Files.writeString(projectDir.resolve("build.gradle"), "plugins { id 'com.patbaumgartner.prune-java' }\n",
@@ -159,7 +162,7 @@ void baselineTaskRunsAgainWhenTheSourcesChangeEvenThoughItsOnlyDeclaredInputsDid
159162
}
160163

161164
@Test
162-
void tasksHonourAnExplicitBaselineFileAndTestReferences(@TempDir Path projectDir) throws Exception {
165+
void tasksHonourAnExplicitBaselineFileAndTestReferences(@TempDir Path projectDir) throws IOException {
163166
Files.writeString(projectDir.resolve("settings.gradle"), "rootProject.name = 'options-probe'\n",
164167
StandardCharsets.UTF_8);
165168
Files.writeString(projectDir.resolve("build.gradle"), """
@@ -194,7 +197,7 @@ void tasksHonourAnExplicitBaselineFileAndTestReferences(@TempDir Path projectDir
194197
}
195198

196199
@Test
197-
void checkTaskTurnsAMalformedBaselineIntoABuildFailure(@TempDir Path projectDir) throws Exception {
200+
void checkTaskTurnsAMalformedBaselineIntoABuildFailure(@TempDir Path projectDir) throws IOException {
198201
Files.writeString(projectDir.resolve("settings.gradle"), "rootProject.name = 'malformed-probe'\n",
199202
StandardCharsets.UTF_8);
200203
Files.writeString(projectDir.resolve("build.gradle"), "plugins { id 'com.patbaumgartner.prune-java' }\n",
@@ -216,7 +219,7 @@ private static GradleRunner runner(Path projectDir, String... arguments) {
216219

217220
private static void writeSource(Path projectDir, String relativePath, String content) throws IOException {
218221
var file = projectDir.resolve(relativePath);
219-
Files.createDirectories(file.getParent());
222+
Files.createDirectories(Objects.requireNonNull(file.getParent()));
220223
Files.writeString(file, content, StandardCharsets.UTF_8);
221224
}
222225

‎prune-gradle-plugin/src/test/java/com/patbaumgartner/prune/gradle/SampleProjectFunctionalTest.java‎

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import java.nio.file.StandardCopyOption;
1313
import java.util.ArrayList;
1414
import java.util.List;
15+
import java.util.Objects;
1516
import java.util.regex.Pattern;
1617
import java.util.stream.Stream;
1718

@@ -23,7 +24,7 @@ class SampleProjectFunctionalTest {
2324

2425
@Test
2526
void checkTaskFailsTheBuildWithTheManifestFindingsForTheGradleSampleProject(@TempDir Path projectDir)
26-
throws Exception {
27+
throws IOException {
2728
copySample("gradle-sample", projectDir);
2829

2930
var result = runner(projectDir, "pruneCheck", "--console=plain").buildAndFail();
@@ -37,12 +38,12 @@ void checkTaskFailsTheBuildWithTheManifestFindingsForTheGradleSampleProject(@Tem
3738
+ expected.size() + " issue(s) found (conservative mode)."),
3839
result.getOutput());
3940
for (var row : expected) {
40-
assertTrue(result.getOutput().contains(simpleName(row.split("\\s+")[2])), row);
41+
assertTrue(result.getOutput().contains(simpleName(row.split("\\s+", -1)[2])), row);
4142
}
4243
}
4344

4445
@Test
45-
void checkTaskWithoutTestReferencesAlsoReportsTheTestOnlyRows(@TempDir Path projectDir) throws Exception {
46+
void checkTaskWithoutTestReferencesAlsoReportsTheTestOnlyRows(@TempDir Path projectDir) throws IOException {
4647
copySample("gradle-sample", projectDir);
4748
Files.writeString(projectDir.resolve("build.gradle"),
4849
Files.readString(projectDir.resolve("build.gradle"), StandardCharsets.UTF_8)
@@ -55,14 +56,14 @@ void checkTaskWithoutTestReferencesAlsoReportsTheTestOnlyRows(@TempDir Path proj
5556
assertTrue(result.getOutput().contains("prune-java found " + expected + " unused-code issue(s)."),
5657
result.getOutput());
5758
for (var row : manifest(projectDir, "test-only")) {
58-
var symbol = row.split("\\s+")[2];
59+
var symbol = row.split("\\s+", -1)[2];
5960
assertTrue(result.getOutput().contains(simpleName(symbol) + " is only referenced from tests"),
6061
result.getOutput());
6162
}
6263
}
6364

6465
@Test
65-
void checkTaskWithIgnoreFailuresLogsAJsonReportEqualToTheManifest(@TempDir Path projectDir) throws Exception {
66+
void checkTaskWithIgnoreFailuresLogsAJsonReportEqualToTheManifest(@TempDir Path projectDir) throws IOException {
6667
copySample("gradle-sample", projectDir);
6768
Files.writeString(projectDir.resolve("build.gradle"),
6869
Files.readString(projectDir.resolve("build.gradle"), StandardCharsets.UTF_8)
@@ -84,15 +85,15 @@ void checkTaskWithIgnoreFailuresLogsAJsonReportEqualToTheManifest(@TempDir Path
8485
reported.add(matcher.group(1) + " " + matcher.group(2));
8586
}
8687
var expected = manifest(projectDir, "unused").stream()
87-
.map(row -> row.split("\\s+"))
88+
.map(row -> row.split("\\s+", -1))
8889
.map(columns -> columns[1] + " " + columns[2])
8990
.sorted()
9091
.toList();
9192
assertEquals(expected, reported.stream().sorted().toList(), json);
9293
}
9394

9495
@Test
95-
void checkTaskHonoursExcludesAndStillReportsDependencies(@TempDir Path projectDir) throws Exception {
96+
void checkTaskHonoursExcludesAndStillReportsDependencies(@TempDir Path projectDir) throws IOException {
9697
copySample("gradle-sample", projectDir);
9798
Files.writeString(projectDir.resolve("build.gradle"),
9899
Files.readString(projectDir.resolve("build.gradle"), StandardCharsets.UTF_8)
@@ -110,14 +111,14 @@ void checkTaskHonoursExcludesAndStillReportsDependencies(@TempDir Path projectDi
110111
}
111112

112113
@Test
113-
void checkTaskReportsNoSymbolTheSampleMarksAsKept(@TempDir Path projectDir) throws Exception {
114+
void checkTaskReportsNoSymbolTheSampleMarksAsKept(@TempDir Path projectDir) throws IOException {
114115
copySample("gradle-sample", projectDir);
115116

116117
var result = runner(projectDir, "pruneCheck").buildAndFail();
117118

118119
for (var row : manifest(projectDir, "kept")) {
119-
var symbol = row.split("\\s+")[2];
120-
for (var line : result.getOutput().split("\\R")) {
120+
var symbol = row.split("\\s+", -1)[2];
121+
for (var line : result.getOutput().lines().toList()) {
121122
if (line.contains(" :: ")) {
122123
assertFalse(line.contains(simpleName(symbol) + " is"), line);
123124
}
@@ -126,7 +127,7 @@ void checkTaskReportsNoSymbolTheSampleMarksAsKept(@TempDir Path projectDir) thro
126127
}
127128

128129
@Test
129-
void fixTaskRewritesTheCopiedSampleAndLeavesTheClassFindingForReview(@TempDir Path projectDir) throws Exception {
130+
void fixTaskRewritesTheCopiedSampleAndLeavesTheClassFindingForReview(@TempDir Path projectDir) throws IOException {
130131
copySample("gradle-sample", projectDir);
131132
var stockLevel = projectDir.resolve("src/main/java/com/example/gradlesample/StockLevel.java");
132133
var warehouseCodes = projectDir.resolve("src/main/java/com/example/gradlesample/WarehouseCodes.java");
@@ -183,7 +184,7 @@ private static void copySample(String sample, Path target) throws IOException {
183184
Files.createDirectories(destination);
184185
}
185186
else {
186-
Files.createDirectories(destination.getParent());
187+
Files.createDirectories(Objects.requireNonNull(destination.getParent()));
187188
Files.copy(path, destination, StandardCopyOption.REPLACE_EXISTING);
188189
}
189190
}

0 commit comments

Comments
 (0)