Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix ObjectPropertyNaming Rule false positive #5466

Merged
merged 2 commits into from Oct 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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