summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--builtin/worktree.c11
-rwxr-xr-xt/t2025-worktree-add.sh7
2 files changed, 17 insertions, 1 deletions
diff --git a/builtin/worktree.c b/builtin/worktree.c
index 6b9c946693..20cf67a549 100644
--- a/builtin/worktree.c
+++ b/builtin/worktree.c
@@ -334,9 +334,18 @@ static int add(int ac, const char **av, const char *prefix)
branch = ac < 2 ? "HEAD" : av[1];
opts.force_new_branch = !!new_branch_force;
- if (opts.force_new_branch)
+ if (opts.force_new_branch) {
+ struct strbuf symref = STRBUF_INIT;
+
opts.new_branch = new_branch_force;
+ if (!opts.force &&
+ !strbuf_check_branch_ref(&symref, opts.new_branch) &&
+ ref_exists(symref.buf))
+ die_if_checked_out(symref.buf);
+ strbuf_release(&symref);
+ }
+
if (ac < 2 && !opts.new_branch && !opts.detach) {
int n;
const char *s = worktree_basename(path, &n);
diff --git a/t/t2025-worktree-add.sh b/t/t2025-worktree-add.sh
index a4d36c0892..cbfa41ec61 100755
--- a/t/t2025-worktree-add.sh
+++ b/t/t2025-worktree-add.sh
@@ -193,6 +193,13 @@ test_expect_success '"add" -B/--detach mutually exclusive' '
test_must_fail git worktree add -B poodle --detach bamboo master
'
+test_expect_success '"add -B" fails if the branch is checked out' '
+ git rev-parse newmaster >before &&
+ test_must_fail git worktree add -B newmaster bamboo master &&
+ git rev-parse newmaster >after &&
+ test_cmp before after
+'
+
test_expect_success 'add -B' '
git worktree add -B poodle bamboo2 master^ &&
git -C bamboo2 symbolic-ref HEAD >actual &&