Loop through directory structure in ant - ant

We want to loop through directory structure in ant without using foreach .
Is there any elegant way to do the same ?

The apply task can iterate over a set of directories or files
<target name="run-apply">
<apply executable="echo">
<dirset dir="src"/>
</apply>
</target>
I personally like the groovy ANT task
<target name="run-groovy">
<taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy"/>
<dirset id="dirs" dir="src"/>
<groovy>
project.references.dirs.each {
ant.echo it
}
</groovy>
</target>
The installation of the task jar is easily automated:
<target name="install-groovy">
<mkdir dir="${user.home}/.ant/lib"/>
<get dest="${user.home}/.ant/lib/groovy-all.jar" src="http://search.maven.org/remotecontent?filepath=org/codehaus/groovy/groovy-all/2.1.1/groovy-all-2.1.1.jar"/>
</target>
Finally if you're iterating thru other build files, the subant task is very useful:
<target name="run-subant">
<subant>
<fileset dir="src" includes="**/build.xml"/>
</subant>
</target>

Short answer: Not really. There are ways around this, but I prefer the ant-contrib <for/> task for clarity and simplicity. With the <local/> task, you can now localize values of variables. Before, you sometimes had to use ant-contrib's <var/> task to reset the values, so you could loop through them over and over.
<for param="directory">
<fileset dir="${some.dir}"/>
<sequential>
<local name="foo"/>
<local name="bar"/> <!-- Properties that may change with each iteration -->
<!-- Here be dragons -->
</sequential>
</for>
It's clean, simple, and easy to understand. The big issue many people have with Ant Contrib is that not everyone may have it installed in their $ANT_HOME/lib directory. Far enough. So, if you use ant-contrib, put it as part of your project.
I'll put the ant-contrib jar in ${basedir}/antlib/antcontrib and then put this in my program:
<taskdef resource="net/sf/antcontrib/antlib.xml">
<classpath>
<fileset dir="${basedir}/antlib/antcontrib"/>
</classpath>
</taskdef>
Now, when someone checks out my project, they have ant-contrib already installed (since it's inside my project) and accessible (since I point my <taskdef> task at the location of ant-contrib.jar in my project).

Related

How to execute Ant build in command line

I have an Ant build file, and I try to execute it in the command line with the following command:
$ C:\Program Files (x86)\.....>ant -f C:\Silk4J\Automation\iControlSilk4J\build.xml
But nothing happens, and the result is:
BUILD SUCCESSFUL
Total time: 0 seconds
My environment variable is correct.
What is the problem? Here is my build file:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- WARNING: Eclipse auto-generated file.
Any modifications will be overwritten.
To include a user specific buildfile here, simply create one in the same
directory with the processing instruction <?eclipse.ant.import?>
as the first entry and export the buildfile again. -->
<project basedir="." default="build" name="iControlSilk4J">
<property environment="env"/>
<property name="ECLIPSE_HOME" value="../../../Program Files (x86)/Silk/SilkTest/eclipse"/>
<property name="junit.output.dir" value="junit"/>
<property name="debuglevel" value="source,lines,vars"/>
<property name="target" value="1.6"/>
<property name="source" value="1.6"/>
<path id="Silk Test JTF 13.5.0 Library.libraryclasspath">
<pathelement location="../../../Program Files (x86)/Silk/SilkTest/ng/JTF/silktest-jtf-nodeps.jar"/>
</path>
<path id="JUnit 4.libraryclasspath">
<pathelement location="${ECLIPSE_HOME}/plugins/org.junit_4.8.2.v4_8_2_v20110321-1705/junit.jar"/>
<pathelement location="${ECLIPSE_HOME}/plugins/org.hamcrest.core_1.1.0.v20090501071000.jar"/>
</path>
<path id="iControlSilk4J.classpath">
<pathelement location="bin"/>
<pathelement location="lib/apache-log4j.jar"/>
<pathelement location="lib/commons-io-2.4.jar"/>
<pathelement location="lib/commons-lang3-3.1.jar"/>
<pathelement location="lib/junit.jar"/>
<pathelement location="lib/org.hamcrest.core_1.1.0.v20090501071000.jar"/>
<pathelement location="lib/silktest-jtf-nodeps.jar"/>
<path refid="Silk Test JTF 13.5.0 Library.libraryclasspath"/>
<path refid="JUnit 4.libraryclasspath"/>
<pathelement location="../../../Users/Admin/Desktop/java-mail-1.4.4.jar"/>
<pathelement location="../../../Users/Admin/Desktop/javax.activation.jar"/>
<pathelement location="lib/joda-time-2.3.jar"/>
</path>
<target name="init">
<mkdir dir="bin"/>
<copy includeemptydirs="false" todir="bin">
<fileset dir="src">
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>
<target name="clean">
<delete dir="bin"/>
</target>
<target depends="clean" name="cleanall"/>
<target depends="build-subprojects,build-project" name="build"/>
<target name="build-subprojects"/>
<target depends="init" name="build-project">
<echo message="${ant.project.name}: ${ant.file}"/>
<javac debug="true" debuglevel="${debuglevel}" destdir="bin" source="${source}" target="${target}">
<src path="src"/>
<classpath refid="iControlSilk4J.classpath"/>
</javac>
</target>
<target description="Build all projects which reference this project. Useful to propagate changes." name="build-refprojects"/>
<target description="copy Eclipse compiler jars to ant lib directory" name="init-eclipse-compiler">
<copy todir="${ant.library.dir}">
<fileset dir="${ECLIPSE_HOME}/plugins" includes="org.eclipse.jdt.core_*.jar"/>
</copy>
<unzip dest="${ant.library.dir}">
<patternset includes="jdtCompilerAdapter.jar"/>
<fileset dir="${ECLIPSE_HOME}/plugins" includes="org.eclipse.jdt.core_*.jar"/>
</unzip>
</target>
<target description="compile project with Eclipse compiler" name="build-eclipse-compiler">
<property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter"/>
<antcall target="build"/>
...
Go to the Ant website and download. This way, you have a copy of Ant outside of Eclipse. I recommend to put it under the C:\ant directory. This way, it doesn't have any spaces in the directory names. In your System Control Panel, set the Environment Variable ANT_HOME to this directory, then pre-pend to the System PATHvariable, %ANT_HOME%\bin. This way, you don't have to put in the whole directory name.
Assuming you did the above, try this:
C:\> cd \Silk4J\Automation\iControlSilk4J
C:\Silk4J\Automation\iControlSilk4J> ant -d build
This will do several things:
It will eliminate the possibility that the problem is with Eclipe's version of Ant.
It is way easier to type
Since you're executing the build.xml in the directory where it exists, you don't end up with the possibility that your Ant build can't locate a particular directory.
The -d will print out a lot of output, so you might want to capture it, or set your terminal buffer to something like 99999, and run cls first to clear out the buffer. This way, you'll capture all of the output from the beginning in the terminal buffer.
Let's see how Ant should be executing. You didn't specify any targets to execute, so Ant should be taking the default build target. Here it is:
<target depends="build-subprojects,build-project" name="build"/>
The build target does nothing itself. However, it depends upon two other targets, so these will be called first:
The first target is build-subprojects:
<target name="build-subprojects"/>
This does nothing at all. It doesn't even have a dependency.
The next target specified is build-project does have code:
<target depends="init" name="build-project">
This target does contain tasks, and some dependent targets. Before build-project executes, it will first run the init target:
<target name="init">
<mkdir dir="bin"/>
<copy includeemptydirs="false" todir="bin">
<fileset dir="src">
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>
This target creates a directory called bin, then copies all files under the src tree with the suffix *.java over to the bin directory. The includeemptydirs mean that directories without non-java code will not be created.
Ant uses a scheme to do minimal work. For example, if the bin directory is created, the <mkdir/> task is not executed. Also, if a file was previously copied, or there are no non-Java files in your src directory tree, the <copy/> task won't run. However, the init target will still be executed.
Next, we go back to our previous build-project target:
<target depends="init" name="build-project">
<echo message="${ant.project.name}: ${ant.file}"/>
<javac debug="true" debuglevel="${debuglevel}" destdir="bin" source="${source}" target="${target}">
<src path="src"/>
<classpath refid="iControlSilk4J.classpath"/>
</javac>
</target>
Look at this line:
<echo message="${ant.project.name}: ${ant.file}"/>
That should have always executed. Did your output print:
[echo] iControlSilk4J: C:\Silk4J\Automation\iControlSilk4J\build.xml
Maybe you didn't realize that was from your build.
After that, it runs the <javac/> task. That is, if there's any files to actually compile. Again, Ant tries to avoid work it doesn't have to do. If all of the *.java files have previously been compiled, the <javac/> task won't execute.
And, that's the end of the build. Your build might not have done anything simply because there was nothing to do. You can try running the clean task, and then build:
C:\Silk4J\Automation\iControlSilk4J> ant -d clean build
However, Ant usually prints the target being executed. You should have seen this:
init:
build-subprojects:
build-projects:
[echo] iControlSilk4J: C:\Silk4J\Automation\iControlSilk4J\build.xml
build:
Build Successful
Note that the targets are all printed out in order they're executed, and the tasks are printed out as they are executed. However, if there's nothing to compile, or nothing to copy, then you won't see these tasks being executed. Does this look like your output? If so, it could be there's nothing to do.
If the bin directory already exists, <mkdir/> isn't going to execute.
If there are no non-Java files in src, or they have already been copied into bin, the <copy/> task won't execute.
If there are no Java file in your src directory, or they have already been compiled, the <java/> task won't run.
If you look at the output from the -d debug, you'll see Ant looking at a task, then explaining why a particular task wasn't executed. Plus, the debug option will explain how Ant decides what tasks to execute.
See if that helps.
Try running all targets individually to check that all are running correct
run ant target name to run a target individually
e.g. ant build-project
Also the default target you specified is
project basedir="." default="build" name="iControlSilk4J"
This will only execute build-subprojects,build-project and init
is it still actual?
As I can see you wrote <target depends="build-subprojects,build-project" name="build"/>, then you wrote <target name="build-subprojects"/> (it does nothing). Could it be a reason?
Does this <echo message="${ant.project.name}: ${ant.file}"/> print appropriate message? If no then target is not running.
Take a look at the next link http://www.sqaforums.com/showflat.php?Number=623277

Ant conditional if within a macrodef

Within ant, I have a macrodef.
Assuming I have to use this macrodef, and there is a item inside said macrodef that I want to run if the property special.property exists and is true, what do I do?
I currently have
<macrodef name="someName">
<sequential>
<someMacroDefThatSetsTheProerty />
<some:thingHereThatDependsOn if="special.property" />
<sequential>
</macrodef>
Which doesn't work - the some:thingHereThatDependsOn doesnt have an "if" attribute, and I cannot add one to it.
antcontrib is not available.
With a target I can give the target an "if", what can I do with a macrodef?
In Ant 1.9.1 and higher, there is now a new implementation of if and unless attributes. This might be what you're thinking of.
First, you need to put them into your namespace. Add them to your <project> header:
<project name="myproject" basedir="." default="package"
xmlns:if="ant:if"
xmlns:unless="ant:unless">
Now, you can add them to almost any Ant task or sub entity:
<!-- Copy over files from special directory, but only if it exists -->
<available property="special.dir.available"
file="${special.dir} type="dir"/>
<copy todir="${target.dir}>
<fileset dir="${special.dir}" if:true="special.dir.available"/>
<fileset dir="${other.dir}"/>
</copy>
<!-- FTP files over to host, but only if it's on line-->
<condition property="ftp.available">
<isreachable host="${ftp.host}"/>
</condition>
<ftp server="${ftp.host}"
userid="${userid}"
passowrd="${password}"
if:true="ftp.available">
<fileset dir=".../>
</ftp>
This is only possible if the ANT "thingHereThatDependsOn" task supports an "if" attribute.
As stated above, conditional execution in ANT, normally, only applies to targets.
<target name="doSomething" if="allowed.to.do.something">
..
..
</target>
<target name="doSomethingElse" unless="allowed.to.do.something">
..
..
</target>
<target name="go" depends="doSomething,doSomethingElse"/>

if else condition in ant task produces error

I have a scenario where i need to move a directory from one location to another. If the same directory exists in the destination folder i need to rename the directory name as oldname_1.
So i wrote a snippet as follows:
<target name="Move">
<IF>
<available file="${output.dir}" type="dir" />
<then>
<echo message="Directory exists" />
<rename src="${output.dir}" dest="${output.dir}_1"/>
<property name="newdirectory" value="${dest}"/>
</then>
<ELSE>
<echo message="Directory does not exist" />
</ELSE>
</IF>
<move file="${newdirectory}" todir="C:\reports" />
</target>
The error i am getting is :
Problem: failed to create task
Cause: The name is undefined.
Action: Check the spelling.
Action: Check that any custom tasks/types have been declared.
Action: Check that any / declarations have taken place.
As Ian Roberts has already mentioned, you need the Ant-Contrib jar, and then setup the <taskdef/> to point to this jar. I highly recommend putting it inside your project and checking it into your version control system. This way, when someone checks out your project, they already have the Ant-Contib.jar installed.
My standard is to put all optional jars required for the build (not jars required for compiling) in the directory ${basedir}/antlib, then put each optional jar in its own directory, so I would put ant-contrib-1.0b3.jar into ${basedir}/antlib/antcontrib.
Then I define the task this way:
<property name="antlib.dir" value="${basedir}/antlib"/>
<taskdef resource="net/sf/antcontrib/antlib.xml">
<classpath>
<fileset dir="${antlib.dir}/antcontrib"/>
</classpath>
</taskdef>
This way, if you update the jar file to a new version of the Ant-Contrib jar, you simply plug it into the directory. You don't have to update the build.xml.
Also note that I use net/sf/antcontrib/antlib.xml and not net/sf/antcontrib/antcontrib.properties. The XML file is what you should use. The directions for this are on the tasks page and differ from the ones on the main page under the installation directions. The reason is that the XML file has the correct definition for the <for> task, and the properties file does not.
However, there is another way to do if and unless in Ant 1.9.1 without the need for optional jar files. These are the new If and Unless entity attributes.
These can be placed in all tasks, or sub-entities, and can usually replace the Ant-Contrib if/else stuff:
<target name="move">
<available file="${output.dir}" type="dir"
property="output.dir.exists"/>
<echo message"Directory exists"
if:true="output.dir.exists"/>
<move file="${output.dir}" tofile="${output.dir}_1"
if:true="output.dir.exists"/>
<property name="newdirectory" value="${dest}"
if:true="output.dir.exists"/>
<echo message="Directory does not exists"
unless:true="output.dir.exists"/>
<move file="${newdirectory}" todir="C:\reports" />
</target>
Not so clean as your example. However, I would instead use the if= and unless= parameters on target names:
<target name="move.test">
<available file="${output.dir}" type="dir"
property="output.dir.exists"/>
</target>
<target name="move"
depends="move.test, move.exists, move.does.not exists">
<move file="${newdirectory}" todir="C:\reports" />
</target>
<target name="move.exists"
if="output.dir.exists">
<echo message="Directory exists" />
<move file="${output.dir}" tofile="${output.dir}_1"/>
<property name="newdirectory" value="${dest}"/>
</move.exists/>
<target name="move.does.not.exists"
unless="output.dir.exists"/>
<echo message="Directory does not exist" />
</target>
If you didn't echo everything, the structure would be a bit cleaner:
<target name="move.test">
<available file="${output.dir}" type="dir"
property="output.dir.exists"/>
</target>
<target name="move"
depends="move.test, backup">
<move file="${newdirectory}" todir="C:\reports" />
</target>
<target name="backup"
if="output.dir.exists">
<move file="${output.dir}" tofile="${output.dir}_1"/>
<property name="newdirectory" value="${dest}"/>
</move.exists/>
The if/else construct is not a native part of Ant out of the box, it is provided by the ant-contrib project, and you need to download a JAR and add the relevant <taskdef> to your build file. For example, if you download ant-contrib-1.0b3.jar and put it in a directory named build in the same directory as your build.xml, then you can say
<taskdef resource="net/sf/antcontrib/antcontrib.properties">
<classpath>
<pathelement location="build/ant-contrib-1.0b3.jar"/>
</classpath>
</taskdef>

Using a conditional length in ANT

I am currently trying to use the length task in ANT, more specifically making a conditional length task.
I want to to flag a message to a currently existing file if a file is greater than a set length, like so:
<project name="ant" default="check-filesize">
<target name="check-filesize">
<length mode="all" property="fs.length.bytes" when="gt" length="100">
<fileset dir="size" includes="*"/>
</length>
<echo>sorry your file set is to large</echo>
</target>
</project>
I have already written the code to print the size of all files in the directory but I haven't included it here to keep this brief.
If length does not allow for the echo tag can I perform this another way if not does any one know what the when tag does ? Obviously I only want the echo to happen when the condition is violated
Many thanks in advance
I discovered a way to do this using no external libraries, but thankyou for your help. here is how :
<project name="ant" default="check-filesize">
<target name="check-filesize">
<fail message="Your File Exceeds Limitations Please Operator For Full Size Of Data Set>
<condition>
<length length="1000" when="gt" mode="all" property="fs.length.bytes">
<fileset dir="size" includes="*"/>
</length>
</condition>
</fail>
</target>
</project>
Here is a way to conditionally echo a statement using Ant's built-in tasks:
<project name="ant-length" default="check-filesize">
<target name="check-filesize" depends="get-length, echo-if-large"/>
<target name="get-length">
<condition property="fs.length.too.large">
<length mode="all" when="gt" length="100">
<fileset dir="size" includes="*"/>
</length>
</condition>
</target>
<target name="echo-if-large" if="fs.length.too.large">
<echo>sorry your file set is too large</echo>
</target>
</project>
The third-party Ant-Contrib library has an <if> task that simplifies this.

How do I pass an argument to an Ant task?

I'm not very good with Ant, but we're using it as a build tool. Right now, we can run "ant test" and it'll run through all the unit tests.
However, I'd love to be able to do something like ant test some_module and have it accept some_module as a parameter, and only test that.
I haven't been able to find how to pass command line args to Ant - any ideas?
One solution might be as follows. (I have a project that does this.)
Have a separate target similar to test with a fileset that restricts the test to one class only. Then pass the name of that class using -D at the ant command line:
ant -Dtest.module=MyClassUnderTest single_test
In the build.xml (highly reduced):
<target name="single_test" depends="compile" description="Run one unit test">
<junit>
<batchtest>
<fileset dir="${test.dir}" includes="**/${test.module}.class" />
</batchtest>
</junit>
</target>
You can also define a property with an optional default value that can be replaced via command line, e.g.
<target name="test">
<property name="moduleName" value="default-module" />
<echo message="Testing Module: ${moduleName}"/>
....
</target>
and run it as:
ant test -DmoduleName=ModuleX
What about using some conditional in your test target and the specifying -Dcondition=true?
<target name="test" depends="_test, _test_if_true>
...
</target>
<target name="_test_if_true" if="condition">
...
</target>
<target name="_test" unless="condition">
...
</target>
Adapted a bit from the ant faq.
You can define a property on commandline when invoking ant:
ant -Dtest.module=mymodulename
Then you can use it as any other ant property:
...
<fileset dir="${test.dir}" includes="**/${test.module}.class" />
...
Have a look at Ant's manual.
I tried the solutions posted here for the very same original question. Yes just use ant -D<arg_name>. THe -D is a "keyword" I guess. I'm no ant expert and have not read the manuals in detail. Then inside the ant XML files can be accessed like: ${arg_name}
For instance you can have an argument name like: arg.myarg, so in XML ${arg.myarg}.
Ant really doesn't have parameters_ for the build file. I can think of a few ways to do this:
Use a special target to specify the tests. You can use the <for/> task from AntContrib to allow you to specify multiple tests. You'll need to download the Ant-Contrib jar file. I recommend placing it inside your project under the `${basedir}/antlib/antcontrib" directory. That way, when others checkout your project, they get the needed Ant-Contrib jar file.
<property name="antlib.dir" value="${basedir}/antlib"/>
<property name="antcontrib.dir" value="${antlib}/antcontrib"/>
<!-- Set up the ant contrib tasks for your use -->
<taskdef resource="net/sf/antcontrib/antlib.xml">
<classpath>
<fileset dir="${antcontrib.dir}"/>
</classpath>
</taskdef>
<target name="select-test"
description="Select the tests to run"
depends="test-compile"
if="junit-tests">
<for parameter="module"
list="${junit-tests}"
delimiter=" ">
<sequential>
<junit
fork="true"
...>
<batchtest todir="$target/unit-tests">
<fileset dir="${test.destdir}">
<include name="**/#{module}.class"/>
</fileset>
</junit>
</sequential>
</for>
</target>
You cab now run multiple tests like this:
$ ant -D"test-one test-two test-three" select-test
You could try this to access one target at a time. Add these lines to your build.xml file :
<project name="whatever" default="default">
<input message="Please select module:" addproperty="mod" />
<target name="default" depends="${mod}/>
...
</project>
This allows you to enter the module you want to execute and execute that itself instead of running the whole build.xml
You might need to make a few more changes to your build.xml for this to work perfectly.
For the arguments , there is Facility called property. You need to set the property. As in ANT plain arguments is taken as target name.
Lest say you have two modules in your project ModuleX and ModuleY where ModuleX has 2 testcases to run and ModuleY with 10 testcases.
You could do something like this :
ant runTestsOnModule -Dtestmodule="ModuleX"
OR to test all modules by calling
ant tests
<target name="runTestsOnModule">
<antCall target="testcase${testmodule}"/>
</target>'
<! -- run single module -->
<target name="runTestsOnModule">
<antCall target="testcase${testmodule}"/>
</target>
<!--run all tests-->
<target name="tests">
<antcall target="testcaseModuleX">
<antcall target="testCaseModuleY">
</target>
<target name="testcaseModuleX">
..run junit task to call 2 testcase
</target>
<target name="testcaseModuleY">
....run junit task to call 10 testcase
</target>

Categories

Resources