Skip to content

Commit

Permalink
Check early that a new branch is new and valid
Browse files Browse the repository at this point in the history
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 <barkalow@iabervon.org>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
  • Loading branch information
Daniel Barkalow authored and Junio C Hamano committed Sep 22, 2008
1 parent cc185a6 commit 352eadc
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
12 changes: 12 additions & 0 deletions builtin-checkout.c
Original file line number Diff line number Diff line change
Expand Up @@ -565,6 +565,18 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
return checkout_paths(source_tree, pathspec);
}

if (opts.new_branch) {
struct strbuf buf;
strbuf_init(&buf, 0);
strbuf_addstr(&buf, "refs/heads/");
strbuf_addstr(&buf, opts.new_branch);
if (!get_sha1(buf.buf, rev))
die("git checkout: branch %s already exists", opts.new_branch);
if (check_ref_format(buf.buf))
die("git checkout: we do not like '%s' as a branch name.", opts.new_branch);
strbuf_release(&buf);
}

if (new.name && !new.commit) {
die("Cannot switch branch to a non-commit.");
}
Expand Down
10 changes: 10 additions & 0 deletions t/t7201-co.sh
Original file line number Diff line number Diff line change
Expand Up @@ -359,4 +359,14 @@ test_expect_success 'checkout an unmerged path should fail' '
test_cmp sample file
'

test_expect_success 'failing checkout -b should not break working tree' '
git reset --hard master &&
git symbolic-ref HEAD refs/heads/master &&
test_must_fail git checkout -b renamer side^ &&
test $(git symbolic-ref HEAD) = refs/heads/master &&
git diff --exit-code &&
git diff --cached --exit-code
'

test_done

0 comments on commit 352eadc

Please sign in to comment.