Skip to content

Commit

Permalink
fix: expose found removable comments in a block (#23)
Browse files Browse the repository at this point in the history
This helps the caller decide whether to call rewritten function.
  • Loading branch information
wsutina authored Nov 26, 2024
1 parent 3f0592b commit 53aa489
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package cash.grammar.kotlindsl.utils

import cash.grammar.kotlindsl.model.Assignment
import cash.grammar.kotlindsl.parse.KotlinParseException
import cash.grammar.kotlindsl.parse.Parser
import cash.grammar.kotlindsl.parse.Rewriter
Expand Down Expand Up @@ -46,6 +47,14 @@ public class CommentsInBlockRemover private constructor(
private val rewriter = Rewriter(tokens)
private val indent = Whitespace.computeIndent(tokens, input)
private val comments = Comments(tokens, indent)
private val foundRemovableComments = mutableListOf<String>()

/**
* Retrieves the list of comments found in the block and can be removed from the script.
*
* @return A list of comments that are eligible for removal.
*/
public fun getFoundRemovableComments(): List<String> = foundRemovableComments

@Throws(KotlinParseException::class)
public fun rewritten(): String {
Expand All @@ -66,7 +75,11 @@ public class CommentsInBlockRemover private constructor(
allInlineComments += inlineComments
}

val nonInlineComments = comments.getCommentsInBlock(ctx).subtract(allInlineComments)
val allComments = comments.getCommentsInBlock(ctx)
foundRemovableComments.addAll(allComments.map { it.text })

// Delete non-inline comments
val nonInlineComments = allComments.subtract(allInlineComments)
nonInlineComments.forEach { token ->
rewriter.deleteWhitespaceToLeft(token)
rewriter.deleteNewlineToRight(token)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ class CommentsInBlockRemoverTest {
""".trimMargin()

// When
val rewrittenBuildScript = CommentsInBlockRemover.of(buildScript, "dependencies").rewritten()
val commentsInBlockRemover = CommentsInBlockRemover.of(buildScript, "dependencies")
val rewrittenBuildScript = commentsInBlockRemover.rewritten()

// Then
assertThat(rewrittenBuildScript).isEqualTo("""
Expand All @@ -42,5 +43,11 @@ class CommentsInBlockRemoverTest {
| // More comments
|}
""".trimMargin())
assertThat(commentsInBlockRemover.getFoundRemovableComments()).containsOnly(
"/* This is a block comment\n that spans multiple lines */",
"// This is an line comment",
"// This is a single-line comment",
"// This is another single-line comment",
)
}
}

0 comments on commit 53aa489

Please sign in to comment.