Created
May 8, 2016 20:11
-
-
Save fikovnik/8b8bcf71aa864db954b84521c4646319 to your computer and use it in GitHub Desktop.
Process freemarker template as a gradle task
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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