branches: do not assert that the given ref is a branch Libraries should use assert(3P) only very scarcely. First, we usually shouldn't cause the caller of our library to abort in case where the assert fails. Second, if code is compiled with -DNDEBUG, then the assert will not be included at all. In our `git_branch_is_checked_out` function, we have an assert that verifies that the given reference parameter is non-NULL and in fact a branch. While the first check is fine, the second is not. E.g. when compiled with -DNDEBUG, we'd proceed and treat the given reference as a branch in all cases. Fix the issue by instead treating a non-branch reference as not being checked out. This is the obvious solution, as references other than branches cannot be directly checked out.
diff --git a/src/branch.c b/src/branch.c
index 61ed03e..516a87f 100644
--- a/src/branch.c
+++ b/src/branch.c
@@ -153,7 +153,10 @@ done:
int git_branch_is_checked_out(const git_reference *branch)
{
- assert(branch && git_reference_is_branch(branch));
+ assert(branch);
+
+ if (!git_reference_is_branch(branch))
+ return 0;
return git_repository_foreach_head(git_reference_owner(branch),
branch_equals, (void *) branch) == 1;
diff --git a/tests/refs/branches/checkedout.c b/tests/refs/branches/checkedout.c
index 2ec665a..2e195e2 100644
--- a/tests/refs/branches/checkedout.c
+++ b/tests/refs/branches/checkedout.c
@@ -37,3 +37,10 @@ void test_refs_branches_checkedout__worktree(void)
cleanup_fixture_worktree(&fixture);
}
+
+void test_refs_branches_checkedout__head_is_not_checked_out(void)
+{
+ repo = cl_git_sandbox_init("testrepo");
+ assert_checked_out(repo, "HEAD", 0);
+ cl_git_sandbox_cleanup();
+}