jakub holý

building the right thing, building it right, fast

Ant/Maven: Add build date/revision to the generated JAR''s Manifest

2006-10-19Tools

I'll explain how to get build time info and svn revision into the buildedjar/ear in Maven or Ant.


1. Maven



If you want to have the build date of a JAR built by Maven in its Manifest file, paste the following lines at the beginning of your maven.xml:

<tstamp/>
<j:set value="JarBuildDate var="maven.jar.manifest.attributes.list" />
<j:set value="${DSTAMP}" var="maven.jar.manifest.attribute.JarBuildDate" />


Explication:

  1. <tstamp/> executes the Ant's task Tstamp, which defines the variables DSTAMP (date in the form YYYYMMDD), TODAY (MMMM dd yyyy) and TSTAMP (hhmm).
  2. The property maven.jar.manifest.attributes.list tells the jar:jar goal what entries to add into the resulting manifest. Attention: value="JarBuildDate" and =" JarBuildDate" define 2 different variables, i.e. whitespaces are very significant. You must also comply with the definition of valid manifest entriy names. The variable may hold multiple entries separated by a comma. Side note: what happens, if the variable is already set? Is the old value preserved or overwritten?
  3. maven.jar.manifest.attribute.JarBuildDate sets the value for the manifest entry defined in the ...list property.


2. Ant

<!-- Create manifest with build time info -->
<manifest file="ear-MANIFEST.MF">
                 <attribute name="MyBuild-Date" value="${DSTAMP}" />
                 <attribute name="MyBuild-Time" value="${TSTAMP}" />
                 <attribute name="MyBuild-Svn-Revision" value="${svn.version}" />
</manifest>

<jar manifest="ear-MANIFEST.MF" .. /> <!-- the same for an <ear .. -->


Explanation: It's basically the same as for maven. The task 'manifest' generates a manifest file.



3. Get SVN revision

Warning:This only works with the plain-text format of .svn/entries, not with the older XML format.

To get an SVN revision of you project at the time of building, you can use the following task to get the revision number into the property svn.version (requires ant >= 1.6):

<loadfile
   property="svn.version" srcFile=".svn/entries" failonerror="true">
   <filterchain>
      <headfilter lines="6"/>
      <tokenfilter>
         <filetokenizer/>
         <replaceregex pattern=".*[\r\n]+dir[\r\n]+([0-9]+)[\r\n]+http://.*"
            flags="s" replace="\1"/>
      </tokenfilter>
   </filterchain>
</loadfile>


Explanation:
.svn/entries is a SVN file having something like this somewhere at its beginning:

8

dir 7946 http://example.com/svn/repos//Projects/MyProject
  • headfilter takes first 6 lines of the file
  • filetokenizer gets all those lines into 1 string
  • replaceregexp finds the revision number in it and replaces all the string with this number
  • the result is stored into the property svn.version