Skip to content

Commit 38fc5ab

Browse files
committed
branch: use foreach_head to see if a branch is checked out
Previously, we have extracted the logic to find and iterate over all HEADs of a repository. Use this function in `git_branch_is_checked_out`.
1 parent 74511aa commit 38fc5ab

File tree

1 file changed

+16
-49
lines changed

1 file changed

+16
-49
lines changed

src/branch.c

Lines changed: 16 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -127,62 +127,29 @@ int git_branch_create_from_annotated(
127127
repository, branch_name, commit->commit, commit->description, force);
128128
}
129129

130-
int git_branch_is_checked_out(
131-
const git_reference *branch)
130+
static int branch_equals(git_repository *repo, const char *path, void *payload)
132131
{
133-
git_buf path = GIT_BUF_INIT, buf = GIT_BUF_INIT;
134-
git_strarray worktrees;
135-
git_reference *ref = NULL;
136-
git_repository *repo;
137-
const char *worktree;
138-
int found = false;
139-
size_t i;
140-
141-
assert(branch && git_reference_is_branch(branch));
142-
143-
repo = git_reference_owner(branch);
144-
145-
if (git_worktree_list(&worktrees, repo) < 0)
146-
return -1;
147-
148-
for (i = 0; i < worktrees.count; i++) {
149-
worktree = worktrees.strings[i];
150-
151-
if (git_repository_head_for_worktree(&ref, repo, worktree) < 0)
152-
continue;
153-
154-
if (git__strcmp(ref->name, branch->name) == 0) {
155-
found = true;
156-
git_reference_free(ref);
157-
break;
158-
}
159-
160-
git_reference_free(ref);
161-
}
162-
git_strarray_free(&worktrees);
163-
164-
if (found)
165-
return found;
132+
git_reference *branch = (git_reference *) payload;
133+
git_reference *head;
134+
int equal;
166135

167-
/* Check HEAD of parent */
168-
if (git_buf_joinpath(&path, repo->commondir, GIT_HEAD_FILE) < 0)
169-
goto out;
170-
if (git_futils_readbuffer(&buf, path.ptr) < 0)
171-
goto out;
172-
if (git__prefixcmp(buf.ptr, "ref: ") == 0)
173-
git_buf_consume(&buf, buf.ptr + strlen("ref: "));
174-
git_buf_rtrim(&buf);
136+
if (git_reference__read_head(&head, repo, path) < 0 ||
137+
git_reference_type(head) != GIT_REF_SYMBOLIC)
138+
return 0;
175139

176-
found = git__strcmp(buf.ptr, branch->name) == 0;
140+
equal = !git__strcmp(head->target.symbolic, branch->name);
141+
git_reference_free(head);
142+
return equal;
143+
}
177144

178-
out:
179-
git_buf_free(&buf);
180-
git_buf_free(&path);
145+
int git_branch_is_checked_out(const git_reference *branch)
146+
{
147+
assert(branch && git_reference_is_branch(branch));
181148

182-
return found;
149+
return git_repository_foreach_head(git_reference_owner(branch),
150+
branch_equals, (void *) branch) == 1;
183151
}
184152

185-
186153
int git_branch_delete(git_reference *branch)
187154
{
188155
int is_head;

0 commit comments

Comments
 (0)