tags:

views:

1481

answers:

3

I need to increment a number in a source file from an ant build script. I can use the ReplaceRegExp task to find the number I want to increment, but how do I then increment that number within the replace attribute?

Heres what I've got so far:

<replaceregexp file="${basedir}/src/path/to/MyFile.java"
    match="MY_PROPERTY = ([0-9]{1,});"
    replace="MY_PROPERTY = \1;"/>

In the replace attribute, how would I do

replace="MY_PROPERTY = (\1 + 1);"

I can't use the buildnumber task to store the value in a file since I'm already using that within the same build target. Is there another ant task that will allow me to increment a property?

+2  A: 

You can use something like:

<propertyfile file="${version-file}"> <entry key="revision" type="string" operation="=" value="${revision}" /> <entry key="build" type="int" operation="+" value="1" />

so the ant task is propertyfile.

Yuval F
A: 

Good question, it can be done in perl similar to that, but I think its not possible in ant, .NET and other areas.. If I'm wrong, I'd really like to know, because that's a cool concept that I've used in Perl many times that I could really use in situations like you've mentioned.

stephenbayer
+2  A: 

In ant, you've always got the fallback "script" tag for little cases like this that don't quite fit into the mold. Here's a quick (messy) implementation of the above:

    <property name="propertiesFile" location="test-file.txt"/>

    <script language="javascript">
        regex = /.*MY_PROPERTY = (\d+).*/;

        t = java.io.File.createTempFile('test-file', 'txt');
        w = new java.io.PrintWriter(t);
        f = new java.io.File(propertiesFile);
        r = new java.io.BufferedReader(new java.io.FileReader(f));
        line = r.readLine();
        while (line != null) {
            m = regex.exec(line);
            if (m) {
                val = parseInt(m[1]) + 1;
                line = 'MY_PROPERTY = ' + val;
            }
            w.println(line);
            line = r.readLine();
        }
        r.close();
        w.close();

        f.delete();
        t.renameTo(f);
    </script>
bsanders
Not come across the script tag before, thanks for pointing it out! I do think using the <propertyfile> is better though.
roryf