views:

93

answers:

4

I'm new to ant, and I want to require a file name if something other than the default target is used, so the calling syntax would be something like this:

ant specifictarget -Dfile=myfile

I'm using the ant contrib package to give me additional functionality, so I have this:

<if>
    <equals arg1="${file}" arg2="" />
     <then>
        <!-- fail here -->
     </then>
</if>

My thinking is that if file was not specified it might be equal to the empty string. Obviously, this didn't work, and I'm not finding any examples on google or the right syntax in the manual.

So what syntax should I use?

+1  A: 

You've got the right idea. The

ant specifictarget -Dfile=myfile

sets Ant Properties from the command line. All you really need is

<property name="file" value=""/>

for your default value. That way if file is not specified, it will be equal to the empty string.

Jweede
+1  A: 

Since properties are not mutable in Ant, you can add this:

<property name="file" value="" />

This will set the property file to an empty string if it hasn't already been set on the command line. Then your equality test will work as you intended.

Critical Failure
+1  A: 

Alternately, you can use escape the value since ant just spits out the actual text when it can't do a property substitution.

     <if>
       <equals arg1="${file}" arg2="$${file}" />
       <then>
         <echo>BARF!</echo>
       </then>
     </if>
seth
+3  A: 

You don't really need the contrib package. This is more conveniently done using built-in ant capabilities like if/unless and depends. See below:

    <target name="check" unless="file" description="check that the file property is set" >
        <fail message="set file property in the command line (e.g. -Dfile=someval)"/> 
    </target>

    <target name="specifictarget" if="file" depends="check" description=" " >
        <echo message="do something ${file}"/> 
    </target>
Was gonna write the same thing :-). An even shorter version would be "<fail unless='file' message='set file property...' />"
Matt Solnit
+1 Thanks, David and Matt. I ended up using the short version.
Keith Bentrup