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" />
<echo message="abc=${abc}" />

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

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

<loadresource property="test2">
<string value="${test}" />
<replaceregex pattern="f(ou)r"
<echo message="test2=${test2}" />



And you will see this output:

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

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

Total time: 0 seconds

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


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.


Mark Melvin said...

Hey Mark - I just sent you an email.