Blog About Contact

Automatically Updating Your Source File Headers With Ant's ReplaceRegExp Task

Published Tue, 25 Aug 2009 • 2 comments

A while ago I was looking for a way to automatically be able to update the standard "flowerbox text" at the start of all the source files in our projects. Generally this is the space where you would include information about the source licensing and that sort of thing.

My "best case scenario" was there was a way to automate this with Subversion (or another source control system), similar to how the keywords substitution works for things like $Id$, etc.

The answer I accepted in the end was that you need to automate this substitution programmatically as part of the build process (or separate process).

As it turns out this is pretty straightforward to perform with Ant's ReplaceRegExp and LoadFile tasks...

<target name="replace_headers">
    <loadfile property="javaheader" srcFile="lib/standardheader.txt"/>
    <replaceregexp match="(/\*.*\*/.*)??^package " flags="sm"
        replace="${javaheader}${line.separator}package ">
        <fileset dir="src">
            <include name="**/*.java"/>
        </fileset>
    </replaceregexp>
</target>

So first of all we have placed our "standard text" in lib/standardheader.txt, and we then use a regular expression to find the first instance of a comment block (if one exists - optional) followed by the package header (I'm assuming .java source here, so you would modify the regex as required for other languages).

We use the LoadFile task to reader the text into a property used for replacement.

This is a very neat solution which can live in your build file ready to be used if your standard header text happens to change. You could apply the same type of trick to standardise class javadocs to include certain keywords such as $Id$ if were so inclined as well.


About the Author

Richard Nichols is an Australian software engineer with a passion for making things.

Follow him on twitter or subscribe by RSS or email.

You might also enjoy reading -


Discuss / Comment

There are 2 comments.

Add a comment

  • {{e.error}}

Thanks for your comment!/

Required.
Valid email address required.
Required.
Posting message, please wait...