Staging precisely with add -p
Use git add -p to stage individual hunks of a file, split a hunk further, and keep each commit about one thing even when your edits were tangled.
Staging precisely with add -p
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- git add -p walks you through each hunk of your changes and asks whether to stage it, so one file can be split across several commits.
- The most-used answers are y to stage, n to skip, s to split a hunk, e to edit it, and q to quit.
- s only splits a hunk that has an unchanged line between two changes. A single unbroken block of changes cannot be split, and Git says so.
- After a partial add, the file shows as MM: part of it is staged and the rest is still an unstaged edit.
- A half-staged commit can leave the project in a state that does not run, so check git diff --staged before you commit.
The problem: you did two things at once
You sat down to add a count command to tinynotes. On the way you noticed the file had no docstring and added one. Now notes.py holds two unrelated changes. git add notes.py stages the whole file, so both go into one commit.
That is a poor commit. If the count command turns out to be buggy, you can’t undo it without also undoing the docstring. Someone reading history sees “Add a docstring” hiding a feature, or “Add count” hiding a docstring. Small, single-purpose commits are what make history readable and changes reversible.
git add -p (short for --patch) stages parts of a file.
A first run
Here is the diff of that tangled notes.py:
$ git diff
@@ -1,3 +1,4 @@
+"""A tiny notes tool."""
import sys
NOTES = "notes.txt"
@@ -21,3 +22,6 @@ if __name__ == "__main__":
show()
elif sys.argv[1] == "clear":
open(NOTES, "w").close()
+ elif sys.argv[1] == "count":
+ with open(NOTES) as f:
+ print(len(f.readlines()))
I trimmed the headers. Each block starting with @@ is a hunk, a run of changes with a few lines of context around it. There are two, far enough apart that Git treats them separately. Now git add -p. For each hunk Git prints it and asks:
(1/2) Stage this hunk [y,n,q,a,d,k,K,j,J,g,/,e,p,P,?]?
I answered y to the docstring and n to the count command. Afterwards:
$ git status -s
MM notes.py
$ git diff --staged
+"""A tiny notes tool."""
import sys
$ git diff
+ elif sys.argv[1] == "count":
+ with open(NOTES) as f:
+ print(len(f.readlines()))
MM is the two-halves state from the three-areas lesson: staged changes and unstaged changes in the same file. I skipped the diff headers again. git diff --staged shows exactly the docstring, so the commit is the one I wanted:
$ git commit -m "Add a docstring to notes.py"
[main 9c02f7a] Add a docstring to notes.py
1 file changed, 1 insertion(+)
The count command is still in my working file as an unstaged change, ready for its own commit.
The answers worth memorising
Type ? at the prompt for the full list. These are the ones you’ll use:
| Key | Meaning |
|---|---|
y |
stage this hunk |
n |
skip it for now |
q |
quit; hunks already staged stay staged |
a |
stage this and every later hunk in the file |
d |
skip this and every later hunk in the file |
s |
split the hunk into smaller hunks |
e |
open the hunk in your editor and edit what gets staged |
? |
help |
Letters like j, k and g move between hunks without deciding.
Splitting a hunk
Sometimes two changes land in one hunk. I changed the signature of add and the line that writes the text, two lines apart:
@@ -4,9 +4,9 @@ import sys
NOTES = "notes.txt"
-def add(text):
+def add(text, prefix=""):
with open(NOTES, "a") as f:
- f.write(text + "\n")
+ f.write(prefix + text + "\n")
The prompt now offered s. Answering it printed “Split into 2 hunks”, and I staged only the first, the signature. That lets you commit pieces of one tight block.
Now the limit, which I hit by accident while writing this. I answered s on a hunk that was a single changed line, and Git printed:
Sorry, cannot split this hunk
Git splits only where an unchanged line sits between two changes. A hunk that is one unbroken block of changes, such as one edited line or one inserted function, has nowhere to split. If you need to stage half of such a block, the answer is e, which opens the hunk in your editor so you can delete the + lines you don’t want staged. That works, but it is fiddly.
Watch out: partial commits may not run
Look at the split I just made. The staged half changed the signature to def add(text, prefix=""). That’s harmless by itself. Staging only the second half, f.write(prefix + text ...), would be a commit that refers to a prefix that doesn’t exist, which crashes. Git doesn’t know or care. When you split hunks it’s easy to build a commit that never existed as a working state on your disk, so look at git diff --staged before committing, and ask whether this half stands alone. A later lesson on stashing shows git stash push --keep-index, which stashes the unstaged part so you can run your tests against only what you staged. I didn’t run it for this lesson.
git add -p only offers changes to files Git already tracks. A brand-new file is untracked, so add it by name first.
What the video covers
typecraft’s “The BEST git command you’ve never heard of | GIT ADD PATCH” is just over five minutes and was published around 2023. I had no transcript. The title says it is about git add -p, and it should show the same flow as above. The channel is English-language. Nick Janetakis’s video on the same command is linked as the second view.
Where this fits
Now each commit can hold just one idea. The next question is what to say about it: writing good commit messages.
Check yourself
You changed two unrelated things in notes.py. How do you commit them separately?
Run git add -p, answer y for the hunk of the first change and n for the second, commit, then repeat for the second change.
What does the s answer do, and when does Git refuse it?
It splits the current hunk into smaller ones. Git refuses with 'Sorry, cannot split this hunk' when the hunk has no unchanged line between changes.
After git add -p stages some hunks, what does git diff show?
The hunks you did not stage. git diff --staged shows the ones you did.
Why review git diff --staged before committing a partial add?
The staged half may depend on the unstaged half, so the commit could be a state that never worked on your machine.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.