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 <sunshine@sunshineco.com> Signed-off-by: Kazuki Yamaguchi <k@rhe.jp> Reviewed-by: Eric Sunshine <sunshine@sunshineco.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Kazuki Yamaguchi committed
Mar 29, 2016 at 18:38 UTC
f292244c04d8109ee32a45016ce08984fbd925f0
2 files changed
+20
-8
builtin/branch.c
+14
-8
@@ -20,6 +20,7 @@
20
#include "utf8.h"
21
#include "wt-status.h"
22
#include "ref-filter.h"
23
+#include "worktree.h"
24
25
static const char * const builtin_branch_usage[] = {
26
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,
216
int flags = 0;
217
218
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
-
219
free(name);
226
-
220
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
+
234
target = resolve_ref_unsafe(name,
235
RESOLVE_REF_READING
236
| RESOLVE_REF_NO_RECURSE
t/t3200-branch.sh
+6
@@ -403,6 +403,12 @@ test_expect_success 'test deleting branch without config' '
403
test_i18ncmp expect actual
404
'
405
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
+
412
test_expect_success 'test --track without .fetch entries' '
413
git branch --track my8 &&
414
test "$(git config branch.my8.remote)" &&