Refactor some stuff, add comment tag

This commit is contained in:
Shadowfacts 2017-08-04 16:56:49 -04:00
parent 6378d6cdc7
commit d809453101
Signed by: shadowfacts
GPG Key ID: 94A5AB95422746E5
1 changed files with 27 additions and 12 deletions

View File

@ -9,10 +9,19 @@ import javax.script.ScriptEngineManager
*/ */
object EKT { object EKT {
private val startString = ":]" private val startControlCodes: Map<String, (String) -> String> = mapOf(
private val endString = "[:" ":" to { s -> s },
private val startStringRegex = Regex("(?:^|[^\\\\])([:=])]\n?") "=" to { s -> ")" + s },
private val endStringRegex = Regex("\\[([:=])") "#" to { s -> "*/" + s }
)
private val endControlCodes: Map<String, (String) -> String> = mapOf(
":" to { s -> s },
"=" to { s -> s + "echo(" },
"#" to { s -> s + "/*" }
)
private val startStringRegex = Regex("(?:^|[^\\\\])([:=#])]\n?")
private val endStringRegex = Regex("\\[([:=#])")
private val scriptPrefix = """ private val scriptPrefix = """
val _result = StringBuilder() val _result = StringBuilder()
@ -29,17 +38,23 @@ _result.toString()
fun render(template: String, data: Map<String, Any>, dumpGeneratedScript: Boolean = false): String { fun render(template: String, data: Map<String, Any>, dumpGeneratedScript: Boolean = false): String {
@Suppress("NAME_SHADOWING") @Suppress("NAME_SHADOWING")
var template = template var template = template
template = template.replace("\"", "\\\"") template = template.replace("\"", "\\\"").replace("$", "\${'$'}")
template = startString + template + endString template = ":]$template[:"
template = template.replace(startStringRegex, { template = template.replace(startStringRegex, {
var res = "\necho(\"\"\"" val c = it.groups[1]!!.value
if (it.groups[1]!!.value == "=") res = ")" + res if (c in startControlCodes) {
res startControlCodes[c]!!("\necho(\"\"\"")
} else {
throw RuntimeException("Unknown control code: [$c")
}
}) })
template = template.replace(endStringRegex, { template = template.replace(endStringRegex, {
var res = "\"\"\")\n" val c = it.groups[1]!!.value
if (it.groups[1]!!.value == "=") res += "echo(" if (c in endControlCodes) {
res endControlCodes[c]!!("\"\"\")\n")
} else {
throw RuntimeException("Unknown control code: $c]")
}
}) })
val script = scriptPrefix + template + scriptSuffix val script = scriptPrefix + template + scriptSuffix