Skip to content

Commit

Permalink
Don't insert blank lines between line comments at the end of files (#401
Browse files Browse the repository at this point in the history
)

Summary:
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.

Pull Request resolved: #401

Reviewed By: strulovich

Differential Revision: D45943361

Pulled By: cgrushko

fbshipit-source-id: 6f2ed970a52b889cec9bfdcc06bd0cb7ae39b651
  • Loading branch information
nreid260 authored and facebook-github-bot committed May 30, 2023
1 parent 1936398 commit b6e5f35
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2390,16 +2390,22 @@ 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)
}

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
39 changes: 35 additions & 4 deletions core/src/test/java/com/facebook/ktfmt/format/FormatterTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -440,15 +440,46 @@ class FormatterTest {
deduceMaxWidth = true)

@Test
fun `don't keep adding newlines between these two comments when they're at end of file`() =
assertFormatted(
"""
fun `don't keep adding newlines between these two comments when they're at end of file`() {
assertFormatted(
"""
|package foo
|// a
|
|/* Another comment */
|"""
.trimMargin())
.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`() =
Expand Down

0 comments on commit b6e5f35

Please sign in to comment.