I think git cherry-pick
is probably nicer here, but I like using git rebase -i
, partly because it's so versatile, you can reuse the knowledge.
(1) First, create a new branch (that will be Pull Requested):
git checkout -b commit2_PR
(2) Then, interactive rebase (-i
for interactive):
git rebase -i commit2_PR^^ commit2_PR
NB: the first argument needs to be the parent of the last (oldest) commit of interest.
(3) Your editor will be fired up with the last 2 commits - and very helpful instructions on the bottom. Now delete the line for the commit you don't want in the Pull Request (in this case, delete commit 1, leaving only commit 2). Now, save and exit, and git rebase
will do its thing.
(3.1) If there's a merge conflict, it will stop and you'll have to fix it in the usual way, following the instructions it gives. This happens surprisingly often, when meddling with history.
(4) Finally, this new branch commit2_PR
- you Pull Request that branch. Done.
I highly recommend reading the manpage for rebase (and/or googling), and experimenting with it a few times. There's a simplification you can do with the git rebase
arguments but I'll leave that for you to read the manpage rather than complicating it here... Don't be afraid!!! Note that because you've made a new branch, it doesn't matter if you muck it up or how badly - just delete that branch and have another go. The original branch is still there, unaltered.
There's wonderful stuff you can do to make your Pull Request easier to read - squash (combine) commits together, reorder commits, separate commits (with git add -p
and creating new commits in between), edit commit message, change commit contents as if you were committing them for the first time etc.
It's perfectly fine to rewrite history in this way, provided you haven't pushed yet and it's still private. It's like editing a novel before it's published so it makes more sense, is easier to read and has fewer errors. (e.g. you need to correct an error, but readers don't need to know when you corrected it, if it hasn't been published yet.)