Commit bf013fc0a8c318570b109ce1516f1c49b5cd37c4

Patrick Steinhardt 2019-02-14T13:30:33

branch: fix `branch_is_checked_out` with bare repos In a bare repository, HEAD usually points to the branch that is considered the "default" branch. As the current implementation for `git_branch_is_checked_out` only does a comparison of HEAD with the branch that is to be checked, it will say that the branch pointed to by HEAD in such a bare repo is checked out. Fix this by skipping the main repo's HEAD when it is bare.

diff --git a/src/branch.c b/src/branch.c
index 30d29a6..7c6d747 100644
--- a/src/branch.c
+++ b/src/branch.c
@@ -153,13 +153,20 @@ done:
 
 int git_branch_is_checked_out(const git_reference *branch)
 {
+	git_repository *repo;
+	int flags = 0;
+
 	assert(branch);
 
 	if (!git_reference_is_branch(branch))
 		return 0;
 
-	return git_repository_foreach_head(git_reference_owner(branch),
-		branch_equals, 0, (void *) branch) == 1;
+	repo = git_reference_owner(branch);
+
+	if (git_repository_is_bare(repo))
+		flags |= GIT_REPOSITORY_FOREACH_HEAD_SKIP_REPO;
+
+	return git_repository_foreach_head(repo, branch_equals, flags, (void *) branch) == 1;
 }
 
 int git_branch_delete(git_reference *branch)
diff --git a/tests/refs/branches/checkedout.c b/tests/refs/branches/checkedout.c
index 2e195e2..d6dab2c 100644
--- a/tests/refs/branches/checkedout.c
+++ b/tests/refs/branches/checkedout.c
@@ -44,3 +44,10 @@ void test_refs_branches_checkedout__head_is_not_checked_out(void)
 	assert_checked_out(repo, "HEAD", 0);
 	cl_git_sandbox_cleanup();
 }
+
+void test_refs_branches_checkedout__master_in_bare_repo_is_not_checked_out(void)
+{
+	repo = cl_git_sandbox_init("testrepo.git");
+	assert_checked_out(repo, "refs/heads/master", 0);
+	cl_git_sandbox_cleanup();
+}