Wednesday, September 10, 2008

Ant Wizardry

I've been spending a lot of time messing around with builds lately and that means reacquainting myself with my old friend, Ant. Back in the old days, I always wished there was an easy way to do simple string replacement/concatenation, creating a new property as a result. Sure you could use the antcontrib tasks, but I usually did not have access to them when it really counted and it was one more dependency to worry about. The other option is to mess with temporary files or some other naughty-feeling hackery (I think I used pathconvert once to do something like this and felt really dirty about it).

Anyway, as of Ant 1.7, check out what is possible. Run the following build file:


<project name="test" default="test">

<target name="test">

<loadresource property="abc">
<string value="One two three four" />
</loadresource>
<echo message="abc=${abc}" />

<loadproperties>
<string value="one=two${line.separator}three=four"/>
</loadproperties>
<echo message="one=${one}" />
<echo message="three=${three}" />

<loadresource property="test">
<string value="${one} two ${three} four" />
</loadresource>
<echo message="test=${test}" />

<loadresource property="test2">
<string value="${test}" />
<filterchain>
<replaceregex pattern="f(ou)r"
replace="f\1l"
flags="g"/>
</filterchain>
</loadresource>
<echo message="test2=${test2}" />

</target>

</project>


And you will see this output:


C:\testing\>ant -f testbuild.xml
Buildfile: testbuild.xml

test:
[echo] abc=One two three four
[echo] one=two
[echo] three=four
[echo] test=two two four four
[echo] test2=two two foul foul

BUILD SUCCESSFUL
Total time: 0 seconds


I wish I had this in my back pocket about four years ago...

4 comments:

nickb said...

Thanks for the tip! That's very handy for string concats and regex replacements! Time to move up to 1.7, I guess. :)

Anonymous said...

Ant 1.7.1 is out ;-)

Anonymous said...

Hi Mark:

My name is Mark Brand, we have just taken over an multiproject Eclipse app. I want to use a CI tool to build it automatically.

I saw one of your comments on a someone elses blog, and wondering if you are able to offer any tips about using ant4eclipse to build multipproject Eclipse apps.

Thanks
Mark
mark.a.brand@gmail.com

Mark Melvin said...

Hey Mark - I just sent you an email.