UNPKG

1.47 kBJavaScriptView Raw
1var fs = require('fs');
2var path = require('path');
3
4// branch naming only has a few excluded characters, see git-check-ref-format(1)
5var REGEX_BRANCH = /^ref: refs\/heads\/([^?*\[\\~^:]+)$/;
6
7module.exports = function detectLocalGit() {
8 var dir = process.cwd(), gitDir;
9 while (path.resolve('/') !== dir) {
10 gitDir = path.join(dir, '.git');
11 var existsSync = fs.existsSync || path.existsSync;
12 if (existsSync(path.join(gitDir, 'HEAD')))
13 break;
14
15 dir = path.dirname(dir);
16 }
17
18 if (path.resolve('/') === dir)
19 return;
20
21 var head = fs.readFileSync(path.join(dir, '.git', 'HEAD'), 'utf-8').trim();
22 var branch = (head.match(REGEX_BRANCH) || [])[1];
23 if (!branch)
24 return { git_commit: head };
25
26 var commit = _parseCommitHashFromRef(dir, branch);
27
28 return { git_commit: commit, git_branch: branch };
29};
30
31function _parseCommitHashFromRef(dir, branch) {
32 var ref = path.join(dir, '.git', 'refs', 'heads', branch);
33 if (fs.existsSync(ref)) {
34 return fs.readFileSync(ref, 'utf-8').trim();
35 } else {
36 // ref does not exist; get it from packed-refs
37 var commit = '';
38 var packedRefs = path.join(dir, '.git', 'packed-refs');
39 var packedRefsText = fs.readFileSync(packedRefs, 'utf-8');
40 packedRefsText.split('\n').forEach(function (line) {
41 if (line.match('refs/heads/'+branch)) {
42 commit = line.split(' ')[0];
43 }
44 });
45 return commit;
46 }
47}