Thursday, January 20, 2011

'git add -p'

Hi, it is NISHIO Hirokazu. I just found "git add -p" is very nice. I show it.

Here is a sample script. I'm going to add new function on it.


def hallo():
print "hello!"


When I added new function 'bye', I also found there is a typo s/hallo/hello/. I fixed it too. Let me show 'git diff'


$ git diff
@@ -1,2 +1,5 @@
-def hallo():
+def hello():
print "hello!"
+
+def bye():
+ print "bye!!"


Now I wanted to commit it, but there are two changesets. I didn't want to commit all in one changeset. That's when I should use 'git add -p'!


$ git add -p
@@ -1,2 +1,5 @@
-def hallo():
+def hello():
print "hello!"
+
+def bye():
+ print "bye!!"
Stage this hunk [y,n,q,a,d,/,s,e,?]?


Git asked me whether choose the block of changes (hunk). But it contains both changes... I chose 's' to split it.


Stage this hunk [y,n,q,a,d,/,j,J,g,e,?]? s
Split into 2 hunks.
@@ -1,2 +1,2 @@
-def hallo():
+def hello():
print "hello!"
Stage this hunk [y,n,q,a,d,/,j,J,g,e,?]?


Now I pressed 'y' to choose the hunk, 'n' to skip another hunk and commit.

Stage this hunk [y,n,q,a,d,/,j,J,g,e,?]? y
@@ -2 +2,4 @@
print "hello!"
+
+def bye():
+ print "bye!!"
Stage this hunk [y,n,q,a,d,/,K,g,e,?]? n

$ git commit -m "fix typo"
[master 82bd7c6] fix typo
1 files changed, 1 insertions(+), 1 deletions(-)


Let me show 'git diff' again. The other modification left. Add it and commit it.

$ git diff
@@ -1,2 +1,5 @@
def hello():
print "hello!"
+
+def bye():
+ print "bye!!"

$ git add .
$ git commit -m "add new function: 'bye'"
[master fd5ab40] add new function: 'bye'
1 files changed, 3 insertions(+), 0 deletions(-)


How nice is it! Does other VCS (mercurial, subversion etc.) has such feature?