1 | 'use strict';
|
2 |
|
3 | const fs = require('fs');
|
4 | const path = require('path');
|
5 |
|
6 |
|
7 | const REGEX_BRANCH = /^ref: refs\/heads\/([^?*[\\~^:]+)$/;
|
8 |
|
9 | function 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 |
|
40 | function _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 |
|
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 |
|
58 | module.exports = detectLocalGit;
|