kaqqao kaqqao - 9 days ago 5
Git Question

Remove commits from an existing pull request

I forked a project on Github, made a commit, pushed to my fork and made a pull request. All good to that point.

Then, I kept committing and pushing unrelated stuff unaware that all of that will be added to my pull request.

I need the changes I made in my fork preserved (in a different branch or something), but I must remove all but the first commit from the pull request. How do I do this?

Answer

First, make sure your current working tree is clean and then create a new branch on the last commit to make sure you do not lose your work:

git stash
git checkout -b unrelated-stuff

Now, you switch back to the pull request branch:

git checkout feature

And then you reset the branch to point to a particular commit ID (you will find the ID via git log or via any GUI application):

git reset --hard COMMIT_ID

Once you have your local feature branch pointing to the commit you like, you may force-push that branch to the server:

git push --force

If you had any unsaved work before you git stashed it, you can get it back with git stash pop.

Please note that force-pushing is a highly discouraged operation in git, because it could break other people's local repositories. It should be generally ok in the context of pull requests (many repo owners prefer merging PRs only when they are clean and tidy after reviewing), but never ever force-push into master or other branches where there is potential that other people are working on.

Comments