Skip to content

Commit 143e539

Browse files
committed
branch: restrict branch deletion for worktrees
Restrict the ability to delete branches that are checked out in any linked repository.
1 parent e3acd37 commit 143e539

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/branch.c

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,12 @@ int git_branch_delete(git_reference *branch)
206206
return -1;
207207
}
208208

209+
if (git_reference_is_branch(branch) && git_branch_is_checked_out(branch)) {
210+
giterr_set(GITERR_REFERENCE, "Cannot delete branch '%s' as it is "
211+
"the current HEAD of a linked repository.", git_reference_name(branch));
212+
return -1;
213+
}
214+
209215
if (git_buf_join(&config_section, '.', "branch",
210216
git_reference_name(branch) + strlen(GIT_REFS_HEADS_DIR)) < 0)
211217
goto on_error;

tests/worktree/refs.c

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#include "clar_libgit2.h"
2+
#include "worktree.h"
23
#include "worktree_helpers.h"
34

45
#define COMMON_REPO "testrepo"
@@ -66,3 +67,29 @@ void test_worktree_refs__read_head(void)
6667

6768
git_reference_free(head);
6869
}
70+
71+
void test_worktree_refs__delete_fails_for_checked_out_branch(void)
72+
{
73+
git_reference *branch;
74+
75+
cl_git_pass(git_branch_lookup(&branch, fixture.repo,
76+
"testrepo-worktree", GIT_BRANCH_LOCAL));
77+
cl_git_fail(git_branch_delete(branch));
78+
79+
git_reference_free(branch);
80+
}
81+
82+
void test_worktree_refs__delete_succeeds_after_pruning_worktree(void)
83+
{
84+
git_reference *branch;
85+
git_worktree *worktree;
86+
87+
cl_git_pass(git_worktree_lookup(&worktree, fixture.repo, fixture.worktreename));
88+
cl_git_pass(git_worktree_prune(worktree, GIT_WORKTREE_PRUNE_VALID));
89+
git_worktree_free(worktree);
90+
91+
cl_git_pass(git_branch_lookup(&branch, fixture.repo,
92+
"testrepo-worktree", GIT_BRANCH_LOCAL));
93+
cl_git_pass(git_branch_delete(branch));
94+
git_reference_free(branch);
95+
}

0 commit comments

Comments
 (0)