Skip to content

Commit f292244

Browse files
rheniumgitster
authored andcommitted
branch -d: refuse deleting a branch which is currently checked out
When a branch is checked out by current working tree, deleting the branch is forbidden. However when the branch is checked out only by other working trees, deleting incorrectly succeeds. Use find_shared_symref() to check if the branch is in use, not just comparing with the current working tree's HEAD. Helped-by: Eric Sunshine <[email protected]> Signed-off-by: Kazuki Yamaguchi <[email protected]> Reviewed-by: Eric Sunshine <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent a0feb1b commit f292244

File tree

2 files changed

+20
-8
lines changed

2 files changed

+20
-8
lines changed

builtin/branch.c

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
#include "utf8.h"
2121
#include "wt-status.h"
2222
#include "ref-filter.h"
23+
#include "worktree.h"
2324

2425
static const char * const builtin_branch_usage[] = {
2526
N_("git branch [<options>] [-r | -a] [--merged | --no-merged]"),
@@ -215,16 +216,21 @@ static int delete_branches(int argc, const char **argv, int force, int kinds,
215216
int flags = 0;
216217

217218
strbuf_branchname(&bname, argv[i]);
218-
if (kinds == FILTER_REFS_BRANCHES && !strcmp(head, bname.buf)) {
219-
error(_("Cannot delete the branch '%s' "
220-
"which you are currently on."), bname.buf);
221-
ret = 1;
222-
continue;
223-
}
224-
225219
free(name);
226-
227220
name = mkpathdup(fmt, bname.buf);
221+
222+
if (kinds == FILTER_REFS_BRANCHES) {
223+
char *worktree = find_shared_symref("HEAD", name);
224+
if (worktree) {
225+
error(_("Cannot delete branch '%s' "
226+
"checked out at '%s'"),
227+
bname.buf, worktree);
228+
free(worktree);
229+
ret = 1;
230+
continue;
231+
}
232+
}
233+
228234
target = resolve_ref_unsafe(name,
229235
RESOLVE_REF_READING
230236
| RESOLVE_REF_NO_RECURSE

t/t3200-branch.sh

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -403,6 +403,12 @@ test_expect_success 'test deleting branch without config' '
403403
test_i18ncmp expect actual
404404
'
405405

406+
test_expect_success 'deleting currently checked out branch fails' '
407+
git worktree add -b my7 my7 &&
408+
test_must_fail git -C my7 branch -d my7 &&
409+
test_must_fail git branch -d my7
410+
'
411+
406412
test_expect_success 'test --track without .fetch entries' '
407413
git branch --track my8 &&
408414
test "$(git config branch.my8.remote)" &&

0 commit comments

Comments
 (0)