Skip to content

Commit beb6f24

Browse files
pcloudsgitster
authored andcommitted
worktree add -B: do the checkout test before update branch
If --force is not given but -B is, we should not proceed if the given branch is already checked out elsewhere. add_worktree() has this test, but it kicks in too late when "git branch --force" is already executed. As a result, even though we correctly refuse to create a new worktree, we have already updated the branch and mess up the other checkout. Repeat the die_if_checked_out() test again for this specific case before "git branch" runs. Signed-off-by: Nguyễn Thái Ngọc Duy <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 0ebf4a2 commit beb6f24

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

builtin/worktree.c

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -334,9 +334,18 @@ static int add(int ac, const char **av, const char *prefix)
334334
branch = ac < 2 ? "HEAD" : av[1];
335335

336336
opts.force_new_branch = !!new_branch_force;
337-
if (opts.force_new_branch)
337+
if (opts.force_new_branch) {
338+
struct strbuf symref = STRBUF_INIT;
339+
338340
opts.new_branch = new_branch_force;
339341

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+
340349
if (ac < 2 && !opts.new_branch && !opts.detach) {
341350
int n;
342351
const char *s = worktree_basename(path, &n);

t/t2025-worktree-add.sh

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,13 @@ 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+
196203
test_expect_success 'add -B' '
197204
git worktree add -B poodle bamboo2 master^ &&
198205
git -C bamboo2 symbolic-ref HEAD >actual &&

0 commit comments

Comments
 (0)