Skip to content

Commit

Permalink
Handle trailing space on preceding line in call to `lineLengthWithout…
Browse files Browse the repository at this point in the history
…NewlinePrefix` (#2644)
  • Loading branch information
paul-dingemans authored Apr 27, 2024
1 parent 0d431e4 commit 1d41320
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -502,7 +502,7 @@ public fun ASTNode.lineLength(excludeEolComment: Boolean = false): Int = leavesO
*/
public fun Sequence<ASTNode>.lineLengthWithoutNewlinePrefix(): Int {
val first = firstOrNull() ?: return 0
require(first.text.startsWith('\n') || first.prevLeaf() == null) {
require(first.textContains('\n') || first.prevLeaf() == null) {
"First node in non-empty sequence must be a whitespace containing a newline"
}
return joinToString(separator = "") { it.text }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPE_REFERENCE
import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_PARAMETER
import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_PARAMETER_LIST
import com.pinterest.ktlint.rule.engine.core.api.ElementType.WHITE_SPACE
import com.pinterest.ktlint.test.SPACE
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatNoException
import org.assertj.core.api.Assertions.entry
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.lang.FileASTNode
Expand Down Expand Up @@ -761,6 +763,30 @@ class ASTNodeExtensionTest {
" val foo4".length,
)
}

@Suppress("DEPRECATION")
@Test
fun `xxGiven some lines containing identifiers at different indentation levels then get line length exclusive the leading newline characters until and including the identifier`() {
val code =
"""
val foo1 = "foo1"$SPACE
val foo2 = "foo2"
""".trimIndent()

assertThatNoException()
.isThrownBy {
transformCodeToAST(code)
.firstChildLeafOrSelf()
.leaves()
.filter { it.elementType == IDENTIFIER }
.map { identifier ->
identifier
.leavesOnLine()
.takeWhile { it.prevLeaf() != identifier }
.lineLengthWithoutNewlinePrefix()
}.toList()
}
}
}

@Nested
Expand Down

0 comments on commit 1d41320

Please # to comment.