Skip to content

Commit 788cd2d

Browse files
committed
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.
1 parent a0f87e1 commit 788cd2d

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

src/branch.c

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,10 @@ static int branch_equals(git_repository *repo, const char *path, void *payload)
153153

154154
int git_branch_is_checked_out(const git_reference *branch)
155155
{
156-
assert(branch && git_reference_is_branch(branch));
156+
assert(branch);
157+
158+
if (!git_reference_is_branch(branch))
159+
return 0;
157160

158161
return git_repository_foreach_head(git_reference_owner(branch),
159162
branch_equals, (void *) branch) == 1;

tests/refs/branches/checkedout.c

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,3 +37,10 @@ void test_refs_branches_checkedout__worktree(void)
3737

3838
cleanup_fixture_worktree(&fixture);
3939
}
40+
41+
void test_refs_branches_checkedout__head_is_not_checked_out(void)
42+
{
43+
repo = cl_git_sandbox_init("testrepo");
44+
assert_checked_out(repo, "HEAD", 0);
45+
cl_git_sandbox_cleanup();
46+
}

0 commit comments

Comments
 (0)