When you’re making pull requests in Bitbucket, GitHub, GitLab, SourceForge, or other Git servers as a services, then often you’ll run into the scenario where unwanted modified files make it into your PR.
Now, the reasons for why you want to remove it are plentiful. It could simply be that you accidentally ran
$ git add on the file or on its directory and added it accidentally. It could be that the file has only formatting changes or newlines or spaces that don’t really need to make it in the target branch. It could be that you changed your mind on including the modified file in this particular pull request.
Whatever the reason, the ability to pull the file out of the pull request without removing it entirely from your project is extremely useful and one that you’ll be reaching for again and again — I know I do.
In the spirit of keeping pull requests limited to just important changes and making them more digestible for reviewers, read on for some simple steps on how to achieve this.
Make sure you’re on the source branch
Basically, you’ll want to make sure you switch locally to the branch that you created the pull request from. So if you were on branch
feature/A and created a pull request to be merged into
master, then make sure you’re on
feature/A. From the command line, you can run:
If you just made the pull request, then there’s a likely chance that you’re already on the source branch, and thus you won’t need to perform this step at all.
Once you’re on the source branch, then you can move on to the next step.
Overwrite the file you wish to remove from the pull request
Let’s say you accidentally modified and committed a file named
What you can now do is overwrite that file with a different branch. You can do it from the
master branch, for instance, to restore it to the state that it once was. To do so, run the following command:
Now, if you run
$ git diff, you’ll see that the original file has been restored locally and your unwanted changes from before have been overwritten.
Commit and push to remove the changes in the pull request
To make things formal in the pull request, now all you have to do is do your usual
$ git commit and
$ git push commands; respectively, you would run them in the general format of the following:
This approach works for a lot of use cases but not all of them.
For one, this will erase your changes since you’re overwriting them in the “Overwrite the file you wish to remove from the pull request” step.
Secondly, this change is tracked in the git history and leaves the previous commit there as well, and some use cases would like that entirely scrubbed.
If these aren’t too much of an issue, though, then I find this is one of the most straightforward and quick ways to clean up a PR of commit(s) you didn’t intend to make it.