Dynamic variable evaluations in copy task template


(mrichar2) #1

I’m looking for a way to dynamically evaluate variables in a copy task template.

Suppose version is dynamically generated to become 1.0.20161103155334.

Given the following defined in gradle.properties:

myprop=foo/bar:$version

I have a copy task:

task mytask(type: Copy, dependsOn: "build") {
	outputs.upToDateWhen { false }
	from 'src/main/resources'
	into "$buildDir/resources"
	include "mytemplate.json"
	expand ([version: "${version}", project: project])
}

mytemplate.json snippet:

<%
 // Simple example... my real code iterates over arrays dynamically
  def myprop = project.myprop;
%>
"key": "${myprop}"

I would like to evaluate myprop (which points to a variable that has variables within it). The above yields:

"key": "$version"

instead of
"key": "1.0.20161103155334"

I am intentionally putting myprop into gradle.properties even though it references another property (and that isn’t done automatically since gradle.properties is read as k/v string pairs) since a lot of other related non-dynamic properties are placed there already and I don’t want multiple locations to define properties.

I have found a way to do what I want using groovy.

<%
// dynamically evaluate variables that reference other variables
def _eval(str) {
	def engine = new groovy.text.SimpleTemplateEngine()
	def template = engine.createTemplate(str)
	return template.make(binding.variables).toString();
}
%>
...
<%
 // Simple example... my real code iterates over arrays dynamically
  def myprop = project.myprop;
%>
"key": "${_eval myprop}"

Results in:
"key": "1.0.20161103155334"

Is there a better or more native way?