Checking commit messages and branch names (gilp-util)

Rodrigo Lopez
August 30, 2017

This is part of Code quality enforcement series.

We will investigate the utilities inside gilp-util for several use cases in the context of creating gulp plugins relying on git.
These are generally self-descriptive.

You might want to do some validations based on the current branch's name. gilpUtil.getBranchName comes in really handy in order to painlessly retrieve it. That's what gilp-check-branch-name uses under the hood.

Let's imagine you want to check that the current branch name corresponds in some way to a ticket in an issue tracker (for instance github, we're going to use node-github).

And let's assume for simplicity that your branch name convention is [dev|master]/[isssue-number].

This is a possible plugin code:

'use strict'
var through = require('through2');
var gilpUtil = require('gilp-util');
var GithubApi = require('node-github');

module.exports = function (opts, message) {
  var githubOpts = opts.github;
  message = message || 'No issue found with that number.';

  function bufferContents(file, enc, cb) {
    cb();
  }

  function endStream(cb) {
    var github = new GitHubApi();
    var branchName = gilpUtil.getBranchName();
    var issueNumber = branchName.split('/')[1];

    github.authenticate(githubOpts.auth);
    github.issues.get({
      owner: githubOpts.owner, 
      repo: githubOpts.repo, 
      number: issueNumber 
      }, (err, res) => {
        if (res.statusCode > 400) {
          this.emit('error', new Error('gilp-check-branch-name-issue-tracker: ' + message));
          cb();
        }
    });
  }
  return through.obj(bufferContents, endStream);
};

And in your gulpfile you should include it this way.

const gilp = require('gilp')(gulp);
const checkBranchIssue = require('check-branch-issue');  // Or something.

gilp.hook('pre-commit', () => {
  gilp.srcFromStaged(['**/*'])
  .pipe(checkBranchIssue(
    {github: 
      {auth: {}, /* type and token  */
       owner: '', /* repo owner */
       repo: '', /* repo */ }
    }))
});

Similarly we have getCommitMessage, isInMerge, and getGitDirectory. Check the README.

"Checking commit messages and branch names (gilp-util)" by Rodrigo Lopez is licensed under CC BY SA. Source code examples are licensed under MIT.

Photo by Luca Bravo.

Categorized under open source.

We are Sophilabs

A software design and development agency that helps companies build and grow products by delivering high-quality software through agile practices and perfectionist teams.