Iterating through a directory with Ant

Shaggy Frog picture Shaggy Frog · May 18, 2010 · Viewed 12.4k times · Source

Let's say I have a collection of PDF files with the following paths:

/some/path/pdfs/birds/duck.pdf
/some/path/pdfs/birds/goose.pdf
/some/path/pdfs/insects/fly.pdf
/some/path/pdfs/insects/mosquito.pdf

What I'd like to do is generate thumbnails for each PDF that respect the relative path structure, and output to another location, i.e.:

/another/path/thumbnails/birds/duck.png
/another/path/thumbnails/birds/goose.png
/another/path/thumbnails/insects/fly.png
/another/path/thumbnails/insects/mosquito.png

I'd like this to be done in Ant. Assume I'm going to use Ghostscript on the command line and I've already worked out the call to GS:

    <exec executable="${ghostscript.executable.name}">
        <arg value="-q"/>
        <arg value="-r72"/>
        <arg value="-sDEVICE=png16m"/>
        <arg value="-sOutputFile=${thumbnail.image.path}"/>
        <arg value="${input.pdf.path}"/>
    </exec>

So what I need to do is work out the correct values for ${thumbnail.image.path} and ${input.pdf.path} while traversing the PDF input directory.

I have access to ant-contrib (just installed the "latest", which is 1.0b3) and I'm using Ant 1.8.0. I think I can make something work using the <for> task, <fileset>s and <mapper>s, but I am having trouble putting it all together.

I tried something like:

    <for param="file">
        <path>
            <fileset dir="${some.dir.path}/pdfs">
                <include name="**/*.pdf"/>
            </fileset>
        </path>
        <sequential>
            <echo message="@{file}"/>
        </sequential>
    </for>

But unfortunately the @{file} property is an absolute path, and I can't find any simple way of decomposing it into the relative components.

If I can only do this using a custom task, I guess I could write one, but I'm hoping I can just plug together existing components.

Answer

martin clayton picture martin clayton · May 18, 2010

In the sequential task you could may be able to use the ant-contrib propertyregex task to map the input paths to output. For example:

<propertyregex override="yes" property="outfile" input="@{file}"
               regexp="/some/path/pdfs/(.*).pdf"
               replace="/another/path/\1.png" />

Which maps, for example /some/path/pdfs/birds/duck.pdf to /another/path/birds/duck.png.