ANT: How to read property setted in a foreach loop

Lolablue picture Lolablue · Mar 16, 2011 · Viewed 19.5k times · Source

Dear, I currently face some problem to retrieve the value of a property setted in a foreach loop. Maybe one of you could help me...

The purpose is to check if one file of a folder has been modified since the corresponding jar has been generated. This way I know if I have to generate the jar again. What I do is to go through the folder with a foreach loop and if one file match my test, set a property to true.

The problem is that my variable doesn't seems to exist after my loop... Here is a simplified code example that has the same problem:

<target name="target">
    <taskdef resource="net/sf/antcontrib/antlib.xml" classpath="${lib.dir}/ant-contrib.jar"></taskdef>
    <foreach target="setVar" param="var" list="a,b"/>
    <echo>myreturn in target: ${env.myreturn}</echo>
    <property name="env.myreturn" value="c"/>
    <echo>myreturn in second: ${env.myreturn}</echo>
</target>
<target name="setVar">
    <property name="env.myreturn" value="${var}"/>
    <echo>myreturn in setVar: ${env.myreturn}</echo>
</target>

The result of this code is:

target:
setVar:
 [echo] myreturn in setVar: a
setVar:
 [echo] myreturn in setVar: b
 [echo] myreturn in target: ${env.myreturn}
 [echo] myreturn in second: c
BUILD SUCCESSFUL

It seems that the variable is correctly set as it could be printed in the "setVar" target but no way to retrieve value from the calling target.

I also know it's not possible to assign a value to a property twice. But the problem doesn't even occurs... When it'll be the case I could add a check on the value of the property before to assign it to be sure it is not already initialized...

Do you have a clue on the way I can solve my problem ???

Many thanks in advance for your help :)

Answer

Konstantin Komissarchik picture Konstantin Komissarchik · Mar 17, 2011

Try <for> task from ant-contrib instead of <foreach>. The <for> task takes advantage of Ant macro facility that came later. It works faster and is more flexible than the older <foreach> task. You are in the same project context when using <for>. That means properties set in the loop will be visible outside of the loop. Of course, normal rules for properties apply... you only get to set it once... unless you use <var> task from ant-contrib to overwrite or unset previously set properties.

Ah the joys of Ant hacking.