-
Notifications
You must be signed in to change notification settings - Fork 336
Expand file tree
/
Copy pathAssertJPreferenceLinter.kt
More file actions
60 lines (52 loc) · 2.09 KB
/
AssertJPreferenceLinter.kt
File metadata and controls
60 lines (52 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package datadog.gradle.plugin.lint
import org.gradle.api.Plugin
import org.gradle.api.Project
import java.io.ByteArrayOutputStream
class AssertJPreferenceLinter : Plugin<Project> {
override fun apply(target: Project) {
target.tasks.register("checkAssertJPreference") {
group = "verification"
description = "Flags JUnit assertion imports in new test files — prefer AssertJ"
doLast {
val newTestFiles = getNewTestFiles(target)
if (newTestFiles.isEmpty()) {
target.logger.lifecycle("checkAssertJPreference: No new test files to check")
return@doLast
}
val warnings = mutableListOf<String>()
val junitAssertImport = Regex("""import\s+(?:static\s+)?org\.junit\.jupiter\.api\.Assertions""")
newTestFiles.forEach { file ->
if (!file.exists()) return@forEach
val lines = file.readLines()
val relPath = file.relativeTo(target.rootProject.projectDir).path
for (i in lines.indices) {
if (junitAssertImport.containsMatchIn(lines[i])) {
warnings.add("STYLE: $relPath:${i + 1} — Prefer AssertJ (org.assertj.core.api.Assertions) over JUnit assertions for richer API")
}
}
}
if (warnings.isNotEmpty()) {
warnings.forEach { target.logger.warn(it) }
target.logger.warn("checkAssertJPreference: ${warnings.size} file(s) using JUnit assertions instead of AssertJ")
} else {
target.logger.lifecycle("checkAssertJPreference: All new test files use AssertJ")
}
}
}
}
private fun getNewTestFiles(project: Project): List<java.io.File> {
return try {
val stdout = ByteArrayOutputStream()
project.exec {
commandLine("git", "diff", "--name-only", "--diff-filter=A", "origin/master...HEAD")
standardOutput = stdout
isIgnoreExitValue = true
}
stdout.toString().trim().lines()
.filter { it.endsWith(".java") && it.contains("src/test/") }
.map { project.rootProject.file(it) }
} catch (e: Exception) {
emptyList()
}
}
}