Skip to content

Commit 595bfef

Browse files
committed
Merge branch 'nd/worktree-add-B'
"git worktree add -B <branchname>" did not work. * nd/worktree-add-B: worktree add -B: do the checkout test before update branch worktree: fix "add -B"
2 parents 5e57f9c + beb6f24 commit 595bfef

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

builtin/worktree.c

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -201,9 +201,7 @@ static int add_worktree(const char *path, const char *refname,
201201
die(_("'%s' already exists"), path);
202202

203203
/* is 'refname' a branch or commit? */
204-
if (opts->force_new_branch) /* definitely a branch */
205-
;
206-
else if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
204+
if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
207205
ref_exists(symref.buf)) { /* it's a branch */
208206
if (!opts->force)
209207
die_if_checked_out(symref.buf);
@@ -336,9 +334,18 @@ static int add(int ac, const char **av, const char *prefix)
336334
branch = ac < 2 ? "HEAD" : av[1];
337335

338336
opts.force_new_branch = !!new_branch_force;
339-
if (opts.force_new_branch)
337+
if (opts.force_new_branch) {
338+
struct strbuf symref = STRBUF_INIT;
339+
340340
opts.new_branch = new_branch_force;
341341

342+
if (!opts.force &&
343+
!strbuf_check_branch_ref(&symref, opts.new_branch) &&
344+
ref_exists(symref.buf))
345+
die_if_checked_out(symref.buf);
346+
strbuf_release(&symref);
347+
}
348+
342349
if (ac < 2 && !opts.new_branch && !opts.detach) {
343350
int n;
344351
const char *s = worktree_basename(path, &n);

t/t2025-worktree-add.sh

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,21 @@ test_expect_success '"add" -B/--detach mutually exclusive' '
193193
test_must_fail git worktree add -B poodle --detach bamboo master
194194
'
195195

196+
test_expect_success '"add -B" fails if the branch is checked out' '
197+
git rev-parse newmaster >before &&
198+
test_must_fail git worktree add -B newmaster bamboo master &&
199+
git rev-parse newmaster >after &&
200+
test_cmp before after
201+
'
202+
203+
test_expect_success 'add -B' '
204+
git worktree add -B poodle bamboo2 master^ &&
205+
git -C bamboo2 symbolic-ref HEAD >actual &&
206+
echo refs/heads/poodle >expected &&
207+
test_cmp expected actual &&
208+
test_cmp_rev master^ poodle
209+
'
210+
196211
test_expect_success 'local clone from linked checkout' '
197212
git clone --local here here-clone &&
198213
( cd here-clone && git fsck )

0 commit comments

Comments
 (0)