From c52b10bea3dd19449973078096a30e5f7409b612 Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Sun, 29 Oct 2017 19:26:09 -0400 Subject: [PATCH] Change import hoisting to only hoist imports in Kotlin blocks Prevents imports in plain text (e.g. a code sample) from unintentionally being hoisted) --- src/main/kotlin/net/shadowfacts/ekt/EKT.kt | 11 +++++++---- src/test/kotlin/net/shadowfacts/ekt/Test.kt | 16 +++++++++------- src/test/resources/templates/template.ekt | 4 ++++ 3 files changed, 20 insertions(+), 11 deletions(-) diff --git a/src/main/kotlin/net/shadowfacts/ekt/EKT.kt b/src/main/kotlin/net/shadowfacts/ekt/EKT.kt index 5028361..2a743b3 100644 --- a/src/main/kotlin/net/shadowfacts/ekt/EKT.kt +++ b/src/main/kotlin/net/shadowfacts/ekt/EKT.kt @@ -52,6 +52,13 @@ _result.toString() @Suppress("NAME_SHADOWING") var template = template + val lines = template.split("\n") + val isImport: (String) -> Boolean = { + val trimmed = it.trim() + trimmed.startsWith("[: import") || trimmed.startsWith("[:import") + } + val imports = lines.filter(isImport).joinToString("\n") { it.substring(2, it.length - 2) } + template = lines.filterNot(isImport).joinToString("\n") template = template.replace("$", "\${'$'}") template = ":]$template[:" template = template.replace(startStringRegex, { @@ -71,10 +78,6 @@ _result.toString() } }) - val lines = template.split("\n") - val imports = lines.filter { it.trim().startsWith("import") }.joinToString("\n") - template = lines.filterNot { it.trim().startsWith("import") }.joinToString("\n") - val script = imports + scriptPrefix + template + scriptSuffix if (env.cacheDir != null) { diff --git a/src/test/kotlin/net/shadowfacts/ekt/Test.kt b/src/test/kotlin/net/shadowfacts/ekt/Test.kt index a5e385f..1c5e8bc 100644 --- a/src/test/kotlin/net/shadowfacts/ekt/Test.kt +++ b/src/test/kotlin/net/shadowfacts/ekt/Test.kt @@ -8,14 +8,16 @@ import kotlin.concurrent.thread * @author shadowfacts */ fun main(args: Array) { - println(ManagementFactory.getRuntimeMXBean().name) + File("output.txt").writeText(render()) - for (i in 0..99) { - println("Rendering $i") - render() - } - - println("done") +// println(ManagementFactory.getRuntimeMXBean().name) +// +// for (i in 0..99) { +// println("Rendering $i") +// render() +// } +// +// println("done") // thread { // for (i in 0..30) { diff --git a/src/test/resources/templates/template.ekt b/src/test/resources/templates/template.ekt index 7cda184..8824124 100644 --- a/src/test/resources/templates/template.ekt +++ b/src/test/resources/templates/template.ekt @@ -8,6 +8,10 @@ Environment type: [= _env::class.simpleName =] Sum: [= list.sum() =] +
+	import a.b.c;
+
+ [: include("include") { "foo" to "bar"