I have been asked to split up several unrelated changes in one file, that I have in one local commit, into two separate commits (say I fixed a bug, but also did some spellchecking, which is not supposed to be part of the fix). Basically, I need to "cherry-pick" some changes out of an existing commit into a new one. Can git help me with that in any way? What is the best method to achieve that?
There are a few options on how to approach this. The easiest situation would be if the commit you want to split up is the latest commit. So when you run git show
, then it shows that commit.
In that case, the easiest way would be to just reset that commit and commit the changes again:
# Remove the commit, but keep all changes
git reset --soft HEAD~1
This will leave you with all the changes from that commit in the index. From there, you can modify the index to include only those changes that you want to commit first. You can work with git reset -p
or git add -p
to do an interactive patch-based addition or removal of staged changes. You could also invoke git gui
to launch the GUI that ships with Git to do this a bit more easily. Of course, you can use any other tool you like.
After you have selected the right changes for the first commit (you can review that using git diff --cached
), just commit them and then work on the next commit. You can repeat that process for as many separate commits you need, until all the pending changes are eventually committed.
If the commit you want to split up is not the latest, then the process is a bit more complex. You can use interactive rebasing to basically edit the commit you want to split up. Interactive rebasing will then put you in a temporary state where that commit is the “latest”. At that point, you can follow the process from above, and continue the rebasing after you are done.
Committing a part of a file is one of the rare occasions I use a GUI tool. And when I do so, I usually use git-cola : https://git-cola.github.io/
With that, you can easily select which part of the file you want to add to a commit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With