Skip to content

Commit d36ba8a

Browse files
committed
Extract adding advice to a reusable function
1 parent b17b6f3 commit d36ba8a

File tree

1 file changed

+13
-11
lines changed

1 file changed

+13
-11
lines changed

src/main/kotlin/com/autonomousapps/internal/parse/KotlinBuildScriptDependenciesRewriter.kt

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package com.autonomousapps.internal.parse
22

33
import cash.grammar.kotlindsl.model.DependencyDeclaration
4-
import cash.grammar.kotlindsl.parse.KotlinParseException
54
import cash.grammar.kotlindsl.parse.Parser
65
import cash.grammar.kotlindsl.parse.Rewriter
76
import cash.grammar.kotlindsl.utils.Blocks.isBuildscript
@@ -22,6 +21,7 @@ import com.squareup.cash.grammar.KotlinParser.ScriptContext
2221
import com.squareup.cash.grammar.KotlinParserBaseListener
2322
import org.antlr.v4.runtime.CharStream
2423
import org.antlr.v4.runtime.CommonTokenStream
24+
import org.antlr.v4.runtime.Token
2525
import java.nio.file.Path
2626

2727
/**
@@ -82,32 +82,34 @@ internal class KotlinBuildScriptDependenciesRewriter(
8282
}
8383

8484
override fun exitNamedBlock(ctx: NamedBlockContext) {
85-
dependencyExtractor.onExitBlock()
86-
8785
if (ctx.isDependencies && !inBuildscriptBlock) {
8886
hasDependenciesBlock = true
89-
advice.filterToSet { it.isAnyAdd() }.ifNotEmpty { addAdvice ->
90-
val closeBrace = ctx.stop
91-
rewriter.insertBefore(closeBrace, addAdvice.joinToString(separator = "\n", postfix = "\n") { a ->
92-
printer.toDeclaration(a)
93-
})
94-
}
87+
insertAdvice(advice, ctx.stop, withDependenciesBlock = false)
9588
}
9689

9790
// Must be last
9891
if (ctx.isBuildscript) {
9992
inBuildscriptBlock = false
10093
}
94+
95+
dependencyExtractor.onExitBlock()
10196
}
10297

10398
override fun exitScript(ctx: ScriptContext) {
10499
// Exit early if this build script has a dependencies block. If it doesn't, we may need to add missing dependencies.
105100
if (hasDependenciesBlock) return
106101

102+
insertAdvice(advice, ctx.stop, withDependenciesBlock = true)
103+
}
104+
105+
private fun insertAdvice(advice: Set<Advice>, beforeToken: Token, withDependenciesBlock: Boolean) {
106+
val prefix = if (withDependenciesBlock) "\ndependencies {\n" else ""
107+
val postfix = if (withDependenciesBlock) "\n}\n" else "\n"
108+
107109
advice.filterToOrderedSet { it.isAnyAdd() }.ifNotEmpty { addAdvice ->
108110
rewriter.insertBefore(
109-
ctx.stop,
110-
addAdvice.joinToString(prefix = "\ndependencies {\n", postfix = "\n}\n", separator = "\n") { a ->
111+
beforeToken,
112+
addAdvice.joinToString(prefix = prefix, postfix = postfix, separator = "\n") { a ->
111113
printer.toDeclaration(a)
112114
}
113115
)

0 commit comments

Comments
 (0)