views:

20

answers:

1

Is there any way in an Ant script to use the <copy> task (replaceTokens) to preprocess Java files and replace a "__FILE__" string with the file name of the copied file and "__LINE__" with the line number in that file? This would go a long way toward solving Java's lack of a preprocessor.

The docs on replaceTokens show examples of fixed replacement strings, but I can't find any way to have Ant put in the file name and line number, respectively.

Do I need to write my own task handler?

A: 

Here's what I came up with. It does __LINE__, but not __FILE__. Oh well :-(.

<target name="preprocess" description="Preprocess the source code">
    <mkdir dir="${target.generated.dir}"/>
    <copy todir="${target.generated.dir}" includeemptydirs="true" failonerror="true" verbose="true">
        <fileset dir="${source.dir}">
            <exclude name="${source.main.resources.dir}"/>
        </fileset>
        <filterchain>
            <tokenfilter>
                <filetokenizer/>
                <scriptfilter language="beanshell" byline="true"><![CDATA[
                    import java.io.BufferedReader;
                    import java.io.StringReader;
                    int count = 1;
                    BufferedReader br = new BufferedReader(new StringReader(self.getToken()));
                    StringBuilder builder = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null) {
                        builder.append(line.replace("\"__LINE__\"", Integer.toString(count))).append('\n');
                        count++;
                    }
                    self.setToken(builder.toString());
                ]]></scriptfilter>
            </tokenfilter>
        </filterchain>
    </copy>
</target>
Ralph