diff --git a/formatter/src/main/kotlin/org/kotlin/formatter/scanning/KotlinFileScanner.kt b/formatter/src/main/kotlin/org/kotlin/formatter/scanning/KotlinFileScanner.kt index 8cd0cfe..c9a80ac 100644 --- a/formatter/src/main/kotlin/org/kotlin/formatter/scanning/KotlinFileScanner.kt +++ b/formatter/src/main/kotlin/org/kotlin/formatter/scanning/KotlinFileScanner.kt @@ -13,12 +13,14 @@ import org.kotlin.formatter.scanning.nodepattern.nodePattern internal class KotlinFileScanner(private val kotlinScanner: KotlinScanner) : NodeScanner { private val nodePattern = nodePattern { + possibleWhitespaceWithComment() either { nonEmptyPackageDirective() thenMapToTokens { nodes -> kotlinScanner.scanNodes(nodes, ScannerState.BLOCK) } - possibleWhitespace() exactlyOne { + possibleWhitespace() + possibleWhitespaceWithComment() nodeOfType(KtNodeTypes.IMPORT_LIST) thenMapToTokens { nodes -> kotlinScanner.scanNodes(nodes, ScannerState.BLOCK) } diff --git a/formatter/src/test/kotlin/org/kotlin/formatter/KotlinFormatterTest.kt b/formatter/src/test/kotlin/org/kotlin/formatter/KotlinFormatterTest.kt index 6fe0857..418f0ab 100644 --- a/formatter/src/test/kotlin/org/kotlin/formatter/KotlinFormatterTest.kt +++ b/formatter/src/test/kotlin/org/kotlin/formatter/KotlinFormatterTest.kt @@ -3659,6 +3659,56 @@ class KotlinFormatterTest { ) } + @Test + fun `admits comments at the top of the file`() { + val subject = KotlinFormatter() + + val result = subject.format( + """ + /* A comment */ + package org.kotlin.formatter + + class MyClass + """.trimIndent() + ) + + assertThat(result).isEqualTo( + """ + /* A comment */ + package org.kotlin.formatter + + class MyClass + """.trimIndent() + ) + } + + @Test + fun `admits comments before the import list`() { + val subject = KotlinFormatter() + + val result = subject.format( + """ + package org.kotlin.formatter + + /* A comment */ + import apackage.AClass + + class MyClass : AClass + """.trimIndent() + ) + + assertThat(result).isEqualTo( + """ + package org.kotlin.formatter + + /* A comment */ + import apackage.AClass + + class MyClass : AClass + """.trimIndent() + ) + } + @Test fun `breaks before inheritance spec when necessary`() { val subject = KotlinFormatter(maxLineLength = 46)