Adding an Auto-incrementing Build Number to a Grails Application

Print This Post Print This Post

The development cycle of a web application (or any software for that matter) always requires tons of builds and deployments to servers allowing the testers to do their thing. One thing that comes up often during this part of the application lifecycle is knowing which build is currently live, especially when reporting defects back to development.

Tracking build numbers is common among build environments, but it may not always be obvious how to implement it. In Grails, there is not direct mechanism for tracking this information, but adding it is simple enough…

The Event Handler

In Grails, you have the option of hooking into a number of events triggered during target and plugin scripts. To start, add the file _Events.groovy into your project’s ‘scripts’ directory (see the link for any caveats that may apply for your project). In it, add the following code (feel free to modify!):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
eventCompileStart = { kind ->
	def buildNumber = metadata.'app.buildNumber'
 
	if (!buildNumber)
		buildNumber = 1
	else
		buildNumber = Integer.valueOf(buildNumber) + 1
 
	metadata.'app.buildNumber' = buildNumber.toString()
 
	metadata.persist()
 
	println "**** Compile Starting on Build #${buildNumber}"
}

Making Use of the Build Number
Once the above has been added, it will be automatically incremented each time there is a build. You can make customizations as to when it’s incremented (as it is, it will increment even when you launch the project in Eclipse).

Once it’s implemented and (hopefully) working, it’s time to go ahead and make some use of it. Add the following to the footer or where ever to your GSP page(s):

1
2
3
Application Version: 
${grailsApplication.metadata['app.version']} 
(Build #${grailsApplication.metadata['app.buildNumber']})

Edit: (7/9/2010)

Extra Stuff

I’ve been making use of other bits of build info in some of my projects, so I figured I might share them here as well… Insert the following into the code block above, somewhere before the call to ‘metadata.persist()’.

1
2
3
4
def formatter = new SimpleDateFormat("MMM dd, yyyy")
def buildDate = formatter.format(new Date(System.currentTimeMillis()))
metadata.'app.buildDate' = buildDate
metadata.'app.buildProfile' = grailsEnv

Then modify the above GSP code above to this:

1
2
3
4
5
Application Version:
${grailsApplication.metadata['app.version']} 
(Build #${grailsApplication.metadata['app.buildNumber']} 
${grailsApplication.metadata['app.buildDate']} 
${grailsApplication.metadata['app.buildProfile']})

which will result in a nice and informative identifier such as:

Application Version: 1.0 (Build #110 Jul 09, 2010 development)

Comments are closed.