GIT is a widely used version control system which really helps us to keep track of our code in a quite managed way. When we have frequent deployments on server it becomes important to know the details of the build, commit reference, date of build etc. Though we have build tools like Jenkins that does all the work but if we want to view git related information on our application page i.e. gsp we can do it using events registered in Grails.

We can fetch information when war file is being created and then store that information and show it on gsp page. We can trigger our code at a particular event and one such event is “CreateWarStart” which is provided by Grails.

Here is the code:


eventCreateWarStart = { warName, developmentDir ->
    ant.propertyfile(file: "${developmentDir}/WEB-INF/classes/application.properties") {
        String gitBranch = "git symbolic-ref --short HEAD".execute().text()
        DateFormat dateFormat = new SimpleDateFormat("MMMM dd, yyyy hh:mm:ss");
        entry(key:"war.build.date", value: dateFormat.format(new Date()))
        entry(key:"git.branch", value: gitBranch)
 
    }
}

 

Any idea what the above code does ? No ? Don’t scratch your head. Here is the explanation 😉

In the above code we are using Apache Ant that provides an easy way to configure the properties file during runtime. The above code executes command line methods using groovy, captures the returned output and stores the build information(git branch and current date) to the application.properties(WEB-INF/classes/application.properties) file using entry method.

We now have the required information in application.properties file. We can access it in Grails in various ways.

  • Using <g:meta .. > tag
  • Using ${grailsApplication.metadata.’keyName’}

In our example we will use

${grailsApplication.metadata.'git.branch'}

and

${grailsApplication.metadata.'war.build.date'}

to access and display the build information.

That was all folks! Thanks for reading 😉