Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing bug with AnnotationRule when annotation is preceeded by multiple newlines #552

Merged
merged 2 commits into from
Aug 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()
)
}
}