Skip to content

Commit abe1998

Browse files
committed
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 <[email protected]>
1 parent 04f6785 commit abe1998

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

builtin/checkout.c

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -916,6 +916,17 @@ static int parse_branchname_arg(int argc, const char **argv,
916916
return argcount;
917917
}
918918

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+
919930
int cmd_checkout(int argc, const char **argv, const char *prefix)
920931
{
921932
struct checkout_opts opts;
@@ -1089,5 +1100,13 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
10891100
if (opts.writeout_stage)
10901101
die(_("--ours/--theirs is incompatible with switching branches."));
10911102

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+
}
10921111
return switch_branches(&opts, &new);
10931112
}

t/t2015-checkout-unborn.sh

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
#!/bin/sh
22

3-
test_description='checkout from unborn branch protects contents'
3+
test_description='checkout from unborn branch'
44
. ./test-lib.sh
55

66
test_expect_success 'setup' '
@@ -37,4 +37,13 @@ test_expect_success 'checkout from unborn merges identical index contents' '
3737
git checkout -b new origin
3838
'
3939

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+
4049
test_done

0 commit comments

Comments
 (0)