01 August 2006

My Ant Discovery for the Day

I love it when I discover or learn something new. Or discover something I should probably already know.

I wanted to make an Ant build file conditional on the O/S on which is was executing - so a target copies either the .bat or .sh scripts into a runtime directory.

I started out thinking of using the inbuilt property ${os.name} -- which returns the O/S name. But with Windows having more flavours than Ben and Jerry, I was finding it hard just to deal with all the Windows flavours in their own right. In a neat manner anyway.

So Google with various keywords related to what I wanted to do returned this Gem of a task which has been added to Ant in recent times -- <os family="windows" /> -- when combined with a condition, it can be used to set a property if the O/S is any flavour of Windows. And then that can be used with the <target> conditional attributes.

Exactly what I wanted!

<!-- Set IsWindows property IF the OS is from the Windows family -->
<condition property="IsWindows" value="true">
<os family="windows" />
</condition>

And then use this in the O/S specific targets

<target name="copy-windows-scripts"if="IsWindows">
<echo message="Copying Windows scripts"/>
...
</target>

<target name="copy-linux-unix-scripts" unless="IsWindows">
<echo message="Copying Linux/Unix Scripts"/>
...
</target>

And then use these in the main task and they will be conditionally executed.

<!-- Either the .bat or .sh scripts will be copied based on the os family -->
<antcall target="copy-windows-scripts"/>
<antcall target="copy-linux-unix-scripts"/>

2 comments:

Stefan Bodewig said...

"in recent times" is Ant 1.4 ;-)

Instead of using the antcalls I'd recommend something like

<target name="copy-scripts" depends="copy-windows-scripts,copy-linux-unix-scripts"/>

Princy said...

Thanks for your discovery.........saved my day.