11package com.autonomousapps.internal.parse
22
33import cash.grammar.kotlindsl.model.DependencyDeclaration
4- import cash.grammar.kotlindsl.parse.KotlinParseException
54import cash.grammar.kotlindsl.parse.Parser
65import cash.grammar.kotlindsl.parse.Rewriter
76import cash.grammar.kotlindsl.utils.Blocks.isBuildscript
@@ -22,6 +21,7 @@ import com.squareup.cash.grammar.KotlinParser.ScriptContext
2221import com.squareup.cash.grammar.KotlinParserBaseListener
2322import org.antlr.v4.runtime.CharStream
2423import org.antlr.v4.runtime.CommonTokenStream
24+ import org.antlr.v4.runtime.Token
2525import 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) " \n dependencies {\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 = " \n dependencies { \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