git: Only commit parts of a patched file (hunk-checkin)

Hi, today I read Og Maciels blog entry on Planet GNOME about how he find out to not checkin a whole changed file with git but include/exclude special parts. This is something I needed in the last time much often, but never thought it exists - so with git its very easy.

Now lets have an example, we call it story.txt. It contains the following:

The New Kitten
After their holidays, Ann and Joe decided to get an malani which should be their everyday joy. They decided to get a cat.
It was about 2 weeks old when they take it home and tried everything to make it feel comfortable.
In the end everybody was happy and they lived long and prosper.

So after this was checked in, we see the mistakes… it should be an animal, not an malani and while we correct this, we also fixed the 2 weeks - because a kitten should not be taken from its mother before the 7th week.

Now we wanted to check in both changes - but separatly, because the malani was a typo and the 2 weeks were a logical error.

How to do so with git?

$> git add --patch story.txt

diff --git a/story.txt b/story.txt
index 74fb958..7d7e63b 100644
--- a/story.txt
+++ b/story.txt
@@ -1,7 +1,7 @@
 The New Kitten

-After their holidays, Ann and Joe decided to get an malani which should be their everyday joy. They decided to get a cat.
+After their holidays, Ann and Joe decided to get an animal which should be their everyday joy. They decided to get a cat.

-It was about 2 weeks old when they take it home and tried everything to make it feel comfortable.
+It was about 7 weeks old when they take it home and tried everything to make it feel comfortable.

 In the end everybody was happy and they lived long and prosper.
Stage this hunk [y/n/a/d/s/e/?]? `</blockquote>

This is how git sees it at first - two changes which belong together, because they are neighbours. But we want to change this, so we use the s-key for split.

Stage this hunk [y/n/a/d/s/e/?]? s
Split into 2 hunks.
@@ -1,4 +1,4 @@
 The New Kitten

-After their holidays, Ann and Joe decided to get an malani which should be their everyday joy. They decided to get a cat.
+After their holidays, Ann and Joe decided to get an animal which should be their everyday joy. They decided to get a cat.

Stage this hunk [y/n/a/d/j/J/e/?]? y
@@ -4,4 +4,4 @@

-It was about 2 weeks old when they take it home and tried everything to make it feel comfortable.
+It was about 7 weeks old when they take it home and tried everything to make it feel comfortable.

 In the end everybody was happy and they lived long and prosper.
Stage this hunk [y/n/a/d/K/e/?]? n`</blockquote>

Now you can easily checkin the first change with git commit and than add the second change with git add story.txt (of course you can also split it again into hunks - if your changes are bigger).

Good luck and thanks to Og.