Arran's Guide to Fixing a Pull Request
So today I was feeling proud as I fixed a bug with a single line change. I changed if (_groupId != -1)
to if (_groupId < 0)
. I summed up my change in a simple commit message, created a pull request to share my change and continued making the necessary changes to the remote server.
When I tested the changes on the remote server I had a panic moment when I realised my simple change didn’t work. I had got my inequality the wrong way around! The change I’d made was checking if _groupId
was less than 0 rather than greater than 0. Oops.
Fixing the pull request was just another simple commit but that left an untidy pull request with two commits, one with a good clear concise message and another that ‘fixed my fix’. Two commits for a single line of code seems rather excessive so I decided to find a way to condense them down into a single commit.
Editing commits that have already been pushed to a remote isn’t easy but it is possible using the magic of ‘rebasing’. Rebasing allows you to edit the order of your commits, ‘squash’ smaller unnecessary commits into larger more meaningful commits, and change the wording of your commit messages.
For this example we’re going to assume your local branch is called branch
, you have a remote called origin
, and your pull request is on the develop
branch.
The first step is to fetch the latest version of your remote.
git fetch origin
The next step is to find the base commit of your branch.
git merge-base branch develop
The hash for the base commit of your branch should be printed. Use this in your next command.
git rebase --interactive HASH
For the above command replace HASH with the hash you obtained in your previous step. For example if your hash was 12345 you would use the command git rebase --interactive 12345
.
Your default text editor will open a file containing all the commits in your branch (mine opened up in vim) and in front of each branch will be the keyword pick
.
The keyword in front of each commit changes how the rebase happens. GitHub has a handy list of the keywords. I’ll outline a few select ones briefly.
pick
simply includes the commit in the rebase, reword
includes the commit but gives you an opportunity to alter the commit message, and fixup
merges the commit with the one above it and uses the commit above’s commit message.
Instead of using the full word you can use the first letter. For example instead of using pick
you could use the letter p
.
Save and exit the file and if you are modifying any commit messages a new text editor window will open allowing you to save you new message(s).
Once that’s done you need to rebase your changes onto your destination.
git rebase origin/develop
Finally you need to force push your changes so they are reflected in the pull request.
git push -f