-
-
Notifications
You must be signed in to change notification settings - Fork 758
/
Suppressions.kt
60 lines (53 loc) · 2.25 KB
/
Suppressions.kt
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 io.gitlab.arturbosch.detekt.core.suppressors
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.RuleSet
import org.jetbrains.kotlin.psi.KtAnnotated
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
/**
* Checks if this psi element is suppressed by @Suppress or @SuppressWarnings annotations.
* If this element cannot have annotations, the first annotative parent is searched.
*/
fun KtElement.isSuppressedBy(id: Rule.Id, aliases: Set<String>, ruleSetId: RuleSet.Id? = null): Boolean =
this is KtAnnotated &&
this.isSuppressedBy(id, aliases, ruleSetId) ||
findAnnotatedSuppressedParent(id, aliases, ruleSetId)
private fun KtElement.findAnnotatedSuppressedParent(
id: Rule.Id,
aliases: Set<String>,
ruleSetId: RuleSet.Id? = null
): Boolean {
val parent = getStrictParentOfType<KtAnnotated>()
var suppressed = false
if (parent != null && parent !is KtFile) {
suppressed = if (parent.isSuppressedBy(id, aliases, ruleSetId)) {
true
} else {
parent.findAnnotatedSuppressedParent(id, aliases, ruleSetId)
}
}
return suppressed
}
private val detektSuppressionPrefixRegex = Regex("(?i)detekt([.:])")
private const val QUOTES = "\""
private val suppressionAnnotations = setOf("Suppress", "SuppressWarnings")
/**
* Checks if this kt element is suppressed by @Suppress or @SuppressWarnings annotations.
*/
private fun KtAnnotated.isSuppressedBy(id: Rule.Id, aliases: Set<String>, ruleSetId: RuleSet.Id? = null): Boolean {
val acceptedSuppressionIds = mutableSetOf(id.value, "ALL", "all", "All")
if (ruleSetId != null) {
acceptedSuppressionIds.addAll(listOf(ruleSetId.value, "$ruleSetId.$id", "$ruleSetId:$id"))
}
acceptedSuppressionIds.addAll(aliases)
return annotationEntries
.find { it.typeReference?.text in suppressionAnnotations }
?.run {
valueArguments
.map { it.getArgumentExpression()?.text }
.map { it?.replace(detektSuppressionPrefixRegex, "") }
.map { it?.replace(QUOTES, "") }
.find { it in acceptedSuppressionIds }
} != null
}