UNPKG

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