George Garside Blog

A place of many ramblings about macOS and development. If you find something useful on here, it's probably an accident.

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.

lettermnemonicstage thisnavigate todescription
yyesyesnext hunkstage this hunk
nnononext hunkdo not stage this hunk
qquitnoexitdo not stage this hunk or any of the remaining ones
aallyes and remaining in this filenext filestage this hunk and all later hunks in the file
ddo notnonext filedo not stage this hunk or any of the later hunks in the file
ssplitundecidedfirst hunk in splitsplit the current hunk into smaller hunks
jvim motionundecidednext undecidedleave this hunk undecided, see next undecided hunk
Jvim motionundecidednext hunkleave this hunk undecided, see next hunk
kvim motionundecidedprevious hunkleave this hunk undecided, see previous undecided hunk
Kvim motionundecidedprevious hunkleave this hunk undecided, see previous hunk
ggo toundecideduser selectedselect a hunk to go to
/vim motionundecideduser regex matchsearch for a hunk matching the given regex
eeditif patch applies cleanlynext hunkmanually 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.

  1. GIT_EDITOR environment variable, core.editor in Git config, or the fallback to VISUAL or EDITOR environment variables. ↩︎

Leave a Reply

No comments