From 37c3ff06f1d692295fa0121ca71550106d52b72f Mon Sep 17 00:00:00 2001 From: paul-dingemans Date: Mon, 11 Dec 2023 14:54:40 +0100 Subject: [PATCH] Disallow `else-if (..) ` as single line construct Closes #2420 --- .../standard/rules/MultiLineIfElseRule.kt | 9 ++++--- .../standard/rules/MultiLineIfElseRuleTest.kt | 26 +++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRule.kt b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRule.kt index 47eefde2a6..c5a1417dcc 100644 --- a/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRule.kt +++ b/ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRule.kt @@ -107,10 +107,13 @@ public class MultiLineIfElseRule : // Allow single line if statements as long as they are really simple (e.g. do not contain newlines) // if (...) // no else statement // if (...) else - return + if (node.treeParent.treeParent.elementType == ELSE) { + // Except in case nested if-else-if on single line + // if (...) else if (..) + } else { + return + } } - - Unit } emit(node.firstChildNode.startOffset, "Missing { ... }", true) diff --git a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRuleTest.kt b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRuleTest.kt index 3f973f3474..971f3c6e29 100644 --- a/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRuleTest.kt +++ b/ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/rules/MultiLineIfElseRuleTest.kt @@ -678,4 +678,30 @@ class MultiLineIfElseRuleTest { LintViolation(1, 53, "Missing { ... }"), ).isFormattedAs(formattedCode) } + + @Test + fun `Issue 2420 - Given a single line else-if`() { + val code = + """ + fun foo() { + if (foo) { + doFoo() + } else if (bar) doBar() + } + """.trimIndent() + val formattedCode = + """ + fun foo() { + if (foo) { + doFoo() + } else if (bar) { + doBar() + } + } + """.trimIndent() + multiLineIfElseRuleAssertThat(code) + .hasLintViolations( + LintViolation(4, 21, "Missing { ... }"), + ).isFormattedAs(formattedCode) + } }