git add -p
Stop doing this:
git add .
git add -A
Use this instead:
git add -p
# or
git add --patch
It walks you through each hunk and asks what to do. You get a mental refresher on what you actually changed, and you can leave the messy bits out of the commit.
The prompts
For each hunk you’ll see something like:
Stage this hunk [y,n,q,a,d,s,e,?]?
The ones that matter most:
| key | meaning |
|---|---|
y | stage this hunk |
n | skip it |
s | split into smaller hunks |
a | stage this and all remaining in the file |
d | skip this and all remaining in the file |
q | quit |
? | help |
A real workflow
You’re mid-feature and also fixed a typo in the README. Don’t let those ride together.
git add -p
- README typo hunk →
y - feature hunks →
nfor now (or the other way around)
Commit the small fix, then come back for the feature:
git commit -m "Fix typo in README"
git add -p
git commit -m "Add theme toggle"
Split when a hunk is too big
If git offers one giant hunk that mixes two ideas, hit s:
Stage this hunk [y,n,q,a,d,s,e,?]? s
It breaks the hunk into smaller pieces so you can stage only the part that belongs in this commit.
Scope it to a path
You don’t have to review the whole repo:
git add -p app/components/ThemeToggle.tsx
git add -p lib/
One rule
If you can’t explain why a hunk is in the commit, don’t stage it yet.