Skip to content

Commit aa47ec9

Browse files
committed
Merge branch 'jc/checkout-out-of-unborn'
* jc/checkout-out-of-unborn: git checkout -b: allow switching out of an unborn branch
2 parents b95ffc1 + abe1998 commit aa47ec9

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
@@ -908,6 +908,17 @@ static int parse_branchname_arg(int argc, const char **argv,
908908
return argcount;
909909
}
910910

911+
static int switch_unborn_to_new_branch(struct checkout_opts *opts)
912+
{
913+
int status;
914+
struct strbuf branch_ref = STRBUF_INIT;
915+
916+
strbuf_addf(&branch_ref, "refs/heads/%s", opts->new_branch);
917+
status = create_symref("HEAD", branch_ref.buf, "checkout -b");
918+
strbuf_release(&branch_ref);
919+
return status;
920+
}
921+
911922
int cmd_checkout(int argc, const char **argv, const char *prefix)
912923
{
913924
struct checkout_opts opts;
@@ -1079,5 +1090,13 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
10791090
if (opts.writeout_stage)
10801091
die(_("--ours/--theirs is incompatible with switching branches."));
10811092

1093+
if (!new.commit) {
1094+
unsigned char rev[20];
1095+
int flag;
1096+
1097+
if (!read_ref_full("HEAD", rev, 0, &flag) &&
1098+
(flag & REF_ISSYMREF) && is_null_sha1(rev))
1099+
return switch_unborn_to_new_branch(&opts);
1100+
}
10821101
return switch_branches(&opts, &new);
10831102
}

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)