Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 683
kaqqao Avatar asked Jul 16 '26 11:07

kaqqao


1 Answers

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

At this point, your pull request on the server will contain only the relevant commits, with the unrelated work still being available on the unrelated-stuff branch.

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.

A great resource for understanding and learning git is http://learngitbranching.js.org - have a look if you are interested!

like image 93
Robert Rossmann Avatar answered Jul 19 '26 03:07

Robert Rossmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!