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
-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.
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?