R – How to turn directories to .jar files with Ant

antjar

How to turn a list of directories into a list of .jar files ?
It seems that using Copy Task and Mappers is the right way to do this but I did not find any nested element creating a jar file from a directory.

Of course, the list of directories would be computed and not hard coded in the ant script.

For instance, a foo directory contains bar1, bar2 and bar3 directories. The script would create bar1.jar from the bar1 dir, bar2.jar from bar2 dir and bar3.jar from bar3 dir
The script would create a bar4.jar from a newly added bar4 directory without any change in the script (no hardcoded list).

Thanks ahead for your help

Best Answer

You can use the subant task to do this. For example:

<project name="jars" default="jar" basedir=".">
    <property name="dir.build" value="${basedir}/build"/>
    <property name="dir.root" value="${basedir}/foo"/>

    <target name="init">
        <tstamp/>
        <mkdir dir="${dir.build}"/>
    </target>

    <target name="jar" depends="init">
        <!-- ${ant.file} is the name of the current build file -->
        <subant genericantfile="${ant.file}" target="do-jar">

            <!-- Pass the needed properties to the subant call. You could also use
                 the inheritall attribute on the subant element above to pass all
                 properties. -->
            <propertyset>
                <propertyref name="dir.build"/>
            </propertyset>

            <!-- subant will call the "do-jar" target for every directory in the
                 ${dir.root} directory, making the subdirectory the basedir. -->
            <dirset dir="${dir.root}" includes="*"/>
        </subant>
    </target>

    <target name="do-jar">
        <!-- Get the basename of the basedir (bar1, bar2, etc.) -->
        <basename file="${basedir}" property="jarname"/>

        <jar jarfile="${dir.build}/${jarname}.jar" basedir="${basedir}"/>
    </target>
</project>
Related Topic