From d809453101b4e369e6a686267f4e71958a8257b8 Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Fri, 4 Aug 2017 16:56:49 -0400 Subject: [PATCH] Refactor some stuff, add comment tag --- src/main/kotlin/net/shadowfacts/ekt/EKT.kt | 39 +++++++++++++++------- 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/src/main/kotlin/net/shadowfacts/ekt/EKT.kt b/src/main/kotlin/net/shadowfacts/ekt/EKT.kt index 78e8f1e..44680d9 100644 --- a/src/main/kotlin/net/shadowfacts/ekt/EKT.kt +++ b/src/main/kotlin/net/shadowfacts/ekt/EKT.kt @@ -9,10 +9,19 @@ import javax.script.ScriptEngineManager */ object EKT { - private val startString = ":]" - private val endString = "[:" - private val startStringRegex = Regex("(?:^|[^\\\\])([:=])]\n?") - private val endStringRegex = Regex("\\[([:=])") + private val startControlCodes: Map String> = mapOf( + ":" to { s -> s }, + "=" to { s -> ")" + s }, + "#" to { s -> "*/" + s } + ) + private val endControlCodes: Map String> = mapOf( + ":" to { s -> s }, + "=" to { s -> s + "echo(" }, + "#" to { s -> s + "/*" } + ) + + private val startStringRegex = Regex("(?:^|[^\\\\])([:=#])]\n?") + private val endStringRegex = Regex("\\[([:=#])") private val scriptPrefix = """ val _result = StringBuilder() @@ -29,17 +38,23 @@ _result.toString() fun render(template: String, data: Map, dumpGeneratedScript: Boolean = false): String { @Suppress("NAME_SHADOWING") var template = template - template = template.replace("\"", "\\\"") - template = startString + template + endString + template = template.replace("\"", "\\\"").replace("$", "\${'$'}") + template = ":]$template[:" template = template.replace(startStringRegex, { - var res = "\necho(\"\"\"" - if (it.groups[1]!!.value == "=") res = ")" + res - res + val c = it.groups[1]!!.value + if (c in startControlCodes) { + startControlCodes[c]!!("\necho(\"\"\"") + } else { + throw RuntimeException("Unknown control code: [$c") + } }) template = template.replace(endStringRegex, { - var res = "\"\"\")\n" - if (it.groups[1]!!.value == "=") res += "echo(" - res + val c = it.groups[1]!!.value + if (c in endControlCodes) { + endControlCodes[c]!!("\"\"\")\n") + } else { + throw RuntimeException("Unknown control code: $c]") + } }) val script = scriptPrefix + template + scriptSuffix