diff --git a/.gitignore b/.gitignore index 0a18ac0c..8db6fb48 100644 --- a/.gitignore +++ b/.gitignore @@ -107,6 +107,7 @@ Temporary Items /test/jte-runtime-test-gradle-convention/jte-classes/ /test/jte-runtime-test-gradle-kotlin-convention/jte-classes/ /test/jte-hotreload-test/jte-classes/ +/test/kte-runtime-test-gradle-kotlin-convention/jte-classes/ .run ### VS Code / VS Code Java extension (uses Eclipse code) ### diff --git a/jte-gradle-plugin/src/main/java/gg/jte/gradle/JteExtension.java b/jte-gradle-plugin/src/main/java/gg/jte/gradle/JteExtension.java index 0feab12d..210e9d6f 100644 --- a/jte-gradle-plugin/src/main/java/gg/jte/gradle/JteExtension.java +++ b/jte-gradle-plugin/src/main/java/gg/jte/gradle/JteExtension.java @@ -38,6 +38,7 @@ public JteExtension(ObjectFactory objectFactory) { public abstract ConfigurableFileCollection getCompilePath(); public abstract Property getHtmlPolicyClass(); public abstract Property getCompileArgs(); + public abstract Property getKotlinCompileArgs(); public abstract Property getProjectNamespace(); public abstract ListProperty getJteExtensions(); diff --git a/jte-gradle-plugin/src/main/java/gg/jte/gradle/PrecompileJteTask.java b/jte-gradle-plugin/src/main/java/gg/jte/gradle/PrecompileJteTask.java index 76a28ba1..169c4cb0 100644 --- a/jte-gradle-plugin/src/main/java/gg/jte/gradle/PrecompileJteTask.java +++ b/jte-gradle-plugin/src/main/java/gg/jte/gradle/PrecompileJteTask.java @@ -58,6 +58,17 @@ public void setCompileArgs(String[] compileArgs) { setterCalled(); } + @Input + @Optional + public String[] getKotlinCompileArgs() { + return extension.getKotlinCompileArgs().getOrNull(); + } + + public void setKotlinCompileArgs(String[] compileArgs) { + extension.getKotlinCompileArgs().set(compileArgs); + setterCalled(); + } + @TaskAction public void execute() { // Prevent Kotlin compiler to leak file handles, see https://github.com/casid/jte/issues/77 @@ -67,7 +78,7 @@ public void execute() { Logger logger = getLogger(); long start = System.nanoTime(); - Path sourceDirectory = getSourceDirectory(); + Path sourceDirectory = getSourceDirectory(); logger.info("Precompiling jte templates found in " + sourceDirectory); Path targetDirectory = getTargetDirectory(); @@ -85,6 +96,7 @@ public void execute() { templateEngine.setHtmlCommentsPreserved(Boolean.TRUE.equals(getHtmlCommentsPreserved())); templateEngine.setBinaryStaticContent(Boolean.TRUE.equals(getBinaryStaticContent())); templateEngine.setCompileArgs(getCompileArgs()); + templateEngine.setKotlinCompileArgs(getKotlinCompileArgs()); templateEngine.setTargetResourceDirectory(getTargetResourceDirectory()); int amount; diff --git a/jte-kotlin/src/main/java/gg/jte/compiler/kotlin/KotlinClassCompiler.java b/jte-kotlin/src/main/java/gg/jte/compiler/kotlin/KotlinClassCompiler.java index 3741086f..932c8492 100644 --- a/jte-kotlin/src/main/java/gg/jte/compiler/kotlin/KotlinClassCompiler.java +++ b/jte-kotlin/src/main/java/gg/jte/compiler/kotlin/KotlinClassCompiler.java @@ -32,6 +32,10 @@ public void compile(String[] files, List classPath, TemplateConfig confi compilerArguments.setClasspath(ClassUtils.join(classPath)); + if (config.kotlinCompileArgs != null) { + applyCompileArgs(compilerArguments, config.kotlinCompileArgs); + } + K2JVMCompiler compiler = new K2JVMCompiler(); SimpleKotlinCompilerMessageCollector messageCollector = new SimpleKotlinCompilerMessageCollector(templateByClassName, config.packageName); @@ -46,6 +50,15 @@ public void compile(String[] files, List classPath, TemplateConfig confi } } + private void applyCompileArgs(K2JVMCompilerArguments compilerArguments, String[] kotlinCompileArgs) { + for (int i = 0; i < kotlinCompileArgs.length; i++) { + if ("-jvm-target".equals(kotlinCompileArgs[i])) { + i++; + compilerArguments.setJvmTarget(kotlinCompileArgs[i]); + } + } + } + private static class SimpleKotlinCompilerMessageCollector implements MessageCollector { private final Map templateByClassName; diff --git a/jte-kotlin/src/test/java/gg/jte/kotlin/TemplateEngineTest.java b/jte-kotlin/src/test/java/gg/jte/kotlin/TemplateEngineTest.java index 280675ad..7f7433a7 100644 --- a/jte-kotlin/src/test/java/gg/jte/kotlin/TemplateEngineTest.java +++ b/jte-kotlin/src/test/java/gg/jte/kotlin/TemplateEngineTest.java @@ -1333,6 +1333,13 @@ void rawWithJavaScript() { "\n"); } + @Test + void kotlinCompileArgs() { + templateEngine.setKotlinCompileArgs("-jvm-target", "17"); + givenRawTemplate("@param model:gg.jte.kotlin.TemplateEngineTest.Model\nHello ${model.x}"); + thenOutputIs("Hello 42"); + } + private void givenTag(String name, String code) { dummyCodeResolver.givenCode("tag/" + name + ".kte", code); } diff --git a/jte-maven-plugin/src/main/java/gg/jte/maven/CompilerMojo.java b/jte-maven-plugin/src/main/java/gg/jte/maven/CompilerMojo.java index f4ec1ae8..e8419407 100644 --- a/jte-maven-plugin/src/main/java/gg/jte/maven/CompilerMojo.java +++ b/jte-maven-plugin/src/main/java/gg/jte/maven/CompilerMojo.java @@ -91,6 +91,12 @@ public class CompilerMojo extends AbstractMojo { @Parameter public String[] compileArgs; + /** + * Sets additional compiler arguments for kte templates. + */ + @Parameter + public String[] kotlinCompileArgs; + /** * The package name, where template classes are generated to. */ @@ -131,6 +137,7 @@ public void execute() { templateEngine.setHtmlCommentsPreserved(htmlCommentsPreserved); templateEngine.setBinaryStaticContent(binaryStaticContent); templateEngine.setCompileArgs(calculateCompileArgs()); + templateEngine.setCompileArgs(kotlinCompileArgs); int amount; try { diff --git a/jte-runtime/src/main/java/gg/jte/TemplateConfig.java b/jte-runtime/src/main/java/gg/jte/TemplateConfig.java index 87140c80..b1b75411 100644 --- a/jte-runtime/src/main/java/gg/jte/TemplateConfig.java +++ b/jte-runtime/src/main/java/gg/jte/TemplateConfig.java @@ -17,6 +17,7 @@ public class TemplateConfig { public final ContentType contentType; public final String packageName; public String[] compileArgs; + public String[] kotlinCompileArgs; public boolean trimControlStructures; public HtmlPolicy htmlPolicy = new OwaspHtmlPolicy(); public String[] htmlTags; diff --git a/jte-runtime/src/main/java/gg/jte/TemplateEngine.java b/jte-runtime/src/main/java/gg/jte/TemplateEngine.java index 52f6c7f4..bc1d887a 100644 --- a/jte-runtime/src/main/java/gg/jte/TemplateEngine.java +++ b/jte-runtime/src/main/java/gg/jte/TemplateEngine.java @@ -422,6 +422,17 @@ public void setCompileArgs(String ... compileArgs) { config.compileArgs = compileArgs; } + /** + * Sets additional compiler arguments for kte templates. + *
+ * This is a template compilation setting and has no effect when loading precompiled templates. + * Currently, only -jvm-target is supported. + * @param compileArgs for instance templateEngine.setCompileArgs("-jvm-target", "17"); + */ + public void setKotlinCompileArgs(String ... compileArgs) { + config.kotlinCompileArgs = compileArgs; + } + /** * Trims control structures, resulting in prettier output. *
diff --git a/test/gradle-test-wrapper/src/test/java/gg/jte/GradleMatrixTest.java b/test/gradle-test-wrapper/src/test/java/gg/jte/GradleMatrixTest.java index 3458edae..133c2a0f 100644 --- a/test/gradle-test-wrapper/src/test/java/gg/jte/GradleMatrixTest.java +++ b/test/gradle-test-wrapper/src/test/java/gg/jte/GradleMatrixTest.java @@ -34,7 +34,7 @@ private static List getTestGradleVersions() { public static Stream runGradleBuild() throws IOException { return Files.find(Paths.get(".."), 2, (p, attr) -> p.getFileName().toString().startsWith("settings.gradle")) .map(Path::getParent) - .filter(p -> p.getFileName().toString().startsWith("jte-runtime")) + .filter(p -> p.getFileName().toString().startsWith("jte-runtime") || p.getFileName().toString().startsWith("kte-runtime")) .flatMap(p -> GRADLE_VERSIONS.stream().map(v -> Arguments.arguments(p, v))); } diff --git a/test/kte-runtime-test-gradle-kotlin-convention/build.gradle.kts b/test/kte-runtime-test-gradle-kotlin-convention/build.gradle.kts new file mode 100644 index 00000000..613df8a6 --- /dev/null +++ b/test/kte-runtime-test-gradle-kotlin-convention/build.gradle.kts @@ -0,0 +1,32 @@ + +plugins { + kotlin("jvm") version "1.9.10" + id("gg.jte.gradle") version("3.1.4-SNAPSHOT") +} + +repositories { + mavenCentral() + mavenLocal() +} + +tasks.test { + useJUnitPlatform() +} + +dependencies { + implementation(kotlin("stdlib-jdk8")) + implementation("org.junit.jupiter:junit-jupiter:5.9.2") + implementation("gg.jte:jte-runtime:3.1.4-SNAPSHOT") +} + +jte { + precompile() + kotlinCompileArgs.set(arrayOf("-jvm-target", "17")) +} + +tasks.jar { + dependsOn(tasks.precompileJte) + from(fileTree("jte-classes") { + include("**/*.class") + }) +} \ No newline at end of file diff --git a/test/kte-runtime-test-gradle-kotlin-convention/gradle/wrapper/gradle-wrapper.jar b/test/kte-runtime-test-gradle-kotlin-convention/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..ccebba77 Binary files /dev/null and b/test/kte-runtime-test-gradle-kotlin-convention/gradle/wrapper/gradle-wrapper.jar differ diff --git a/test/kte-runtime-test-gradle-kotlin-convention/gradle/wrapper/gradle-wrapper.properties b/test/kte-runtime-test-gradle-kotlin-convention/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..fc10b601 --- /dev/null +++ b/test/kte-runtime-test-gradle-kotlin-convention/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.1-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/test/kte-runtime-test-gradle-kotlin-convention/gradlew b/test/kte-runtime-test-gradle-kotlin-convention/gradlew new file mode 100644 index 00000000..79a61d42 --- /dev/null +++ b/test/kte-runtime-test-gradle-kotlin-convention/gradlew @@ -0,0 +1,244 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/test/kte-runtime-test-gradle-kotlin-convention/gradlew.bat b/test/kte-runtime-test-gradle-kotlin-convention/gradlew.bat new file mode 100644 index 00000000..93e3f59f --- /dev/null +++ b/test/kte-runtime-test-gradle-kotlin-convention/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/test/kte-runtime-test-gradle-kotlin-convention/settings.gradle.kts b/test/kte-runtime-test-gradle-kotlin-convention/settings.gradle.kts new file mode 100644 index 00000000..588dcaf8 --- /dev/null +++ b/test/kte-runtime-test-gradle-kotlin-convention/settings.gradle.kts @@ -0,0 +1,6 @@ +pluginManagement { + repositories { + mavenLocal() + gradlePluginPortal() + } +} \ No newline at end of file diff --git a/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/.jteroot b/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/.jteroot new file mode 100644 index 00000000..e69de29b diff --git a/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/exceptionLineNumber1.kte b/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/exceptionLineNumber1.kte new file mode 100644 index 00000000..65591034 --- /dev/null +++ b/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/exceptionLineNumber1.kte @@ -0,0 +1,5 @@ +@import test.Model + +@param model:Model + +${model.getThatThrows()} \ No newline at end of file diff --git a/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/helloDataClass.kte b/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/helloDataClass.kte new file mode 100644 index 00000000..2cf9b520 --- /dev/null +++ b/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/helloDataClass.kte @@ -0,0 +1,2 @@ +@param model:test.DataClass +Hello ${model.name}, your id is ${model.id}. \ No newline at end of file diff --git a/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/helloInlineMethod.kte b/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/helloInlineMethod.kte new file mode 100644 index 00000000..efc9144b --- /dev/null +++ b/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/helloInlineMethod.kte @@ -0,0 +1,2 @@ +@param model:test.Model +${model.inlineMethod()} World \ No newline at end of file diff --git a/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/helloValueClass.kte b/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/helloValueClass.kte new file mode 100644 index 00000000..fb33fa7c --- /dev/null +++ b/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/helloValueClass.kte @@ -0,0 +1,2 @@ +@param model:test.ValueClass +${model.s()} World \ No newline at end of file diff --git a/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/helloValueClassTemplateCall.kte b/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/helloValueClassTemplateCall.kte new file mode 100644 index 00000000..91e9ef78 --- /dev/null +++ b/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/helloValueClassTemplateCall.kte @@ -0,0 +1,2 @@ +@param model:test.ValueClass +Calling template.. @template.tag.usesValueClass(model = model) \ No newline at end of file diff --git a/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/helloWorld.kte b/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/helloWorld.kte new file mode 100644 index 00000000..75a9dfc1 --- /dev/null +++ b/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/helloWorld.kte @@ -0,0 +1,2 @@ +@param model:test.Model +${model.hello} World \ No newline at end of file diff --git a/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/tag/unused.kte b/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/tag/unused.kte new file mode 100644 index 00000000..f5059592 --- /dev/null +++ b/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/tag/unused.kte @@ -0,0 +1,3 @@ +@param param1:String +@param param2:String +One is ${param1}, two is ${param2}. \ No newline at end of file diff --git a/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/tag/usesValueClass.kte b/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/tag/usesValueClass.kte new file mode 100644 index 00000000..5257f13e --- /dev/null +++ b/test/kte-runtime-test-gradle-kotlin-convention/src/main/jte/tag/usesValueClass.kte @@ -0,0 +1,2 @@ +@param model:test.ValueClass +you passed ${model.s()} \ No newline at end of file diff --git a/test/kte-runtime-test-gradle-kotlin-convention/src/main/kotlin/test/DataClass.kt b/test/kte-runtime-test-gradle-kotlin-convention/src/main/kotlin/test/DataClass.kt new file mode 100644 index 00000000..df4d0034 --- /dev/null +++ b/test/kte-runtime-test-gradle-kotlin-convention/src/main/kotlin/test/DataClass.kt @@ -0,0 +1,3 @@ +package test + +data class DataClass(val id: Long, val name: String) diff --git a/test/kte-runtime-test-gradle-kotlin-convention/src/main/kotlin/test/Model.kt b/test/kte-runtime-test-gradle-kotlin-convention/src/main/kotlin/test/Model.kt new file mode 100644 index 00000000..946908d8 --- /dev/null +++ b/test/kte-runtime-test-gradle-kotlin-convention/src/main/kotlin/test/Model.kt @@ -0,0 +1,13 @@ +package test + +@Suppress("unused") +class Model { + var hello:String = "" + fun getThatThrows():String { + throw NullPointerException() + } + + inline fun inlineMethod():String { + return "inline"; + } +} \ No newline at end of file diff --git a/test/kte-runtime-test-gradle-kotlin-convention/src/main/kotlin/test/ModelType.kt b/test/kte-runtime-test-gradle-kotlin-convention/src/main/kotlin/test/ModelType.kt new file mode 100644 index 00000000..7c168c8d --- /dev/null +++ b/test/kte-runtime-test-gradle-kotlin-convention/src/main/kotlin/test/ModelType.kt @@ -0,0 +1,6 @@ +package test + +@Suppress("unused") +enum class ModelType { + One, Two, Three +} \ No newline at end of file diff --git a/test/kte-runtime-test-gradle-kotlin-convention/src/main/kotlin/test/ValueClass.kt b/test/kte-runtime-test-gradle-kotlin-convention/src/main/kotlin/test/ValueClass.kt new file mode 100644 index 00000000..6c6fbd3c --- /dev/null +++ b/test/kte-runtime-test-gradle-kotlin-convention/src/main/kotlin/test/ValueClass.kt @@ -0,0 +1,8 @@ +package test + +@JvmInline +value class ValueClass(private val s: String) { + fun s() : String { + return s + } +} \ No newline at end of file diff --git a/test/kte-runtime-test-gradle-kotlin-convention/src/test/kotlin/test/TemplateEngineTest.kt b/test/kte-runtime-test-gradle-kotlin-convention/src/test/kotlin/test/TemplateEngineTest.kt new file mode 100644 index 00000000..3a565860 --- /dev/null +++ b/test/kte-runtime-test-gradle-kotlin-convention/src/test/kotlin/test/TemplateEngineTest.kt @@ -0,0 +1,117 @@ +package test + +import gg.jte.ContentType +import gg.jte.TemplateEngine +import gg.jte.TemplateException +import gg.jte.output.StringOutput +import gg.jte.runtime.TemplateUtils +import org.junit.jupiter.api.* +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import java.lang.NullPointerException +import java.nio.file.Path + +/** + * To run these tests, you first need to run the jte-gradle-plugin (jte:precompile) + */ +class TemplateEngineTest { + + companion object { + val templateEngine = TemplateEngine.createPrecompiled(Path.of("jte-classes"), ContentType.Html) + } + + val output = StringOutput() + val model = Model() + + @BeforeEach + internal fun setUp() { + model.hello = "Hello" + } + + @Test + internal fun helloWorld() { + whenTemplateIsRendered("helloWorld.kte") + thenOutputIs("Hello World") + } + + @Test + internal fun helloInlineMethod() { + whenTemplateIsRendered("helloInlineMethod.kte") // Inline method requires JDK-17 + thenOutputIs("inline World") + } + + @Test + internal fun helloValueClass() { + val exception:TemplateException = assertThrows { templateEngine.render("helloValueClass.kte", ValueClass("Hello valued"), output) } + assertEquals("Failed to render helloValueClass.kte, type mismatch for parameter: Expected java.lang.String, got test.ValueClass\n" + + "It looks like you're rendering a template with a Kotlin value class parameter. To make this work, pass the value class parameter in a map.\n" + + "Example: templateEngine.render(\"helloValueClass.kte\", mapOf(\"myValue\" to MyValueClass(), output)", exception.message) + } + + @Test + internal fun helloValueClass_map() { + templateEngine.render("helloValueClass.kte", mapOf("model" to ValueClass("Hello valued")), output) + thenOutputIs("Hello valued World") + } + + @Test + internal fun helloValueClassTemplateCall_map() { + templateEngine.render("helloValueClassTemplateCall.kte", mapOf("model" to ValueClass("Hello valued")), output) + thenOutputIs("Calling template.. you passed Hello valued") + } + + @Test + internal fun helloDataClass() { + templateEngine.render("helloDataClass.kte", DataClass(42, "data"), output) + thenOutputIs("Hello data, your id is 42.") + } + + @Test + internal fun helloDataClass_map() { + templateEngine.render("helloDataClass.kte", mapOf("model" to DataClass(42, "data")), output) + thenOutputIs("Hello data, your id is 42.") + } + + @Test + internal fun templateNotFound() { + val exception = thenRenderingFailsWithException("unknown.kte") + assertEquals("Failed to load unknown.kte", exception.message) + } + + @Test + internal fun exceptionLineNumber1() { + val exception = thenRenderingFailsWithException("exceptionLineNumber1.kte") + assertTrue(exception.cause is NullPointerException) + assertEquals("Failed to render exceptionLineNumber1.kte, error at exceptionLineNumber1.kte:5", exception.message) + } + + @Test + internal fun unusedTag() { + templateEngine.render("tag/unused.kte", TemplateUtils.toMap("param1", "One", "param2", "Two"), output) + thenOutputIs("One is One, two is Two.") + } + + @Test + internal fun params() { + val paramInfo = templateEngine.getParamInfo("tag/unused.kte") + assertEquals(2, paramInfo.size) + } + + @Test + internal fun paramWithWrongType() { + val exception = assertThrows { templateEngine.render("helloWorld.kte", TemplateUtils.toMap("model", "string"), output) } + assertTrue(exception.message!!.contains("Failed to render helloWorld.kte, error at helloWorld.kte:1")) + } + + private fun whenTemplateIsRendered(templateName: String) { + templateEngine.render(templateName, model, output) + } + + private fun thenRenderingFailsWithException(templateName: String): TemplateException { + return assertThrows { whenTemplateIsRendered(templateName) } + } + + private fun thenOutputIs(expected: String) { + assertEquals(expected, output.toString()) + } +} \ No newline at end of file