Skip to content

Commit 352eadc

Browse files
iabervongitster
authored andcommitted
Check early that a new branch is new and valid
If you fail to update refs to change branches in checkout, your index and working tree are left already updated. We don't have an easy way to undo this, but at least we can check things that would make the creation of a new branch fail. These checks were in the shell version, and were lost in the C conversion. The messages are from the shell version, and should probably be made nicer. [jc: added test to t7201] Signed-off-by: Daniel Barkalow <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent cc185a6 commit 352eadc

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)