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 <barkalow@iabervon.org> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Daniel Barkalow committed
Sep 21, 2008 at 14:36 UTC
352eadc40024b141e1295693654ec20cc123844f
2 files changed
+22
builtin-checkout.c
+12
@@ -565,6 +565,18 @@ no_reference:
565
return checkout_paths(source_tree, pathspec);
566
}
567
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
+
580
if (new.name && !new.commit) {
581
die("Cannot switch branch to a non-commit.");
582
}
t/t7201-co.sh
+10
@@ -359,4 +359,14 @@ test_expect_success 'checkout an unmerged path should fail' '
359
test_cmp sample file
360
'
361
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
+
372
test_done