It is an usual requirement that we want to display information about version control on gsp pages. In agile development, project deployment is a routine process because very time we did some enhancement/fixes on previous version of project. Generally a project under development has more then one instance running over servers for demos, client testing, QA server etc, and we have to update them time to time. For this, we should know when the war file was developed and which particular fixes it needed.

One of the approach is to gather information at the time of war file creation and use that data to display on gsp pages. We can execute some code at different events registered with the grails.
Some events are as follows :

  • CreateWarStart
  • CreateWarEnd
  • CompileStart
  • CompileEnd

All events are prefixed with event and needs to define a block per events we want to customize in file Events.groovy. For example
File : _Events.gsp

import java.text.DateFormat
import java.text.SimpleDateFormat

eventCreateWarStart = { warName, stagingDir  ->
    ant.propertyfile(file: "${stagingDir}/WEB-INF/classes/application.properties") {
        String branchName = "git symbolic-ref --short HEAD".execute().text.trim()
        String commit = "git rev-parse HEAD".execute().text.trim()
        DateFormat fmt = new SimpleDateFormat("MMMM dd, yyyy k:mm:ss");
        entry(key:"war.release.date", value: fmt.format(new Date()))
        if(branchName!=null && !branchName.isEmpty()) entry(key:"build.git.branch", value: branchName)
        if(commit!=null && !commit.isEmpty()) entry(key:"build.git.commit", value: commit.length()==40?commit:"N/A")
    }
}

Now the properties are stored in file WEB-INF/classes/application.properties in WAR file. There are several ways of read properties from application.properties. We can use gsp tag g:meta to show them directly on view. We can use grailsApplication instance to get these values. For example :

Holders.grailsApplication.metadata['build.git.branch']

OR
Inject grailsApplication bean :

def grailsApplication
grailsApplication.metadata['build.git.branch']

There is also a plugin Build Info to display git information which provides a controller and gsp page to render the properties. But the information displayed is limited and if you need some extra information then go with the above approach : run your command in events.groovy before the war creation and use them where you want.

Thanks & Happy coding 😀