Borek Bernard
Borek Bernard

Reputation: 53281

Is there a way to dynamically build Ant elements from within an Ant script?

The question probably isn't very clear so let me illustrate what I mean with an example. Say that I want to copy a few folders:

<copy todir="..." overwrite="true">
    <fileset dir="dir1" />
    <fileset dir="dir2" />
    <fileset dir="dir3" />
    ...
</copy>

But instead of hardcoding those folders in a script, I need to load them from a text file that looks like this:

Directories to copy:
  dir1
  dir2
  dir3
  ...

So I somehow need to load the text file, parse it, find out which directories should be copied and the construct elements from it (<copy> and <fileset> are just examples).

Is it possible to achieve that from within Ant without executing some transformation (e.g., XSLT) on my build.xml file?

Upvotes: 3

Views: 1782

Answers (2)

Dan O
Dan O

Reputation: 6090

since you're not able to modify the format of the input text file, the best way I can think of doing what you want is to:

1.create a [shell|Perl|etc] script which generates XML from your original file. This can either be a snippet of XML or a complete Ant file.

2.run that script before invoking Ant.

3.import the generated XML into your Ant file (see the relevant Ant documentation at http://ant.apache.org/faq.html#xml-entity-include).

Upvotes: 2

ioscode
ioscode

Reputation: 821

The best way I can think of to accomplish what you want to do with ant is to use the ant contrib foreach task to read the file and act on each line. The ant targets would look something like this:

<taskdef resource="net/sf/antcontrib/antcontrib.properties" />
<path id="dirlists">
    <fileset dir="${basedir}/dirlists">
        <include name="**/*.txt" />
    </fileset>
</path>

<target name="runCopy">
    <foreach target="_copyDir" param="dirPath">
        <path refid="dirlists"/>
    </foreach>
</target>   

<target name="_copyDir">
    <copy todir="..." overwrite="true">
        <fileset dir="${dirPath}"/>
    </copy>
</target>

This will read any .txt files in a folder named dirlists, and for every line in each file do a copy from the dir specified by that line to the target dir ...

Upvotes: 0

Related Questions