Skip to content

Commit

Permalink
Insert spacing after annotation (#601)
Browse files Browse the repository at this point in the history
  • Loading branch information
yukukotani authored and Tapchicoma committed Oct 3, 2019
1 parent 3963a77 commit f82f133
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ package com.pinterest.ktlint.ruleset.experimental
import com.pinterest.ktlint.core.Rule
import com.pinterest.ktlint.core.ast.ElementType.MODIFIER_LIST
import com.pinterest.ktlint.core.ast.children
import com.pinterest.ktlint.core.ast.upsertWhitespaceBeforeMe
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.endOffset
import org.jetbrains.kotlin.psi.psiUtil.nextLeaf

/**
Expand Down Expand Up @@ -55,6 +57,15 @@ class AnnotationRule : Rule("annotation") {
.take(annotations.size)
.toList()

val noWhiteSpaceAfterAnnotation = whiteSpaces.isEmpty() || whiteSpaces.last().nextSibling is KtAnnotationEntry
if (noWhiteSpaceAfterAnnotation) {
emit(
annotations.last().endOffset - 1,
"Missing spacing after ${annotations.last().text}",
true
)
}

val multipleAnnotationsOnSameLineAsAnnotatedConstruct =
annotations.size > 1 && !whiteSpaces.last().textContains('\n')
val annotationsWithParametersAreNotOnSeparateLines =
Expand Down Expand Up @@ -86,11 +97,15 @@ class AnnotationRule : Rule("annotation") {
it.substring(it.lastIndexOf('\n'))
}

if (noWhiteSpaceAfterAnnotation) {
(annotations.last().nextLeaf() as LeafPsiElement).upsertWhitespaceBeforeMe(" ")
}
if (annotationsWithParametersAreNotOnSeparateLines) {
whiteSpaces.forEach {
(it as LeafPsiElement).rawReplaceWithText(newLineWithIndent)
}
} else if (multipleAnnotationsOnSameLineAsAnnotatedConstruct) {
}
if (multipleAnnotationsOnSameLineAsAnnotatedConstruct) {
(whiteSpaces.last() as LeafPsiElement).rawReplaceWithText(newLineWithIndent)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,23 @@ class AnnotationRuleTest {
)
}

@Test
fun `lint spacing after annotations`() {
assertThat(
AnnotationRule().lint(
"""
class A {
@SomeAnnotation("value")val x: String
}
""".trimIndent()
)
).containsExactly(
LintError(
2, 28, "annotation", "Missing spacing after @SomeAnnotation(\"value\")"
)
)
}

@Test
fun `lint annotations with params should not be placed on same line before annotated construct`() {
assertThat(
Expand Down

0 comments on commit f82f133

Please sign in to comment.