`git add -p` has made me a better programmer

If you don’t know about this already, then file it under your collection of “One Simple Trick articles”…

git add -p (AKA git add --patch) will interactively show you each change in your repo and ask you if you want to stage it.

Do you ever use git commit --all? Have you ever accidentally committed more than you meant to?

By using git add -p, you get a chance to review each change. That helps you catch mistakes, like leaving in debugging printlns that you don’t need anymore, or other temporary hacks. Since git add -p will present each change separately, you can even include some changes and exclude others within the same file.

And, it’s not uncommon for me to fix small, unrelated issues while working on a major feature. I’d like for those fixes to go into a separate commit, and git add -p gives me a chance to catch those fixes if I haven’t committed them already.

The other major benefit is that it gives you a refresher on what all you changed before you need to write your commit message. If I work on a big changeset, sometimes it’s hard for me to remember all the important changes that I should write about in my commit message. Quickly running through the changes interactively means that, instead of writing “Add feature X”, I can write more detailed commit messages that list the major areas that have been touched.

Overall, it’s made my commits cleaner and me a more thoughtful programmer.

Don’t blindly commit files. Try git add -p.

P.S. Even though I now mostly use VS Code, I still prefer to review changes in the built-in terminal instead of the Source Control pane. Since git add‘s interactive mode uses single-character commands, I can quickly step through the changes without fiddling with the mouse.

Leave a Reply