Reviewing Your Changes Piece-by-Piece Before Commiting, with Git

If you’ve ever worked on a tough piece of code, you know that there is some trial and error involved. You add code, try it, tweak it, sometimes remove it altogether and then attempt to change a different part. Sometimes, at the end of a whirlwind session, do you worry you left something in that eventually didn’t need to be there?

You can use the patch option of git add to verify each and every change you’ve made to your code, so you can decide which to keep and which to throw out. Just use the -p option, like so:

mysite$ git add -p
diff --git a/index.html b/index.html
index 4e5050b..da78acf 100644
--- a/index.html
+++ b/index.html
@@ -5,5 +5,8 @@

   <h1>Hello, World!</h1>
+  <ul>
+    <li><a href="about.html">About</a></li>
+  </ul>
Stage this hunk [y,n,q,a,d,/,e,?]? y

When you’re finished, only the changes you’ve approved will be saved at your next commit. The other changes won’t be wiped out – they’ll still be in your code for you to remove as you see fit. But they won’t be “staged” for the next commit, so they won’t make it into your repository.

Another use is when you realize you made changes that should have been committed, but now you’re partway through another feature. You can commit the finished changes, while excluding the changes that are still in progress.


Tags: , , , ,

3 Responses to “Reviewing Your Changes Piece-by-Piece Before Commiting, with Git”

  1. DGM Says:

    If you use a Mac, GitX is an excellent tool for this. I use it to review and stage all my commits to be sure I’m committing only what I need.

    • Jaime Bellmyer Says:

      Funny you should mention it. I’ve actually been a long-time Linux user on Dell hardware. But recently I’ve made the decision to switch to Mac. Since the Rails community is predominantly Mac, it’ll make it easier to collaborate with others and resolve any tech issues that come up. Right now I’m stuck waiting for the Mac refresh because the big thing I was looking forward to with this year’s new Dell purchase was quad core! As soon as that happens, I’ll give GitX a try.

  2. DGM Says:

    I’ve been a Linux user since about 1995, and used to make fun of macs… but I got a Macbook Pro a few years ago to work on my first rails contract…. and it paid for itself in a year. :) I love it, as I’m less distracted by tinkering with the OS and can focus on programming more.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: