Skip to content

Commit a38bb0c

Browse files
committed
Merge branch 'db/maint-checkout-b' into maint
* db/maint-checkout-b: Check early that a new branch is new and valid
2 parents 3b1eb12 + 352eadc commit a38bb0c

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

builtin-checkout.c

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -565,6 +565,18 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
565565
return checkout_paths(source_tree, pathspec);
566566
}
567567

568+
if (opts.new_branch) {
569+
struct strbuf buf;
570+
strbuf_init(&buf, 0);
571+
strbuf_addstr(&buf, "refs/heads/");
572+
strbuf_addstr(&buf, opts.new_branch);
573+
if (!get_sha1(buf.buf, rev))
574+
die("git checkout: branch %s already exists", opts.new_branch);
575+
if (check_ref_format(buf.buf))
576+
die("git checkout: we do not like '%s' as a branch name.", opts.new_branch);
577+
strbuf_release(&buf);
578+
}
579+
568580
if (new.name && !new.commit) {
569581
die("Cannot switch branch to a non-commit.");
570582
}

t/t7201-co.sh

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,4 +359,14 @@ test_expect_success 'checkout an unmerged path should fail' '
359359
test_cmp sample file
360360
'
361361

362+
test_expect_success 'failing checkout -b should not break working tree' '
363+
git reset --hard master &&
364+
git symbolic-ref HEAD refs/heads/master &&
365+
test_must_fail git checkout -b renamer side^ &&
366+
test $(git symbolic-ref HEAD) = refs/heads/master &&
367+
git diff --exit-code &&
368+
git diff --cached --exit-code
369+
370+
'
371+
362372
test_done

0 commit comments

Comments
 (0)