aboutsummaryrefslogtreecommitdiff
path: root/lib/detectLocalGit.js
blob: 46a9e6759f3c2236cbbcd1f0ab0c3ae7812f009d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
var fs = require('fs');
var path = require('path');

// branch naming only has a few excluded characters, see git-check-ref-format(1)
var REGEX_BRANCH = /^ref: refs\/heads\/([^?*\[\\~^:]+)$/;

module.exports = function detectLocalGit() {
  var dir = process.cwd(), gitDir;
  while (path.resolve('/') !== dir) {
    gitDir = path.join(dir, '.git');
    var existsSync = fs.existsSync || path.existsSync;
    if (existsSync(path.join(gitDir, 'HEAD')))
      break;

    dir = path.dirname(dir);
  }

  if (path.resolve('/') === dir)
    return;

  var head = fs.readFileSync(path.join(dir, '.git', 'HEAD'), 'utf-8').trim();
  var branch = (head.match(REGEX_BRANCH) || [])[1];
  if (!branch)
    return { git_commit: head };

  var commit = _parseCommitHashFromRef(dir, branch);

  return { git_commit: commit, git_branch: branch };
};

function _parseCommitHashFromRef(dir, branch) {
    var ref = path.join(dir, '.git', 'refs', 'heads', branch);
    if (fs.existsSync(ref)) {
        return fs.readFileSync(ref, 'utf-8').trim();
    } else {
        // ref does not exist; get it from packed-refs
        var commit = '';
        var packedRefs = path.join(dir, '.git', 'packed-refs');
        var packedRefsText = fs.readFileSync(packedRefs, 'utf-8');
        packedRefsText.split('\n').forEach(function (line) {
            if (line.match('refs/heads/'+branch)) {
                commit = line.split(' ')[0];
            }
        });
        return commit;
    }
}