.githooks.js.hbs 2.44 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var exec = require('sync-exec');
var exit = 0;
var glob = require("glob");
var globOptions = {
  ignore: [
    'bower_components/**/*',
    'node_modules/**/*'
  ]
};

var pkg = require('../../package');
// Change to \{{ hook }} once that variable is available.
// @see https://github.com/wecodemore/grunt-githooks/pull/40
var hooks = pkg.githooks && pkg.githooks['{{ task }}'];
if (hooks) {
16 17
  var ret, hook, files, commands, staged, matchAll;
  var filesMatched = [];
18 19 20 21

  // Iterate over all hook definitions.
  for (var h in hooks) {
    hook = hooks[h];
22 23 24
    commands = hook.commands || [];
    staged = hook.staged === void 0 ? false : !!hook.staged;
    matchAll = hook.matchAll === void 0 ? true : !!hook.matchAll;
25 26 27 28 29

    // Iterate over all files in a hook definition.
    if (hook.files) {
      // Expand all file paths using glob (for pattern matching).
      if (typeof hook.files === 'string') {
30
        files = glob.sync(hook.files, globOptions) || [];
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
      }
      if (Array.isArray(hook.files)) {
        files = [];
        for (var f = 0; f < hook.files.length; f++) {
          files = [].concat(files, glob.sync(hook.files[f], globOptions) || []);
        }
      }

      // All files must either be staged or modified for the entire
      // hook definition command(s) to be executed.
      for (f in files) {
        var file = files[f];
        if (file) {
          // Only continue if file has been staged or modified.
          ret = exec((staged ? 'git diff --name-only --cached ' + file : 'git diff HEAD@{1} --stat -- ' + file));
          exit = ret.status;
47 48 49 50
          if (exit === 0 && ret.stdout !== '') {
            filesMatched.push(file);
          }
          else if (matchAll && (exit > 0 || ret.stdout === '')) {
51
            console.log(ret.stdout);
52
            filesMatched = [];
53 54 55 56 57 58
            break;
          }
        }
      }
    }

59 60
    // Iterate over all commands that should be executed for matched files.
    if (filesMatched.length) {
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
      if (typeof commands === 'string') {
        commands = [commands];
      }
      for (var c in commands) {
        var command = commands[c];
        console.log("\033[4;35mgit: {{ task }}\033[0;35m\n>> " + command + "\033[0m\n");
        ret = exec(command);
        console.log(ret.stdout);
        exit = ret.status;
        if (exit > 0) {
          break;
        }
      }
    }

    // Display any errors.
    if (exit > 0 && ret && ret.stderr) {
      console.log(ret.stderr);
    }
  }
}

process.exit(exit);