Skip to content

Commit bfd7cd0

Browse files
committed
feat(git): use remote branches only for local detached head
If the local repository is not in a detached head state, use `git rev-parse --abbrev-ref HEAD` to determine the `branch` as it is more reliable.
1 parent 4324504 commit bfd7cd0

File tree

2 files changed

+18
-7
lines changed

2 files changed

+18
-7
lines changed

lib/git.js

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,17 @@ function head() {
1717

1818
function branch() {
1919
try {
20-
const branch = execa
21-
.sync('git', ['show', '-s', '--pretty=%d', 'HEAD'])
22-
.stdout.replace(/^\(|\)$/g, '')
23-
.split(', ')
24-
.find(branch => branch.startsWith('origin/'));
20+
const headRef = execa.sync('git', ['rev-parse', '--abbrev-ref', 'HEAD']).stdout;
2521

26-
return branch ? branch.match(/^origin\/(.+)/)[1] : execa.sync('git', ['rev-parse', '--abbrev-ref', 'HEAD']).stdout;
22+
if (headRef === 'HEAD') {
23+
const branch = execa
24+
.sync('git', ['show', '-s', '--pretty=%d', 'HEAD'])
25+
.stdout.replace(/^\(|\)$/g, '')
26+
.split(', ')
27+
.find(branch => branch.startsWith('origin/'));
28+
return branch ? branch.match(/^origin\/(.+)/)[1] : undefined;
29+
}
30+
return headRef;
2731
} catch (err) {
2832
return undefined;
2933
}

test/git.test.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import test from 'ava';
22
import git from '../lib/git';
3-
import {gitRepo, gitCommit, gitHead} from './helpers/git-utils';
3+
import {gitRepo, gitCommit, gitHead, gitCheckout} from './helpers/git-utils';
44

55
// Save the current working diretory
66
const cwd = process.cwd();
@@ -17,8 +17,15 @@ test.serial('Git repository', async t => {
1717
t.deepEqual(git.configuration(), {commit, branch: 'master'});
1818
});
1919

20+
test.serial('Git cloned repository', async t => {
21+
await gitRepo(true);
22+
23+
t.deepEqual(git.configuration(), {commit: await gitHead(), branch: 'master'});
24+
});
25+
2026
test.serial('Git repository with detached head', async t => {
2127
await gitRepo(true);
28+
await gitCheckout('HEAD~0', false);
2229

2330
t.deepEqual(git.configuration(), {commit: await gitHead(), branch: 'master'});
2431
});

0 commit comments

Comments
 (0)