Skip to content

Commit

Permalink
Fix ObjectPropertyNaming Rule false positive (#5466)
Browse files Browse the repository at this point in the history
* fix: ObjectPropertyNaming false positive

* fix: detekt correct
  • Loading branch information
sanggggg committed Oct 23, 2022
1 parent 125e8e7 commit abd58d2
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
Expand Up @@ -12,7 +12,10 @@ 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.KtClassOrObject
import org.jetbrains.kotlin.psi.KtObjectDeclaration
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.isPrivate

/**
Expand All @@ -38,7 +41,7 @@ class ObjectPropertyNaming(config: Config = Config.empty) : Rule(config) {
private val privatePropertyPattern: Regex by config("(_)?[A-Za-z][_A-Za-z0-9]*") { it.toRegex() }

override fun visitProperty(property: KtProperty) {
if (property.isLocal || property.isTopLevel) {
if (property.isPropertyOfObjectDeclaration().not()) {
return
}

Expand All @@ -49,6 +52,9 @@ class ObjectPropertyNaming(config: Config = Config.empty) : Rule(config) {
}
}

private fun KtProperty.isPropertyOfObjectDeclaration(): Boolean =
this.isMember && this.getNonStrictParentOfType<KtClassOrObject>() is KtObjectDeclaration

private fun handleConstant(property: KtProperty) {
if (!property.identifierName().matches(constantPattern)) {
report(property, "Object constant names should match the pattern: $constantPattern")
Expand Down
Expand Up @@ -251,6 +251,30 @@ class ObjectPropertyNamingSpec {
assertThat(subject.compileAndLint(code)).isEmpty()
}
}

@Test
fun `should not detect class properties`() {
val subject = ObjectPropertyNaming()
val code = """
class O {
val _invalidNaming = 1
}
""".trimIndent()
assertThat(subject.compileAndLint(code)).isEmpty()
}

@Test
fun `should not detect properties of class in object declaration`() {
val subject = ObjectPropertyNaming()
val code = """
object A {
class O {
val _invalidNaming = 1
}
}
""".trimIndent()
assertThat(subject.compileAndLint(code)).isEmpty()
}
}

@Suppress("UnnecessaryAbstractClass")
Expand Down

0 comments on commit abd58d2

Please sign in to comment.