Partial commit with Git

Published on Saturday, 10 May 2014 in Trick ; tagged with trick, git, add, patch, commit ; text version

Have you ever been in a situation where you are constantly using a tool and you feel like it misses an important feature for you?

Well a couple of days ago I felt like you with Git but not anymore thanks to git add --patch!

I constantly use Git. It offers so many essential features that I use it for everything:

That is to say that without Git, my life would be really sad :(

My problem

I have a bad habit when I code though.

I am really fond of the PEP8 because it offers really nice rules which give good looking code and make reviews way easier. Because of that, I really try to be constant when following these rules and when I see a line that break one of them, I can't stop myself to fix it.

This means that I often have several things in one commit (new code plus pep8 fixes). I know that I should not since a commit should only deal with one and only one thing.
This article nicely explain how a commit should be:

But until a couple of days before, I never figured out how to avoid this because I did not think that it was possible to partially commit a file with Git (and I should be ashamed because it was obvious that this feature had to exist!).

Partial commit with git --patch

When reading the Git man page of the add command (for some unrelated reasons), I stumbled onto this entry:

   git-add - Add file contents to the index

. . .

    . . .
    -p, --patch
       Interactively choose hunks of patch between the index and the work
       tree and add them to the index. This gives the user a chance to
       review the difference before adding modified contents to the index.

       This effectively runs add --interactive, but bypasses the initial
       command menu and directly jumps to the patch subcommand. See
       “Interactive mode” for details. License WTFPL2