Have you ever made changes to a file and wanted to commit only some of those changes. Perhaps, along with with your modifications, you’ve also added a lot of instrumentation code to a source file which really shouldn’t be part of the commit. Or maybe you’ve worked on two features in one source file, each of which deserving of their own commit, but you forgot to commit the first feature, so now it appears you have to put the two features in one commit.
Well it turns out Git has a solution to this problem and it’s quite easy to learn how to use it. It’s also very much worth your while to learn it. Plus it helps to explain why Git has an index, unlike most other VCS’s.
So lets say you have a file called
helloworld.c which has some changes you would like to commit and some you would rather not. Add it to the index by using the familiar
git add command, but this time pas in the
--patch option (or
-p for short).
git add --patch helloworld.c
Git will then present you with “hunks” of helloworld.c and prompt you to indicate whether or not you want the hunk to be staged. Use y to indicate that you want to stage the hunk, and n to indicate you don’t want to stage the hunk.
Here is a complete list of the options:
- y stage this hunk for the next commit
- n do not stage this hunk for the next commit
- q quit; do not stage this hunk or any of the remaining hunks
- a stage this hunk and all later hunks in the file
- d do not stage this hunk or any of the later hunks in the file
- g select a hunk to go to
- / search for a hunk matching the given regex
- j leave this hunk undecided, see next undecided hunk
- J leave this hunk undecided, see next hunk
- k leave this hunk undecided, see previous undecided hunk
- K leave this hunk undecided, see previous hunk
- s split the current hunk into smaller hunks
- e manually edit the current hunk
- ? print hunk help
Now you can check what has been staged by diffing the index:
git diff --cached
If you noticed that you’ve staged a change that you don’t want, you can reverse the operation with this command:
git reset HEAD -p
This will do exactly what
git add -p, except in reverse.
Once you have everything staged the way you want it, you can commit you changes like normal