views:

7045

answers:

4

Hello!

I want to execute a command from an Ant buildfile, for each file in a directory.
I am looking for a platform-independent solution.

How do I do this?

Sure, I could write a script in some scripting language, but this would add further dependencies to the project.

+7  A: 
blak3r
So, I have to include something? Or do I need some external ant lib? I'm getting *"Problem: failed to create task or type foreach"*. If I understand correctly, this means, **foreach** is an unknown keyword.
ivan_ivanovich_ivanoff
Ohhh lame... it's an Ant-Contrib Task. So, you have to install something. See here: http://ant-contrib.sourceforge.net/
blak3r
+2  A: 

ant-contrib is evil; write a custom ant task.

ant-contrib is evil because it tries to convert ant from a declarative style to an imperative style. But xml makes a crap programming language.

By contrast a custom ant task allows you to write in a real language (Java), with a real IDE, where you can write unit tests to make sure you have the behavior you want, and then make a clean declaration in your build script about the behavior you want.

This rant only matters if you care about writing maintainable ant scripts. If you don't care about maintainability by all means do whatever works. :)

Jtf

Jeffrey Fredrick
Your're right, I should just write a custom ant task in Java ;)
ivan_ivanovich_ivanoff
ant-contrib really is evil. Right now I'm in the middle of a large ant build project that makes intense use of if/then/else and antcalls and it really reads horrible. The whole thing looks like a converted batch/shell script and all the dependency stuff that ant does is completly turned off by the heavy use of ant-contrib.If you want to keep your setup clean, build your own task. :-/
cringe
+4  A: 

An approach without ant-contrib is suggested by Tassilo Horn (the original target is here)

Basicly, as there is no extension of <java> (yet?) in the same way that <apply> extends <exec>, he suggests to use <apply> (which can of course also run a java programm in a command line)

Here some examples:

  <apply executable="java"> 
    <arg value="-cp"/> 
    <arg pathref="classpath"/> 
    <arg value="-f"/> 
    <srcfile/> 
    <arg line="-o ${output.dir}"/> 

    <fileset dir="${input.dir}" includes="*.txt"/> 
  </apply>
Jmini
A: 

Use the <apply> task.

It executes a command once for each file. Specify the files by means of filesets or any other resource. <apply> is built-in; no additional dependency needed; no custom task implementation needed.

It's also possible to run the command only once, appending all files as arguments in one go. Use the parallel attribute to switch the behaviour.

Sorry for being late a year.

Alex