Pick for 9.5: "Refactor how we fetch ref for merge requests"
Picked and resolved conflicts from https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/13416
Picked and resolved conflicts from https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/13416