Question

I would like to write a generic Ant build script with a <copy> task that could optionally rename files based on regexps. A nested <regexpmapper> would load the renaming patterns from a project-specific properties files if it exists.

Has someone already done this or do I have to write an own mapper?

Was it helpful?

Solution

Here's an example of how you might do this.

Project properties file proj_props.txt contains:

use.filter=regexp.mapper
from.regexp=(.*)_test(.*)
to.regexp=\\1\\2

(Note the escapes \ in the to string.)

Buildfile:

<property file="proj_props.txt" />

<!-- filter for regexp -->    
<filtermapper id="regexp.mapper">
    <tokenfilter>
        <replaceregex pattern="${from.regexp}"
                      replace="${to.regexp}" />
    </tokenfilter>
</filtermapper>

<!-- identity filter, used when no regexp needed -->
<filtermapper id="identity.mapper" />

<!-- decide which filter to use -->
<condition property="chosen.mapper"
           value="regexp.mapper" else="identity.mapper">
    <isset property="use.filter" />
</condition>

<copy todir="...">
    <fileset>
       ...
    </fileset>
    <filtermapper refid="${chosen.mapper}" />
</copy>

You define a couple of filtermapper instances, one that carries out a regexp replace based on properties from the project properties file, the other that does nothing. The use.filter property decides which gets chosen. If the project properties file doesn't exist use.filter would not be set, so the 'do-nothing' identity filtermapper will be used.

Note that this only works when using nested resources in the copy task. If you only have one file to copy, and use <copy file="...", the filtermapper is ignored.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top