Last Updated: February 25, 2016
·
1.863K
· victorquinn

git: add files by hunk

Often I just want to commit some bits of a file and not others. Perhaps I have a change at the top that's ready to be committed but one at the bottom I want to defer.

For cases like this, simply use

git add -p

And git will interactively ask you about each hunk:

$ git add -p
diff --git a/chance.js b/chance.js
index ec32b52..cf4ddbb 100644
--- a/chance.js
+++ b/chance.js
@@ -143,6 +143,7 @@

     Chance.prototype.integer = function (options) {
         var num, range;
+        // This is a useless change, do not commit ;)

         options = initOptions(options, {min : MIN_INT, max : MAX_INT});

Stage this hunk [y,n,q,a,d,/,e,?]?

It'll show you a diff for each one and you can add or ignore it.

Choosing the option ? will bring up the help menu, which I've pasted below for convenience (shout out to @bobz for the suggestion!)

Stage this hunk [y,n,q,a,d,/,e,?]? ?
y - stage this hunk
n - do not stage this hunk
q - quit; do not stage this hunk nor any of the remaining ones
a - stage this hunk and all later hunks in the file
d - do not stage this hunk nor 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 help

You'll see there are actually some hidden options there which can be quite useful!

I use it basically every time I commit so I added an alias for this in my .gitconfig:

[alias]
    a = add -p

Then I can just use

git a

And it will ask me hunk by hunk what I want to commit.

Not only is this useful for staging only part of a file, but helps when working with a team as it'll force you to review each change before adding it.

Using this, I can make sure I'm never the guy who accidentally commits the merge conflict :)

2 Responses
Add your response

Enhancement request: what do all the response options do?

over 1 year ago ·

Done! Thanks for the suggestion @bobz

over 1 year ago ·