From a6c563a1e38624fd4610bf71036a3543e37c1469 Mon Sep 17 00:00:00 2001 From: Afzal Najam Date: Thu, 12 Sep 2024 19:45:12 -0400 Subject: [PATCH] Don't report when entries with multiple conditions and trailing comma --- .../com/doist/detekt/ConsistentWhenEntries.kt | 2 +- .../doist/detekt/ConsistentWhenEntriesTest.kt | 34 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/main/kotlin/com/doist/detekt/ConsistentWhenEntries.kt b/src/main/kotlin/com/doist/detekt/ConsistentWhenEntries.kt index 23c11ad..141ecc3 100644 --- a/src/main/kotlin/com/doist/detekt/ConsistentWhenEntries.kt +++ b/src/main/kotlin/com/doist/detekt/ConsistentWhenEntries.kt @@ -33,5 +33,5 @@ class ConsistentWhenEntries(config: Config) : Rule(config) { } } - private fun KtWhenEntry.isMultiline() = text.count { it == '\n' } > 1 + private fun KtWhenEntry.isMultiline() = (expression?.text?.count { it == '\n' } ?: 0) > 1 } diff --git a/src/test/kotlin/com/doist/detekt/ConsistentWhenEntriesTest.kt b/src/test/kotlin/com/doist/detekt/ConsistentWhenEntriesTest.kt index 09e8cea..6ee47f2 100644 --- a/src/test/kotlin/com/doist/detekt/ConsistentWhenEntriesTest.kt +++ b/src/test/kotlin/com/doist/detekt/ConsistentWhenEntriesTest.kt @@ -53,4 +53,38 @@ internal class ConsistentWhenEntriesTest(private val env: KotlinCoreEnvironment) val findings = rule.compileAndLintWithContext(env, code) findings shouldHaveSize 0 } + + @Test + fun `doesn't report single line when entries with multiple conditions and trailing comma`() { + val code = """ + val a = listOf() + val b = when(a) { + is ArrayList, + is MutableList, + -> true + else -> false + } + """ + val rule = ConsistentWhenEntries(Config.empty) + val findings = rule.compileAndLintWithContext(env, code) + findings shouldHaveSize 0 + } + + @Test + fun `report inconsistent when entries with multiple conditions and trailing comma`() { + val code = """ + val a = listOf() + val b = when(a) { + is ArrayList, + is MutableList, + -> { + true + } + else -> false + } + """ + val rule = ConsistentWhenEntries(Config.empty) + val findings = rule.compileAndLintWithContext(env, code) + findings shouldHaveSize 1 + } }