Git: Improve your commits by reviewing changes one-by-one

Git commits should be very deliberate, and only contain changes that you really want to be in there. In order to reduce the chance to accidentally commit something you didn't intend, review your changes before committing.

My preferred way of doing this is (only using git)

git add -N . # Add all paths, but not their contents
git add -p

Git will now show you all your changes in small chunks and ask you in an interactive mode whether you really want to add them.

The most helpful commands are

  • y: yes (add the change)
  • n: no (discard the change)
  • s: split (try to make smaller chunks)
  • d: skip the rest of the file
  • q: abort
  • ?: help

Note: Sometimes you add a hunk accidentally. With git reset -p you can unstage hunks easily.

Speedup: How to stage hunks with a single key press

Another way to do this is to use tig:

tig status

Will show you all changed files (tracked and untracked).

  • You can add whole files with u,
  • View changes of a file with Enter and navigating in them with j (down) and k (up)
  • Only add (or remove) certain chunks through navigating in the changes and select the current chunk for adding/removing with u
  • Only add (or remove) certain lines through navigating in the changes and select the current line with 1
  • Split a chunk with \
Tobias Kraze Over 11 years ago