How can I split a commit in two, after I've already committed my changes

Issue

I committed some changes into u-boot (I organized my changes in three commits) and now I want to split the first of my commits in two separate commits (this was proposed from a reviewer). Here is what came to my mind:

  1. clone my branch from remote
  2. git reset –hard HEAD~3
  3. Redo my changes but this time organize them in four commits instead of 3.
  4. git push -f

My doubt is should I have one additional git push -f after step 2? Meaning the sequence is as follows:
1. clone the my branch from remote
2. git reset –hard HEAD~3
3. git push -f (is this necessary, or i can skip this and continue with redo my changes and then push?).
4. Redo my changes but this time organize them in four commits instead of 3.
5. git push

Thanks in advance.

Solution

The strategy you propose can work, but you will have to redo your work, which is more work on top of all your other work. So that’s no good.

What you can do is the following, given the scenarios you have.

  1. If the commit you want to split is the latest commit (the last one you did), then that’s pretty simple.
git reset HEAD^

This will reset your last commit, but you will keep all your changes in your working directory. Then it’s a matter of you just picking which changes you want to go in one commit and which changes go in the second commit (thus splitting your last commit into two). Then you’ll have to force push.

  1. If the commit you want to split is not the latest commit, then things get just a little bit more tricky.

First, checkout the commit you want to split.

git checkout <commit>

Then reset your changes (as in the first scenario)

git reset HEAD^

Add and commit your changes into two commits. Now, at this point, you have successfully split your desired commit, but oh no! What about the other commits on top of this one? You need to cherry-pick those commits one-by-one.

These commits are not lost. You can still find them in your git log and even in your git reflog. For each one of those commits, type git cherry-pick <commit> and bam! You have successfully split a commit in two.

Now there is still a problem here. The branch you were on still points to the old commits. You just need to move that branch to point to the current tip you are on. So you can do git branch -f branch-name new-tip-commit.

Finally, force push your branch so that the remote has your new commits, split!

Answered By – mnestorov

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published