Skip to content

Commit

Permalink
Consider comments when searching for multiline annotations (#499)
Browse files Browse the repository at this point in the history
* Consider comments when searching for multiline annotations

* Make sure the annotated statement is really not on the same line regardless of a comment
  • Loading branch information
arturbosch authored and shashachu committed Jul 15, 2019
1 parent 215056a commit 1fc0836
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ import com.pinterest.ktlint.core.Rule
import com.pinterest.ktlint.core.ast.ElementType.MODIFIER_LIST
import com.pinterest.ktlint.core.ast.children
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.PsiComment
import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.psiUtil.nextLeaf

class AnnotationRule : Rule("annotation") {

Expand Down Expand Up @@ -52,7 +54,8 @@ class AnnotationRule : Rule("annotation") {
annotations.size > 1 && !whiteSpaces.last().textContains('\n')
val annotationsWithParametersAreNotOnSeparateLines =
annotations.any { it.valueArgumentList != null } &&
!whiteSpaces.all { it.textContains('\n') }
!whiteSpaces.all { it.textContains('\n') } &&
doesNotEndWithAComment(whiteSpaces)

if (multipleAnnotationsOnSameLineAsAnnotatedConstruct) {
emit(
Expand Down Expand Up @@ -84,4 +87,9 @@ class AnnotationRule : Rule("annotation") {
}
}
}

private fun doesNotEndWithAComment(whiteSpaces: List<PsiWhiteSpace>): Boolean {
val lastNode = whiteSpaces.lastOrNull()?.nextLeaf()
return lastNode !is PsiComment || lastNode.nextLeaf()?.textContains('\n') == false
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,40 @@ class AnnotationRuleTest {
).isEmpty()
}

@Test
fun `lint single annotation with parameters ends with a comment`() {
assertThat(
AnnotationRule().lint(
"""
@Suppress("AnnotationRule") // this is a comment
class A
""".trimIndent()
)
).isEmpty()
}

@Test
fun `lint single annotation with parameters on the same line with a comment`() {
assertThat(
AnnotationRule().lint(
"""
@Suppress("AnnotationRule") /* this is a comment */ class A
""".trimIndent()
)
).hasSize(1)
}

@Test
fun `lint single annotation with parameters on the same line with a comment and many spaces`() {
assertThat(
AnnotationRule().lint(
"""
@Suppress("AnnotationRule") /* this is a comment */ class A
""".trimIndent()
)
).hasSize(1)
}

@Test
fun `format single annotation may be placed on line before annotated construct`() {
val code =
Expand Down

0 comments on commit 1fc0836

Please # to comment.