DEV Community

Erik Nelson
Erik Nelson

Posted on

Splitting a commit with git rebase

I was recently working on migrating a project to GitLab, and had a branch with a some extraneous commits from trying to get CI setup correctly. While I was rebasing I noticed that I had a commit with two separate changes in it. After some digging I found out that I could also use interactive rebase split this commit into two distinct, atomic ones. I'll walk through how we can accomplish this goal.

First, let's perform an interactive rebase so that the commit we want to split is included in the range. In this case we can rebase the entire branch to where it diverged from master, so simply run git rebase -i master. Below we can see a snippet of the interactive rebase:

Screenshot of rebase

The commit we want to split has the hash bc38ac55, so let's change pick to edit.

Screenshot of updated rebase with edit

We can save and exit the editor, now we've gotten the message "Stopped at bc38ac55". Good right? Not quite. What we really want to do is edit bc38ac55, so we need to run git reset HEAD~ to get to a state where the changes haven't been staged and committed yet. After running this command and doing a git status we can see that the changes are present but not staged:

Screenshot of git status

Now we can stage and commit as needed, creating 2 (or more commits). After we're done we can go ahead and run git rebase --continue to finish the rebase. Now when we run git log --oneline we can see our changes.

Screenshot of git log after changes

We can now see the two commits created from the process, and notice that the hash has also changed. Obviously this is something that is best done on a local branch or one that you've been working on solo and can safely force push over to the remote repo.

Hopefully this will be as helpful for you as it was for me!

Discussion (3)

Collapse
jessekphillips profile image
Jesse Phillips

Rather than use a reset, I suggest amending with Git gui. Also consider using partial commits to break up charges even more.

Collapse
erikthered profile image
Erik Nelson Author • Edited on

I'm most comfortable with the git CLI, so that's what I wrote the instructions using. Reset vs amend shouldn't matter much, the hash is going to change regardless. Amend would preserve the message I suppose.

The CLI actually lets you stage individual lines too, check out interactive staging. But I've used GUIs like git-cola for this purpose before, so you can use whatever you're most comfortable with.

Collapse
jessekphillips profile image
Jesse Phillips

Oh most certainly, I showed off the amend and line manipulation to someone and got the response that they use the command line as though that was an excuse not to do it.

If cli works, great, find it too hard for certain operations, get a different tool.