In the last post, we covered squashing commits, which consolidates several commits into one single commit.
In this post, we'll do just the opposite, expanding commit history by splitting one commit into multiple commits.
Splitting commits can be useful if you've been working locally and making a lot of changes then make one single commit. It might be hard for your teammates to understand all the changes incorporated under that one commit. So breaking that commit into smaller incremental changes can help them better understand what you've done.
In this example, we'll use the "git rebase" command. As mentioned in previous posts about rebase:
The rebase command is a powerful but potentially dangerous tool, because it has the ability to rewrite commit history. If not used properly, it can cause data loss, cause headaches for team members, and reorder the logical development history of the project which can cause confusion. Use with care!
I'll start the example by adding four files, one at a time, and committing them with the below commit messages, one at a time.
Here's what my git log looks like:
Notice that the commit for "Add three.txt" has the following commit hash:
b60ac6e713f20e407210f9fbcc42c4535a2c6a31
What I want to do is split the commit "Add four.txt" But in order to do that, I need to run the rebase command on the parent hash, the one just before, "Add three.txt".
So I'll use the command "git rebase -i b60ac6e713f20e407210f9fbcc42c4535a2c6a31".
And that will bring me to the following screen:
Now I'll change the "pick" command to "edit". Since we're in the Vim editor, I'll use the "i" character on the keyboard to edit.
I'll the use the Vim command [ESC] :wq to write the file and quit out of the Vim editor. This brings us back to the command line.
At this point Git has paused the rebase of the commit, allow you to amend it. I'll use the command "git reset HEAD^". This puts the changes of that commit back into my working directory. I'm now free to add new files and new commits for the split.
I'll make the following changes using the following commands:
Finally, I'll wrap up the rebase session by using the command "git rebase --continue". Here is the result.
We've successfully split our commit!
Here is my revised git log:
As you can see, the "Add four.txt" commit has been removed and split into two separate commits "Add README.md" and "Add log.txt"
I hope this was helpful! Stay tuned for more posts on Git!