Commit 143e539fd0e9b83c6a3a369d5baf508ccb51697b

Patrick Steinhardt 2015-11-06T12:33:59

branch: restrict branch deletion for worktrees Restrict the ability to delete branches that are checked out in any linked repository.

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);
+}