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.
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:
Each option is invoked by typing the corresponding letter.
|stage this hunk
|do not stage this hunk
|do not stage this hunk or any of the remaining ones
|yes and remaining in this file
|stage this hunk and all later hunks in the file
|do not stage this hunk or any of the later hunks in the file
|first hunk in split
|split the current hunk into smaller hunks
|leave this hunk undecided, see next undecided hunk
|leave this hunk undecided, see next hunk
|leave this hunk undecided, see previous undecided hunk
|leave this hunk undecided, see previous hunk
|select a hunk to go to
|user regex match
|search for a hunk matching the given regex
|if patch applies cleanly
|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.editorin Git config, or the fallback to VISUAL or EDITOR environment variables. ↩︎