Sorting filesets numerically in Ant
I have a folder structure like this:
wsdl/v1,----,v11
I need to copy all of its files to a new folder called "latestVersion" and I need to keep the copy order from v1 to v11. So for this I need to sort the directories by name during copying. My code looks like this:
<copy todir="${srcdist.layout.dir}/etc/wsdl/latestVersion" flatten="true" overwrite="true" verbose="true">
<sort>
<fileset dir="../../sdk/etc/wsdl">
<include name="**/*.wsdl"/>
</fileset>
</sort>
</copy>
I would like the copy to start at v1 and end at v11. However, it is copied like this:
v1,v10,v11,v2,v3,v4,v5,v6,v7,v8,v9
How, instead, I get Ant to copy, like:
v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11
source to share
You can use the JavaScript built into the Ant script to sort the directory names numerically.
Then you can use a <for>
task from the third party Ant -Contrib library to copy from sorted directories one at a time:
<dirset id="wsdl.dirs" dir="../../sdk/etc/wsdl" includes="v*"/>
<script language="javascript">
<![CDATA[
var dirSet = project.getReference( "wsdl.dirs" );
var ds = dirSet.getDirectoryScanner( project );
var includes = ds.getIncludedDirectories();
var versions = [];
for ( var i = 0; i < includes.length; i++ ) {
var dirname = includes[i]
// chop off the "v" from the front
var dirVersion = dirname.substr(1);
versions.push( dirVersion );
}
versionsSorted = versions.sort(function (a, b) {
return a - b;
});
// the "list" of <for> takes a comma-delimited string
project.setProperty( "versions", versionsSorted.join( ',' ) );
]]>
</script>
<echo>sorted versions: ${versions}</echo>
<for list="${versions}" param="version">
<sequential>
<copy todir="${srcdist.layout.dir}/etc/wsdl/latestVersion">
<fileset dir="../../sdk/etc/wsdl/v@{version}" includes="**/*.wsdl"/>
</copy>
</sequential>
</for>
source to share
Ant sorts correctly because it v10
precedes it v2
lexicographically (the comparator compares characters one by one).
To have v2
up v11
, you need to write your own comparator (the list of built-in comparators in the documentation is not enough). In other words, you have to write a class that implements the class org.apache.tools.ant.types.resources.comparators.ResourceComparator
, adds your class to the classpath, and declares it as a typedef in your Ant script:
<typedef name="my_custom_sort" classname="com.example.MyCustomResourceComparator" />
source to share