73
votes

I can't figure out how to set an Ant property on the condition that it has not been set (i.e it is not defined in the properties file and should automatically default).

So far, I only have the following code:

<condition property="core.bin" value="../bin">
    <isset property="core.bin"/>
</condition>

But this only seems to work if the value is defined in a <property> tag.

Does anyone know how to conditionally set a property for the first time if it currently unset?

5

5 Answers

117
votes

You simply can set the property with the property-task. If the property is already set, the value is unchanged, because properties are immutable.

But you can also include 'not' in your condition:

<condition property="core.bin" value="../bin">
   <not>  
      <isset property="core.bin"/>
   </not>
</condition>
65
votes

Ant does this by default; if the property is already set; setting it again has no effect:

<project name="demo" default="demo">
    <target name="demo" >
        <property name="aProperty" value="foo" />
        <property name="aProperty" value="bar" /> <!-- already defined; no effect -->
        <echo message="Property value is '${aProperty}'" /> <!-- Displays 'foo' -->
    </target>
</project>

Gives

   /c/scratch> ant -f build.xml
Buildfile: build.xml

demo:
     [echo] Property value is '${aProperty}'

BUILD SUCCESSFUL
Total time: 0 seconds
/c/scratch> ant -f build.xml
Buildfile: build.xml

demo:
     [echo] Property value is 'foo'

BUILD SUCCESSFUL

Properties cannot be redefined; to do this you need to use something like the variable task from ant-contrib.

6
votes

The easiest way to do what you want:

<if>
    <not>
        <isset property="your.property"/>
    </not>
    <then>
        <property name="your.property" value="your.value"/>
    </then>
</if>
4
votes

There is support of using 'else' within : https://ant.apache.org/manual/Tasks/condition.html to serve your exact purpose.

else

The value to set the property to if the condition evaluates to false. By default the property will remain unset. Since Apache Ant 1.6.3

So change to :

<condition property="core.bin" else="../bin">
    <isset property="core.bin"/>
</condition>
2
votes

Properties in Ant are immutable. After defined they cannot be changed.

But the Ant Contrib package offers the variable task. It works like a property but the values can be modified and unset. Exmaple from the variable task documentation:

    <var name="x" value="6"/>
    <if>
        <equals arg1="${x}" arg2="6" />
        <then>
            <var name="x" value="12"/>
        </then>
    </if>
    <echo>${x}</echo>   <!-- will print 12 -->