Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle trailing space on preceding line in call to lineLengthWithoutNewlinePrefix #2644

Merged
merged 1 commit into from
Apr 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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