Showing the last commit info in angular via Grunt

1 minute read

I find it very useful to see details of the commit which was the HEAD at the time of building and deploying an application. It can be fairly easy added to angular in a few steps described below.

  • Install gitinfo grunt plugin
    npm install grunt-gitinfo --save-dev
    
  • Install grunt-ng-constant plugin
    npm install grunt-ng-constant --save-dev
    
  • Add gitinfo task to Gruntfile.js
     grunt.loadNpmTasks('grunt-gitinfo');
    
      grunt.initConfig({
      //...
          gitinfo: {
              commands : {
                  'local.branch.current.lastCommitTime': ['log', '--format=%at', '-n1', 'HEAD'],
                  'local.branch.current.lastCommitMessage' : ['log', '--format=', '-n1', 'HEAD']
              }
          }
      //...
      };
    
  • Add ngconstant task:
  grunt.loadNpmTasks('grunt-ng-constant');
  grunt.initConfig({
    //...
        ngconstant: {
            options: {
                name: 'yourApp',
                deps: false,
                wrap: '"use strict";\n// DO NOT EDIT THIS FILE, EDIT THE GRUNT TASK NGCONSTANT SETTINGS INSTEAD WHICH GENERATES THIS FILE\n{%= __ngModule %}\n',
                dest: 'src/main/webapp/scripts/app/app.constants.js'
                constants: {
                    GIT: '<%= gitinfo.local.branch.current %>'
                }
            }
        }
    //...
    };

 }
  • Register gitinfo and ngconstant tasks:
 grunt.registerTask('build', [
        'gitinfo',
        'ngconstant',
        //....
    ]);

Resulting app.constants.js file will look similar to this:

"use strict";
// DO NOT EDIT THIS FILE, EDIT THE GRUNT TASK NGCONSTANT SETTINGS INSTEAD WHICH GENERATES THIS FILE
angular.module('yourApp')
.constant('GIT', {lastCommitNumber:'425',lastCommitAuthor:'"lukasz.dziedziul"',lastCommitMessage:'',lastCommitTime:'1499116041',currentUser:'Łukasz Dziedziul',shortSHA:'3c993af',SHA:'3c993afa349c90d06ae10a1f995e649206f2be5a',name:'master'})
;

Now you can use the constant object in your angular application by adding it to the $scope:

function ($scope, GIT) {
        $scope.GIT = GIT;
}

and then using it in a view:

<span class="navbar-version">build:{{GIT.shortSHA}}@{{GIT.lastCommitTime*1000 | date: 'short'}}</span>