git checkout -b: allow switching out of an unborn branch

Running "git checkout -b another" immediately after "git init" when you do not even have a commit on 'master' fails with: $ git checkout -b another fatal: You are on a branch yet to be born This is unnecessary, if we redefine "git checkout -b $name" that does not take any $start_point (which has to be a commit) as "I want to check out a new branch $name from the state I am in". Signed-off-by: Junio C Hamano <gitster@pobox.com>

Junio C Hamano committed Jan 30, 2012 at 12:10 UTC abe199808c6586047fb7255b80e3d17ffc26bf6c
2 files changed +29 -1
builtin/checkout.c
+19
@@ -916,6 +916,17 @@ static int parse_branchname_arg(int argc, const char **argv,
916 return argcount;
917 }
918
919 +static int switch_unborn_to_new_branch(struct checkout_opts *opts)
920 +{
921 + int status;
922 + struct strbuf branch_ref = STRBUF_INIT;
923 +
924 + strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
925 + status = create_symref("HEAD", branch_ref.buf, "checkout -b");
926 + strbuf_release(&branch_ref);
927 + return status;
928 +}
929 +
930 int cmd_checkout(int argc, const char **argv, const char *prefix)
931 {
932 struct checkout_opts opts;
@@ -1089,5 +1100,13 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
1100 if (opts.writeout_stage)
1101 die(_("--ours/--theirs is incompatible with switching branches."));
1102
1103 + if (!new.commit) {
1104 + unsigned char rev[20];
1105 + int flag;
1106 +
1107 + resolve_ref("HEAD", rev, 0, &flag);
1108 + if ((flag & REF_ISSYMREF) && is_null_sha1(rev))
1109 + return switch_unborn_to_new_branch(&opts);
1110 + }
1111 return switch_branches(&opts, &new);
1112 }
t/t2015-checkout-unborn.sh
+10 -1
@@ -1,6 +1,6 @@
1 #!/bin/sh
2
3 -test_description='checkout from unborn branch protects contents'
3 +test_description='checkout from unborn branch'
4 . ./test-lib.sh
5
6 test_expect_success 'setup' '
@@ -37,4 +37,13 @@ test_expect_success 'checkout from unborn merges identical index contents' '
37 git checkout -b new origin
38 '
39
40 +test_expect_success 'checking out another branch from unborn state' '
41 + git checkout --orphan newroot &&
42 + git checkout -b anothername &&
43 + test_must_fail git show-ref --verify refs/heads/newroot &&
44 + git symbolic-ref HEAD >actual &&
45 + echo refs/heads/anothername >expect &&
46 + test_cmp expect actual
47 +'
48 +
49 test_done