Tuesday, September 22, 2009

HOWTO Include Subversion version identifiers in your Java source code with Eclipse

It's often useful to include version markers in your source code files, especially when it's possible they will be distributed outside the bounds of a version control system. In my case, I'm using Subversion and Eclipse to write code.

Subversion provides keyword substitution for special keywords that are managed by Subversion during checkin an checkout. (See: http://svnbook.red-bean.com/en/1.5/svn.advanced.props.special.keywords.html). These include Date, HeadURL, Revision, Author, and Id (a combination of the others). You can embed these in your text files and SVN will automatically replace them with appropriate values each time. To enable this, you need to do the following:

svn propset svn:keywords "Id HeadURL Revision Author Date" foo.java

Then, you embed a keyword like "$Id" in your file and next time SVN updates your file, it will replace the $Id string with something like $Id: foo.java 148 2006-07-28 21:30:43Z sally $.

To make this easier, you might want to change the [auto-props] section of your config file to automatically set this property any time you create a new java file:

*.java: svn:keywords="
Id HeadURL Revision Author Date";svn:eol-style:native

Typically, this is embedded in a comment block. To make this easy, you can include it in your Eclipse file templates so things get pre-populated when you generate new files.

For general purpose insertion in all your Java source files, use Window > Preferences > Java > Code Style > Templates, then edit the "Files" entry and add the following to the template:

/*
*
* $$Id$$
*/

That will automatically insert the "$Id$" tag into any new source file you create.

Another reference:
http://wiki.collectionspace.org/display/collectionspace/Java+Source+Files+-+Beginning+Comments+Block+Template

For more advanced usage, you can embed a string in a variable that gets compiled into the object code and can be used to identify versions of binaries.

For Java, insert a piece of code that looks like this:

// version identifier automatically filled by svn:keywords "Id"
public static final String __class_id = "$Id$";

This will expand when the files are checked in to be representative of the version of code that was committed.

This can automatically be inserted in new classes with code templates, again. Window > Preferences > Java > Code Style > Templates > Code > Class body. (Make sure you use $$ for the dollar signs when you create the template.)

Pitfall: Make sure you have cleanly committed/updated files when you do this. Don't make the mistake of building your modified code that is checked out, then distributing it. Once you commit this code, the version number will bump up and potentially be different.


No comments:

Post a Comment