Splitting a commit in Git

I must be getting pretty good at Git, because the other day I realized that I wanted to take a set of changes I had made in a single commit and divide them into two, and I was thinking “Hey, Git must have a way to do this!” and lo and behold I was right. Here’s what to do.

First, figure out which commit you want to split. It has its hash, let’s say, abc123. You’re going to use git’s interactive rebase capability to back up to just before the commit, commit its changes in new, multiple commits, and then finish your rebase. History will be rewritten with abc123 replaced. So, avoid doing this to a shared repository, or risk the wrath of your coworkers.

Let’s get started.

$ git rebase -i abc123^

Git will pop open your editor with all of the commits listed from the one before abc123 up until your current HEAD. Mark abc123 as “edit” instead of “pick” and proceed. The rebase will pause at abc123 to let you change stuff. This is where you start being awesome.

$ git reset HEAD^

This rewinds your index and HEAD, backing you up to just before you would have committed abc123. You are now free to do your adds and commits to save the changes piecemeal, doing the split. Once your working tree is clean:

$ git rebase --continue

You end up with the same code as where you started, but with abc123 broken out. The following commits will have the same changes as before, but new hashes because of the changed history.

References:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s