Skip to content

Commit

Permalink
Fixing bug with AnnotationRule when annotation is preceeded by multip…
Browse files Browse the repository at this point in the history
…le newlines (pinterest#552)

* Fixing bug with AnnotationRule when annotation is preceeded by multiple newlines

* fix CI
  • Loading branch information
shashachu authored and sowmyav24 committed Aug 31, 2019
1 parent 908c5c2 commit 8064c88
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,12 @@ class AnnotationRule : Rule("annotation") {
autoCorrect: Boolean,
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit
) {
val root =
val modifierListRoot =
node.children().firstOrNull { it.elementType == MODIFIER_LIST }
?: return

val annotations =
root.children()
modifierListRoot.children()
.mapNotNull { it.psi as? KtAnnotationEntry }
.toList()
if (annotations.isEmpty()) {
Expand All @@ -50,7 +50,7 @@ class AnnotationRule : Rule("annotation") {
// @JvmField
// val s: Any
//
val whiteSpaces = (annotations.asSequence().map { it.nextSibling } + root.treeNext)
val whiteSpaces = (annotations.asSequence().map { it.nextSibling } + modifierListRoot.treeNext)
.filterIsInstance<PsiWhiteSpace>()
.take(annotations.size)
.toList()
Expand Down Expand Up @@ -78,10 +78,13 @@ class AnnotationRule : Rule("annotation") {
}

if (autoCorrect) {
val nodeBeforeAnnotations = root.treeParent.treePrev as? PsiWhiteSpace
val nodeBeforeAnnotations = modifierListRoot.treeParent.treePrev as? PsiWhiteSpace
// If there is no whitespace before the annotation, the annotation is the first
// text in the file
val newLineWithIndent = nodeBeforeAnnotations?.text ?: "\n"
val newLineWithIndent = (nodeBeforeAnnotations?.text ?: "\n").let {
// Make sure we only insert a single newline
it.substring(it.lastIndexOf('\n'))
}

if (annotationsWithParametersAreNotOnSeparateLines) {
whiteSpaces.forEach {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -391,4 +391,36 @@ class AnnotationRuleTest {
""".trimIndent()
assertThat(AnnotationRule().lint(code)).isEmpty()
}

@Test
fun `multiple newlines preceding annotation`() {
val code =
"""
fun foo() {
@Subscribe(threadMode = ThreadMode.MAIN) fun onEventMainThread(e: ModalContainer.ShowEvent) {
modalContainer?.show(e)
}
}
""".trimIndent()
assertThat(
AnnotationRule().format(code)
).isEqualTo(
"""
fun foo() {
@Subscribe(threadMode = ThreadMode.MAIN)
fun onEventMainThread(e: ModalContainer.ShowEvent) {
modalContainer?.show(e)
}
}
""".trimIndent()
)
}
}

0 comments on commit 8064c88

Please sign in to comment.