11

I need your help to rename a remote branch.
I created a PR but now I need to rename the remote branch name.
I don't want to follow the process where I have to rename the local branch then push and delete the old branch because it will clear the PR.
Is there a way to just rename the remote branch and PR should stay as it is. thanks.

Ofek Hod
  • 3,544
  • 2
  • 15
  • 26
Vikas Rathore
  • 8,242
  • 8
  • 35
  • 54
  • 2
    As far as i know this is maybe not possible but there is one alternative approach mentioned in this post: https://stackoverflow.com/questions/20007578/renaming-a-branch-while-on-pull-request – Fareed Khan May 29 '20 at 11:32

2 Answers2

15

Renaming a remote branch in Git is really just creating a new branch with same commits and new name and deleting old branch. Depending on where you have pull request open (you don't mention whether is it Github, Gitlab, Phabricator or something else) you might have some options given to you by tool operating on repository locally where pull request exists. I can say only for Github that there's no option to rename a branch in their interface nor option to change "compare" branch in a pull request.

Best solution (for Github) is probably to create a new branch and new pull request, post a comment to old pull-request that it was "closed in favor of #NEW" and "continuation of #OLD" to new one. Then delete old branch which will also close the old pull-request.

Quick oneliner for deleting old branch and creating a new one with same content is:

git push <remote> <remote>/<old>:refs/heads/<new> :<old>

where remote is obvious - e.g. origin, old and new are names of branches old and new respectively.

blami
  • 6,588
  • 2
  • 23
  • 31
  • 1
    when you say "creating a new branch with same commits", does that mean the same commits with the same hashes or will they be new commits with the same content (as though the commits were cherry picked) on the new branch? I'm trying to understand if renaming the branch in Bitbucket creates new commits to review using your command before I actually ... commit to it. – flipdoubt May 17 '23 at 21:08
  • 2
    @flipdoubt same hashes, basically the operation is checkout old branch name as new branch name (so that those branches have identical history) and delete old branch. – blami May 18 '23 at 00:32
  • why is the `refs/heads/` prefix needed? Omitting it tells me that I need it – lucidbrot Jul 12 '23 at 09:40
1

I don't want to follow the process where I have to rename the local branch then push and delete the old branch.

I don't think there's any other way. You could try to change the branch in the PR screen, but I suppose you would've tried it already.

Pull or merge requests are not part of git itself, but a feature of hosting services, such as GitHub or BitBucket. As it's a standard, so to say, the implementation is completely up to the system.

Andrei Mustata
  • 1,013
  • 1
  • 9
  • 21