git-checkout: disallow --detach on unborn branch

abe199808c (git checkout -b: allow switching out of an unborn branch) introduced a bug demonstrated by git checkout --orphan foo git checkout --detach git symbolic-ref HEAD which gives 'refs/heads/(null)'. This happens because we strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch) when opts->new_branch can be NULL for --detach. Catch and forbid this case, adding a test to t2017 to catch it in future. Signed-off-by: Chris Webb <chris@arachsys.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Chris Webb committed Jun 26, 2012 at 16:06 UTC 8ced1aa08f9e1798b2b3fec41a0598ef79b477fe
2 files changed +8
builtin/checkout.c
+2
@@ -921,6 +921,8 @@ static int switch_unborn_to_new_branch(struct checkout_opts *opts)
921 int status;
922 struct strbuf branch_ref = STRBUF_INIT;
923
924 + if (!opts->new_branch)
925 + die(_("You are on a branch yet to be born"));
926 strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
927 status = create_symref("HEAD", branch_ref.buf, "checkout -b");
928 strbuf_release(&branch_ref);
t/t2017-checkout-orphan.sh
+6
@@ -116,4 +116,10 @@ test_expect_success '--orphan refuses to switch if a merge is needed' '
116 git reset --hard
117 '
118
119 +test_expect_success 'cannot --detach on an unborn branch' '
120 + git checkout master &&
121 + git checkout --orphan new &&
122 + test_must_fail git checkout --detach
123 +'
124 +
125 test_done