Patching with Git (git add -p)

In this video you will learn how to use git add -p to interactively choose whether to accept or discard the individual changes between the index and your current working tree.

This is exactly the sort of thing that sounds scary, confusing, or needless - git add --all for the win, amiright?

Well, using git add -p will more than likely allow you to spot careless, or potentially embarrassing commit mistakes before they ever reach your remote repository.

Ringing The Shame Bell

I recently had to switch from using OSX and Ubuntu to using Windows. I still got to use PHPStorm (thank the Lord), but I made a boo-boo. I forgot to change the line endings from Windows format (CRLF) to Linux (LF).

"So what?" you may be thinking.

Well, by doing this, I accidentally committed a single line change that git thought had changed the entire file.

When this code went in for code review, the reviewer promptly - and correctly - rejected my change and sent it back to me to change.

I learned a valuable lesson - shame will do that for you - so hopefully you don't have too.

Keep your changes clean, catch potential errors or bad commits before they leave your development machine, and keep your central repo super clean and your code reviewers happy :)

Official Git Manual Blurb for git add -p

-p --patch

Interactively choose hunks of patch between the index and the work tree and add them to the index. This gives the user a chance to review the difference before adding modified contents to the index.

This effectively runs add --interactive, but bypasses the initial command menu and directly jumps to the patch subcommand. See “Interactive mode” for details.

What Do All The Options Mean?

Yes, I was terribly confused the first several times also :)

Stage this hunk [y,n,a,d,/,j,J,g,e,?]? ?
y - stage this hunk
n - do not stage this hunk
a - stage this and all the remaining hunks in the file
d - do not stage this hunk nor any of the remaining hunks in the file
g - select a hunk to go to
/ - search for a hunk matching the given regex
j - leave this hunk undecided, see next undecided hunk
J - leave this hunk undecided, see next hunk
k - leave this hunk undecided, see previous undecided hunk
K - leave this hunk undecided, see previous hunk
s - split the current hunk into smaller hunks
e - manually edit the current hunk
? - print help

Learn more about all the options for git add.

Code For This Course

Get the code for this course.