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 <pclouds@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Nguyễn Thái Ngọc Duy committed
Feb 15, 2016 at 20:35 UTC
beb6f24beef67f6f825c8c99e408f67d23b784d4
2 files changed
+17
-1
builtin/worktree.c
+10
-1
@@ -334,9 +334,18 @@ static int add(int ac, const char **av, const char *prefix)
334
branch = ac < 2 ? "HEAD" : av[1];
335
336
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
+
340
opts.new_branch = new_branch_force;
341
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
+
349
if (ac < 2 && !opts.new_branch && !opts.detach) {
350
int n;
351
const char *s = worktree_basename(path, &n);
t/t2025-worktree-add.sh
+7
@@ -193,6 +193,13 @@ test_expect_success '"add" -B/--detach mutually exclusive' '
193
test_must_fail git worktree add -B poodle --detach bamboo master
194
'
195
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 &&