git.day/3 • See all at git.day
Continuing from Git of the day #2: git add --interactive, the most common use of interactive add for me is to add specific hunks of changes. These are sections of diff grouped by proximity, allowing for parts of files to be added rather than the whole file in one go.
Running git add -p
, short for --patch
, begins an interactive session starting with the first hunk. A file path can be specified to start with a specific file instead.
With the hunk shown in the normal diff format, various options are now available shown in the last line:
(1/2) Stage this hunk [y,n,q,a,d,j,J,g,/,e,?]?
Code language: JavaScript (javascript)
Each option is invoked by typing the corresponding letter.
letter | mnemonic | stage this | navigate to | description |
---|---|---|---|---|
y | yes | yes | next hunk | stage this hunk |
n | no | no | next hunk | do not stage this hunk |
q | quit | no | exit | do not stage this hunk or any of the remaining ones |
a | all | yes and remaining in this file | next file | stage this hunk and all later hunks in the file |
d | do not | no | next file | do not stage this hunk or any of the later hunks in the file |
s | split | undecided | first hunk in split | split the current hunk into smaller hunks |
j | vim motion | undecided | next undecided | leave this hunk undecided, see next undecided hunk |
J | vim motion | undecided | next hunk | leave this hunk undecided, see next hunk |
k | vim motion | undecided | previous hunk | leave this hunk undecided, see previous undecided hunk |
K | vim motion | undecided | previous hunk | leave this hunk undecided, see previous hunk |
g | go to | undecided | user selected | select a hunk to go to |
/ | vim motion | undecided | user regex match | search for a hunk matching the given regex |
e | edit | if patch applies cleanly | next hunk | manually edit the current hunk |
Various options only appear if relevant. For example, s for split, which only appears when there are unchanged lines between two edited lines in close proximity. This splits the hunk into multiple, allowing for staging even smaller ranges of changes than an automatically chosen hunk.
My favourite option here is e for edit. This opens configured Git editor1 with the hunk diff shown. Edit the code in the hunk, such as
- removing ‘-’ lines by changing the hyphen to a space,
- removing ‘+’ lines by deleting the line,
- or making any other edits to the lines.
Once editing is done, save and close the file to apply it. If there are any problems with the editing of the hunk, the hunk remains undecided and can be edited again (or any other option chosen). Otherwise with no problems, the hunk is staged (added) and interactive add moves on to the next hunk.
- GIT_EDITOR environment variable,
core.editor
in Git config, or the fallback to VISUAL or EDITOR environment variables. ↩︎