for-each-ref: do not segv with %(HEAD) on an unborn branch

The code to flip between "*" and " " prefixes depending on what branch is checked out used in --format='%(HEAD)' did not consider that HEAD may resolve to an unborn branch and dereferenced a NULL. This will become a lot easier to trigger as the codepath will be used to reimplement "git branch [--list]" in the future. Signed-off-by: Junio C Hamano <gitster@pobox.com>

Junio C Hamano committed Nov 18, 2016 at 15:21 UTC 84679d470d577bcde1b6aa6af36c08a2d77b6e68
2 files changed +11 -1
ref-filter.c
+1 -1
@@ -1017,7 +1017,7 @@ static void populate_value(struct ref_array_item *ref)
1017
1018 head = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
1019 sha1, NULL);
1020 - if (!strcmp(ref->refname, head))
1020 + if (head && !strcmp(ref->refname, head))
1021 v->s = "*";
1022 else
1023 v->s = " ";
t/t6300-for-each-ref.sh
+10
@@ -553,4 +553,14 @@ test_expect_success 'Verify sort with multiple keys' '
553 refs/tags/bogo refs/tags/master > actual &&
554 test_cmp expected actual
555 '
556 +
557 +test_expect_success 'do not dereference NULL upon %(HEAD) on unborn branch' '
558 + test_when_finished "git checkout master" &&
559 + git for-each-ref --format="%(HEAD) %(refname:short)" refs/heads/ >actual &&
560 + sed -e "s/^\* / /" actual >expect &&
561 + git checkout --orphan HEAD &&
562 + git for-each-ref --format="%(HEAD) %(refname:short)" refs/heads/ >actual &&
563 + test_cmp expect actual
564 +'
565 +
566 test_done