Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save fikovnik/8b8bcf71aa864db954b84521c4646319 to your computer and use it in GitHub Desktop.

Select an option

Save fikovnik/8b8bcf71aa864db954b84521c4646319 to your computer and use it in GitHub Desktop.
Process freemarker template as a gradle task
package com.oracle.bacs
import freemarker.template.Configuration
import freemarker.template.TemplateException
import freemarker.template.TemplateExceptionHandler
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
/**
* Processes a freemarker {@code template} using given {@code properties},
* storing its output into an {@code output} file.
*/
class ProcessFreemarkerTemplateTask extends DefaultTask {
/**
* Path for the freemarker template. It can be either a relative path which will be resolved from the {@ projectDir}
* or absolute path.
*/
String template
/**
* Path for the output file. It can be either a relative path which will be resolved from the {@ projectDir}
* or absolute path.
*/
String output
Map<String, Object> properties
@TaskAction
def process() throws IOException, TemplateException {
assert template != null
assert output != null
assert properties != null
def cfg = new Configuration()
def templateFile = absoluteFile(template)
println(templateFile.getAbsolutePath())
cfg.setDirectoryForTemplateLoading(templateFile.getParentFile())
cfg.setDefaultEncoding("UTF-8")
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER)
def outputFile = absoluteFile(output)
logger.info("Processing ${templateFile.absolutePath} to ${outputFile.absolutePath}")
outputFile.withWriter { out ->
cfg.getTemplate(templateFile.getName()).process(properties, out)
}
}
private def absoluteFile(String fileName) {
def file = new File(fileName)
file.absolute ? file : new File(project.projectDir, fileName)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment