Skip to content

Commit

Permalink
Don't insert blank lines between line comments at the end of files
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
nreid260 committed May 17, 2023
1 parent 1936398 commit 85ea42a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
13 changes: 12 additions & 1 deletion core/src/test/java/com/facebook/ktfmt/format/FormatterTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -450,6 +450,17 @@ class FormatterTest {
|"""
.trimMargin())

assertFormatted(
"""
|// Comment as first element
|package foo
|// a
|
|/* Another comment */
|"""
.trimMargin())
}

@Test
fun `properties with line comment above initializer`() =
assertFormatted(
Expand Down

0 comments on commit 85ea42a

Please sign in to comment.