diff --git a/src/main/kotlin/com/doist/detekt/NewLineAfterSuperCall.kt b/src/main/kotlin/com/doist/detekt/NewLineAfterSuperCall.kt new file mode 100644 index 0000000..fa621ca --- /dev/null +++ b/src/main/kotlin/com/doist/detekt/NewLineAfterSuperCall.kt @@ -0,0 +1,36 @@ +package com.doist.detekt + +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 org.jetbrains.kotlin.psi.KtNamedFunction + +class NewLineAfterSuperCall(config: Config = Config.empty) : Rule(config) { + override val issue = Issue( + javaClass.simpleName, + Severity.Style, + "Ensure there is a new line after every call to a super() method.", + Debt.FIVE_MINS + ) + + override fun visitNamedFunction(function: KtNamedFunction) { + super.visitNamedFunction(function) + + function.bodyBlockExpression?.statements?.forEachIndexed { index, statement -> + if (statement.text?.startsWith("super.") == true) { + if (statement.nextSibling.text.contains("\n\n")) return + report( + CodeSmell( + issue, + Entity.from(statement), + "There should be a new line after the call to super()." + ) + ) + } + } + } +} diff --git a/src/main/resources/config/config.yml b/src/main/resources/config/config.yml index 47662c1..f9e6e79 100644 --- a/src/main/resources/config/config.yml +++ b/src/main/resources/config/config.yml @@ -12,3 +12,5 @@ DoistRuleSet: TodoPattern: active: true pattern: '// TODO(.+): .*' + NewLineAfterSuperCall: + active: true diff --git a/src/test/kotlin/com/doist/detekt/NewLineAfterSuperCallTest.kt b/src/test/kotlin/com/doist/detekt/NewLineAfterSuperCallTest.kt new file mode 100644 index 0000000..023c9eb --- /dev/null +++ b/src/test/kotlin/com/doist/detekt/NewLineAfterSuperCallTest.kt @@ -0,0 +1,39 @@ +package com.doist.detekt + + +import io.gitlab.arturbosch.detekt.rules.KotlinCoreEnvironmentTest +import io.gitlab.arturbosch.detekt.test.lint +import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +@KotlinCoreEnvironmentTest +internal class NewLineAfterSuperCallTest(private val env: KotlinCoreEnvironment) { + @Test + fun `should report when there is no blank line after super() call`() { + val code = """ + override fun foo() { + super.foo() + bar.bazinga() + } + """ + + val findings = NewLineAfterSuperCall().lint(code) + assertEquals(1, findings.size) + assertEquals("There should be a new line after the call to super().", findings.first().message) + } + + @Test + fun `should not report when there is a blank line after super() call`() { + val code = """ + override fun foo() { + super.foo() + + bar.bazinga() + } + """ + + val findings = NewLineAfterSuperCall().lint(code) + assertEquals(0, findings.size) + } +}