Search

Using Git Hunks

Mike Skalnik

2 min read

Jan 1, 2012

Using Git Hunks

As a developer, I always try to follow the “Boy Scout Principle” when it comes to the code I’m working with. Simply put:

always leave the code cleaner than when you found it

based on the idea that Boy Scouts always leave a campground cleaner than when they found it.

It is tempting to make sweeping changes and clean up lots of code while implementing a small new feature, however, it’s also good practice to separate commits that don’t include any unrelated changes. Occasionally this means that a file that has a few small changes that clean up code, and others that are dealing with some functional changes, needs to get committed. Luckily, git has an awesome feature that allows us to get exactly what we want: hunks.

[Many of the git subcommands can be passed --patch or -p for short. When used with git add, we can compose a commit with exactly the changes we want, instead of just adding whole files. Once you hit enter, you get an interactive prompt where you’re presented with a diff and a set of options.

Some of the more important options are y (yes), n (no), q (quit), and s for “split into smaller hunks”. Using this we can easily create a commit with only the changes I made to clean up a file, instead of any other changes I made. When this isn’t enough, you can also use e (edit) which will open $EDITOR and allow you to modify your diff and get it just right. Once you save, git will make sure that it still applies to the files you’re editing.

Using git add -p allows us to make nice small self-contained commits that only change 1 thing at a time. However, we can use hunks in other places too. git reset -p will allow us to do the exact opposite and unstage things we don’t want to commit by hunk. We can also use it with git checkout to completely get rid of changes we don’t want and may have accidentally added.

This small feature changed how I work, allowing me to crank through a bunch of code and then go back and compose good commits. Are there any small git features that you really enjoy?

Mark Dalrymple

Reviewer Big Nerd Ranch

MarkD is a long-time Unix and Mac developer, having worked at AOL, Google, and several start-ups over the years.  He’s the author of Advanced Mac OS X Programming: The Big Nerd Ranch Guide, over 100 blog posts for Big Nerd Ranch, and an occasional speaker at conferences. Believing in the power of community, he’s a co-founder of CocoaHeads, an international Mac and iPhone meetup, and runs the Pittsburgh PA chapter. In his spare time, he plays orchestral and swing band music.

Speak with a Nerd

Schedule a call today! Our team of Nerds are ready to help

Let's Talk

Related Posts

We are ready to discuss your needs.

Not applicable? Click here to schedule a call.

Stay in Touch WITH Big Nerd Ranch News