Skip to content

Instantly share code, notes, and snippets.

@GuySartorelli
Last active March 11, 2024 20:54
Show Gist options
  • Save GuySartorelli/74627843aeb75e12b777b1f44cb22d2f to your computer and use it in GitHub Desktop.
Save GuySartorelli/74627843aeb75e12b777b1f44cb22d2f to your computer and use it in GitHub Desktop.
How to reset commits on a pull request after retargetting it to a new branch

Resetting commits after retargetting a pull request

Sometimes after retargetting a pull request to a new branch, you'll find a lot of new commits are added to the PR that weren't there before. This is because the branch you used to create the pull request has additional commits on it that aren't in your new target branch.

Solution one: Reset commits

# Show the last commit(s) in your PR branch
git log # take note of the commit hash(es) that relate to your pull request

# Check out the branch your PR is now targetting
git checkout 5.0 # replace 5.0 with whatever branch you need to target the PR to
git pull
# Delete and recreate the LOCAL copy of your PR branch
git branch -D <your-pr-branch-name>
git checkout -b <your-pr-branch-name>

# Cherry-pick your commit(s) - add all of the commit hashes that you noted in the first step
# This will add them on top of the last commit in the branch you want to retarget the PR to
git cherry-pick <commit-hash> [more-commit-hashes]
# Resolve any conflicts at this stage

# Force push your local branch to your fork - this will update the pull request
git push <your-remote> <your-pr-branch-name> --force-with-lease

Solution two: Recreate pull request

If you've given option one an honest attempt but there are still unexpected commits showing in the PR, you can recreate the pull request.

# Checkout the latest changes for the branch you're targetting
git checkout 5.0 # replace 5.0 with whatever branch you need to target the PR to
git pull
# Create a NEW branch for your NEW pull request
git checkout -b <new-pr-branch-name>

Copy or recreate the changes for your pull request, and commit them to your new branch, then create a new pull request like normal. Don't forget to add a link to your new PR from the old one, and link to the old PR from the new one - as well as linking appropriately to whatever issue your PR is fixing.

@johannesx75
Copy link

Quick note: I had to add the local branch name (the one checked out earlier) in the last step:
git push : --force-with-lease

Otherwise I always got: Everything up-to-date

@GuySartorelli
Copy link
Author

GuySartorelli commented Oct 19, 2023

Yes, you're meant to do that. git push <your-remote> <your-pr-branch-name> --force-with-lease where <your-pr-branch-name> is the name of the branch you are using for your PR. At that point your local branch name and the remote branch name should be the same, even though the commits are different.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment