-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathindex.js
45 lines (35 loc) · 963 Bytes
/
index.js
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
'use strict';
const fs = require('fs');
const util = require('util');
const find = require('findup-sync');
const readFile = util.promisify(fs.readFile);
function branch(cwd, callback) {
if (typeof cwd === 'function') {
callback = cwd;
cwd = null;
}
const promise = readFile(gitHeadPath(cwd)).then(buf => parseBranch(buf));
if (typeof callback === 'function') {
promise.then(res => callback(null, res)).catch(callback);
return;
}
return promise;
}
branch.sync = function(cwd) {
return parseBranch(fs.readFileSync(gitHeadPath(cwd)));
};
function parseBranch(buf) {
const match = /ref: refs\/heads\/([^\n]+)/.exec(buf.toString());
return match ? match[1] : null;
}
function gitHeadPath(cwd) {
const filepath = find('.git/HEAD', { cwd: cwd || process.cwd() });
if (!fs.existsSync(filepath)) {
throw new Error('.git/HEAD does not exist');
}
return filepath;
}
/**
* Expose `branch`
*/
module.exports = branch;