You sat down to fix a validation bug, and forty minutes later the file also contains a renamed method, a corrected comment, and an unrelated typo fix. git add app/ would bake all of that into one commit. git add -p is how you split it instead.
Stage by hunk, not by file#
git add -p app/Http/Requests/StoreInvoiceRequest.php
Git walks through the file’s changes hunk by hunk and asks what to do with each:
Stage this hunk [y,n,q,a,d,s,e,?]?
The keys worth memorizing:
y- stage this hunkn- skip it (stays in your working tree)s- split the hunk into smaller pieces, when Git’s chunk is too coarsee- edit the hunk manually, for the cases splitting cannot reachq- stop; everything already chosen stays staged
Two passes and you have the validation fix staged as one commit while the rename waits in the working tree for its own. This is the mechanical skill underneath Tidying Commits Before You Open a Pull Request - clean commits are much easier to build at staging time than to reconstruct afterwards.
Why it matters beyond tidiness#
Partial staging is also a review tool. Going hunk by hunk forces you to look at every change once more before it is committed - the same effect as reviewing your own pull request, but earlier and cheaper. The leftover dump() rarely survives a git add -p pass.
And it keeps each commit revertable. When the typo fix and the validation fix are separate commits, rolling back a bad one with git revert does not take the good one with it - the payoff promised in When to Reset, Restore, or Revert.
The same idea elsewhere#
git checkout -p, git restore -p, and git stash -p all speak hunk-level too: discard part of a file, or stash only the experiment while keeping the fix. Once the hunk way of thinking clicks, half of Git’s plumbing turns out to support it.
One honest caveat: staging part of a file means the committed state is one you never ran. For risky splits, git stash --keep-index before testing stashes the unstaged half so you can run the test suite against exactly what you are about to commit.
Share this post
Keep reading
Annotating Commits with git notes: Metadata Without Rewriting History
Some things belong on a commit but not in it: review links, benchmark results, the ticket nobody remembered to reference. git notes adds them after the fact, no rebase required.
Backing Up Your Git Server So It Actually Restores
Every clone is a partial backup - but hooks, config and server state live outside the repo. Mirror, bundle, copy off-site, and rehearse the restore.
Cherry-Picking: One Commit Without the Branch
Cherry-pick copies a single commit onto your branch and leaves the rest behind. Right for hotfixes across release branches, wrong as a sync strategy.