/
TopLevelPropertyNaming.kt
79 lines (68 loc) · 2.83 KB
/
TopLevelPropertyNaming.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package io.gitlab.arturbosch.detekt.rules.naming
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.config
import io.gitlab.arturbosch.detekt.api.internal.ActiveByDefault
import io.gitlab.arturbosch.detekt.api.internal.Configuration
import io.gitlab.arturbosch.detekt.rules.identifierName
import io.gitlab.arturbosch.detekt.rules.isConstant
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.psiUtil.isPrivate
/**
* Reports top level constant that which do not follow the specified naming convention.
*/
@ActiveByDefault(since = "1.0.0")
class TopLevelPropertyNaming(config: Config = Config.empty) : Rule(config) {
override val issue = Issue(
javaClass.simpleName,
Severity.Style,
"Top level property names should follow the naming convention set in the projects configuration.",
debt = Debt.FIVE_MINS
)
@Configuration("naming pattern")
private val constantPattern: Regex by config("[A-Z][_A-Z0-9]*") { it.toRegex() }
@Configuration("naming pattern")
private val propertyPattern: Regex by config("[A-Za-z][_A-Za-z0-9]*") { it.toRegex() }
@Configuration("naming pattern")
private val privatePropertyPattern: Regex by config("_?[A-Za-z][_A-Za-z0-9]*") { it.toRegex() }
override fun visitProperty(property: KtProperty) {
super.visitProperty(property)
if (!property.isTopLevel) return
if (property.isConstant()) {
handleConstant(property)
} else {
handleProperty(property)
}
}
private fun handleConstant(property: KtProperty) {
if (!property.identifierName().matches(constantPattern)) {
report(property, "Top level constant names should match the pattern: $constantPattern")
}
}
private fun handleProperty(property: KtProperty) {
if (property.isPrivate()) {
if (!property.identifierName().matches(privatePropertyPattern)) {
report(property, "Private top level property names should match the pattern: $privatePropertyPattern")
}
} else if (!property.identifierName().matches(propertyPattern)) {
report(property, "Top level property names should match the pattern: $propertyPattern")
}
}
private fun report(property: KtProperty, message: String) {
report(
CodeSmell(
issue,
Entity.atName(property),
message = message
)
)
}
companion object {
const val CONSTANT_PATTERN = "constantPattern"
}
}