Merge branch 'ab/fetch-set-upstream-while-detached'

"git fetch --set-upstream" did not check if there is a current
branch, leading to a segfault when it is run on a detached HEAD,
which has been corrected.

* ab/fetch-set-upstream-while-detached:
  pull, fetch: fix segfault in --set-upstream option
This commit is contained in:
Junio C Hamano 2021-12-22 22:48:10 -08:00
commit dcaf17c75d
2 changed files with 32 additions and 0 deletions

View File

@ -1643,6 +1643,16 @@ static int do_fetch(struct transport *transport,
}
}
if (source_ref) {
if (!branch) {
const char *shortname = source_ref->name;
skip_prefix(shortname, "refs/heads/", &shortname);
warning(_("could not set upstream of HEAD to '%s' from '%s' when "
"it does not point to any branch."),
shortname, transport->remote->name);
goto skip;
}
if (!strcmp(source_ref->name, "HEAD") ||
starts_with(source_ref->name, "refs/heads/"))
install_branch_config(0,

View File

@ -91,6 +91,17 @@ test_expect_success 'fetch --set-upstream with valid URL sets upstream to URL' '
check_config_missing other2
'
test_expect_success 'fetch --set-upstream with a detached HEAD' '
git checkout HEAD^0 &&
test_when_finished "git checkout -" &&
cat >expect <<-\EOF &&
warning: could not set upstream of HEAD to '"'"'main'"'"' from '"'"'upstream'"'"' when it does not point to any branch.
EOF
git fetch --set-upstream upstream main 2>actual.raw &&
grep ^warning: actual.raw >actual &&
test_cmp expect actual
'
# tests for pull --set-upstream
test_expect_success 'setup bare parent pull' '
@ -178,4 +189,15 @@ test_expect_success 'pull --set-upstream with valid URL and branch sets branch'
check_config_missing other2
'
test_expect_success 'pull --set-upstream with a detached HEAD' '
git checkout HEAD^0 &&
test_when_finished "git checkout -" &&
cat >expect <<-\EOF &&
warning: could not set upstream of HEAD to '"'"'main'"'"' from '"'"'upstream'"'"' when it does not point to any branch.
EOF
git pull --no-rebase --set-upstream upstream main 2>actual.raw &&
grep ^warning: actual.raw >actual &&
test_cmp expect actual
'
test_done