branch: restrict branch deletion for worktrees Restrict the ability to delete branches that are checked out in any linked repository.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
diff --git a/src/branch.c b/src/branch.c
index e48cb1f..7d5e9cb 100644
--- a/src/branch.c
+++ b/src/branch.c
@@ -206,6 +206,12 @@ int git_branch_delete(git_reference *branch)
return -1;
}
+ if (git_reference_is_branch(branch) && git_branch_is_checked_out(branch)) {
+ giterr_set(GITERR_REFERENCE, "Cannot delete branch '%s' as it is "
+ "the current HEAD of a linked repository.", git_reference_name(branch));
+ return -1;
+ }
+
if (git_buf_join(&config_section, '.', "branch",
git_reference_name(branch) + strlen(GIT_REFS_HEADS_DIR)) < 0)
goto on_error;
diff --git a/tests/worktree/refs.c b/tests/worktree/refs.c
index e08e553..38f6127 100644
--- a/tests/worktree/refs.c
+++ b/tests/worktree/refs.c
@@ -1,4 +1,5 @@
#include "clar_libgit2.h"
+#include "worktree.h"
#include "worktree_helpers.h"
#define COMMON_REPO "testrepo"
@@ -66,3 +67,29 @@ void test_worktree_refs__read_head(void)
git_reference_free(head);
}
+
+void test_worktree_refs__delete_fails_for_checked_out_branch(void)
+{
+ git_reference *branch;
+
+ cl_git_pass(git_branch_lookup(&branch, fixture.repo,
+ "testrepo-worktree", GIT_BRANCH_LOCAL));
+ cl_git_fail(git_branch_delete(branch));
+
+ git_reference_free(branch);
+}
+
+void test_worktree_refs__delete_succeeds_after_pruning_worktree(void)
+{
+ git_reference *branch;
+ git_worktree *worktree;
+
+ cl_git_pass(git_worktree_lookup(&worktree, fixture.repo, fixture.worktreename));
+ cl_git_pass(git_worktree_prune(worktree, GIT_WORKTREE_PRUNE_VALID));
+ git_worktree_free(worktree);
+
+ cl_git_pass(git_branch_lookup(&branch, fixture.repo,
+ "testrepo-worktree", GIT_BRANCH_LOCAL));
+ cl_git_pass(git_branch_delete(branch));
+ git_reference_free(branch);
+}