From e8df680ead1213681fef84f5ac8da17899f3e4ed Mon Sep 17 00:00:00 2001 From: nickreid Date: Thu, 11 May 2023 09:19:17 -0700 Subject: [PATCH] Don't insert blank lines between line comments at the end of files There was already code/testing for this, but it wasn't covering a strange case where a comment was the first line of the file. --- .../ktfmt/format/KotlinInputAstVisitor.kt | 19 ++++++----- .../facebook/ktfmt/format/FormatterTest.kt | 33 ++++++++++++++++++- 2 files changed, 43 insertions(+), 9 deletions(-) diff --git a/core/src/main/java/com/facebook/ktfmt/format/KotlinInputAstVisitor.kt b/core/src/main/java/com/facebook/ktfmt/format/KotlinInputAstVisitor.kt index a8375222..c7be0376 100644 --- a/core/src/main/java/com/facebook/ktfmt/format/KotlinInputAstVisitor.kt +++ b/core/src/main/java/com/facebook/ktfmt/format/KotlinInputAstVisitor.kt @@ -2390,16 +2390,19 @@ class KotlinInputAstVisitor( override fun visitKtFile(file: KtFile) { markForPartialFormat() - var importListEmpty = false + val importListEmpty = file.importList?.text?.isBlank() ?: true + var isFirst = true for (child in file.children) { - if (child.text.isBlank()) { - importListEmpty = child is KtImportList - continue - } - if (!isFirst && child !is PsiComment && (child !is KtScript || !importListEmpty)) { - builder.blankLineWanted(OpsBuilder.BlankLineWanted.YES) - } + if (child.text.isBlank()) continue + + builder.blankLineWanted(when { + isFirst -> OpsBuilder.BlankLineWanted.NO + child is PsiComment -> OpsBuilder.BlankLineWanted.NO + child is KtScript && importListEmpty -> OpsBuilder.BlankLineWanted.PRESERVE + else -> OpsBuilder.BlankLineWanted.YES + }) + visit(child) isFirst = false } diff --git a/core/src/test/java/com/facebook/ktfmt/format/FormatterTest.kt b/core/src/test/java/com/facebook/ktfmt/format/FormatterTest.kt index 6d0c9616..90a019e3 100644 --- a/core/src/test/java/com/facebook/ktfmt/format/FormatterTest.kt +++ b/core/src/test/java/com/facebook/ktfmt/format/FormatterTest.kt @@ -440,7 +440,7 @@ class FormatterTest { deduceMaxWidth = true) @Test - fun `don't keep adding newlines between these two comments when they're at end of file`() = + fun `don't keep adding newlines between these two comments when they're at end of file`() { assertFormatted( """ |package foo @@ -450,6 +450,37 @@ class FormatterTest { |""" .trimMargin()) + assertFormatted( + """ + |// Comment as first element + |package foo + |// a + | + |/* Another comment */ + |""" + .trimMargin()) + + assertFormatted( + """ + |// Comment as first element then blank line + | + |package foo + |// a + | + |/* Another comment */ + |""" + .trimMargin()) + + assertFormatted( + """ + |// Comment as first element + |package foo + |// Adjacent line comments + |// Don't separate + |""" + .trimMargin()) + } + @Test fun `properties with line comment above initializer`() = assertFormatted(