Git Patching Flexibility

I don't know about you, but when I'm coding I'll often need to make a change that's unrelated to the current feature or bug I am working on. I'll notice a spelling mistake, a typo, or some other small code change. You don't want to commit the unrelated change as part of your overall commit because, well, it's unrelated. It should be its own commit with its own commit message. This will make it much easier to read the commit log and cuts down on confusion. People won't have to ask "Why did they change that? It has nothing to do with the change"

When I used Subversion, you had to remove the unrelated change, commit, then add it back in and commit again. Maybe there was a nicer way, but I didn't know it. Git is much nicer.

When you stage a file ready for committing, Git allows you to only stage a certain part or parts of the file, which it calls hunks.

So, run:

git add --patch <filename>

Git will show you a diff of the first difference that it wants to stage and will ask if you'd like to stage the current hunk, like this:

Stage this hunk [y/n/a/d/s/?]?

The options in this example are:

y - stage this hunk
n - do not stage this hunk
a - stage this and all the remaining hunks in the file
d - do not stage this hunk nor any of the remaining hunks in the file
s - split the current hunk into smaller hunks

Choose what you'd like to do with the current hunk. Git will continue to go through the rest of the hunks in the file, asking you what to do with each one.

When you've decided which hunks should be staged, commit as normal and only those changes will form part of the commit. You can then add the rest of your changes and commit again.

It's the flexibility that's great. It works with you, not against you.

For a much more in depth look at the capabilities of git add --patch, see the following article.