Commit hygiene: staging hunks and writing useful messages
Turn an afternoon of mixed edits into focused commits: keep generated files and secrets out, stage hunks with `git add -p` and write messages that explain why.
Contentsand lesson path
On this page
- The problem
- Step 1: Keep generated files and secrets out
- Step 2: Stage only the fix with git add -p
- Step 3: Write a message that explains why
- Step 4: Commit the formatting change and drop the debug line
- Check your understanding
- Apply it
- Review prompt
Lessons of Git Workflow
- Git's model: snapshots, commits and pointers Concept · 15 min
- Commit hygiene: staging hunks and writing useful messages Worked example · 15 min
- Branching, merging and resolving a real conflict Lab · 25 min
- Pull requests, reviews and short-lived branches Concept · 20 min
- Recovering from mistakes without breaking teammates Lab · 20 min
- Check: repository-state challenges Knowledge check · 8 questions
What you will learn
- Explain the working tree, staging area, commits and refs, and make small, focused commits with clear messages.
01. The problem
You have spent the afternoon on report.py, a small script that emails a daily sales summary. Your working tree now mixes three unrelated things:
- a bug fix: the script crashed on days with no sales, because it divided by zero
- a formatting change: names and amounts now line up in columns
- a debug
printyou added while hunting the bug and do not want to keep
Git has also noticed two things it should never store: a .env file holding a local API token, and a __pycache__/ folder of generated bytecode.
git add . followed by one commit would bundle all of that together. The history would say little about why anything changed, a reviewer would have to untangle three ideas in one diff, and undoing the formatting later would undo the fix as well. The goal of this walk-through is three focused commits, each with a message that will still make sense in a year. The example is Python, but the commands work the same in any language.
$ git status --short
M report.py
?? .env
?? __pycache__/
$ git diff --stat
report.py | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)In the short format, the first column describes the staging area and the second the working tree: M means modified but not staged, and ?? means untracked. Your commit hashes will differ from the ones shown in this lesson.
02. Step 1: Keep generated files and secrets out
Deal first with the files that should never be committed. A .gitignore file at the top of the repository lists patterns for Git to leave untracked. Commit it, so that everyone who clones the repository gets the same rules.
$ printf '__pycache__/\n.env\n' > .gitignore
$ git status --short
M report.py
?? .gitignore
$ git add .gitignore
$ git commit -m 'Ignore Python caches and the local .env file'
[main f6a907c] Ignore Python caches and the local .env file
1 file changed, 2 insertions(+)
create mode 100644 .gitignore.env and __pycache__/ have dropped out of the status. A pattern ending in a slash, such as __pycache__/, matches a directory of that name anywhere in the project. Typical entries are build output, dependency folders such as node_modules/ or .venv/, editor settings, large data or model files that belong in other storage, and anything that holds credentials.
Ignore rules only affect files Git is not already tracking. A file that was committed before you ignored it stays tracked; the common mistakes below show the fix.
03. Step 2: Stage only the fix with git add -p
git add -p (short for --patch) walks through your changes one hunk at a time, a hunk being a block of nearby changed lines, and asks whether to stage each one. The answers you will use most are y (stage it), n (skip it), s (split it into smaller hunks, possible when unchanged lines separate its changes), e (edit the hunk by hand), q (quit) and ? (help). The exact list of letters varies a little between Git versions and between hunks.
$ git add -p report.py
diff --git a/report.py b/report.py
index 649f569..cd08f9c 100644
--- a/report.py
+++ b/report.py
@@ -2,6 +2,8 @@
def average(values):
+ if not values:
+ return 0.0
return sum(values) / len(values)
(1/3) Stage this hunk [y,n,q,a,d,j,J,g,/,e,p,?]? y
@@ -12,7 +14,7 @@ def summarise(sales):
def format_line(name, value):
- return f"{name}: {value}"
+ return f"{name:<6}{value:>10.2f}"
def main():
(2/3) Stage this hunk [y,n,q,a,d,K,j,J,g,/,e,p,?]? n
@@ -20,6 +22,7 @@ def main():
summary = summarise(sales)
for name, value in summary.items():
print(format_line(name, value))
+ print("DEBUG", name, value)
if __name__ == "__main__":
(3/3) Stage this hunk [y,n,q,a,d,K,g,/,e,p,?]? nBefore committing, look at what you are about to record. git diff --staged shows the staging area against the last commit; git diff shows what is left in the working tree.
$ git diff --staged
diff --git a/report.py b/report.py
index 649f569..772f01c 100644
--- a/report.py
+++ b/report.py
@@ -2,6 +2,8 @@
def average(values):
+ if not values:
+ return 0.0
return sum(values) / len(values)
$ git diff --stat
report.py | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)Only the fix is staged; the formatting change and the debug line are still in the working tree, untouched. Reading the staged diff before every commit is the most effective hygiene habit you can build. It catches stray debug code, commented-out experiments and accidentally added files while they are still easy to drop.
04. Step 3: Write a message that explains why
A commit message has two parts, separated by a blank line.
- The subject line says what the commit does in about 50 characters or fewer. Write it in the imperative mood, as an instruction to the code base ("Return 0.0…", not "Returned…" or "Returns…"), start with a capital letter and leave off the full stop. A handy test is that the subject should complete the sentence "If applied, this commit will…". Short subjects matter because
git log --oneline, the commit lists on GitHub and many other tools show only that line. - The body explains why: the problem, the reason for this approach, and any side effects a future reader should know about. Wrap it at about 72 characters. The diff already shows what changed line by line, so the body should not repeat it.
Running git commit without -m opens your editor so you can write both parts comfortably. This is the message for the fix:
Return 0.0 when averaging an empty list
On days with no sales, average() divided by zero and the nightly
report crashed before it was sent. Treat an empty list as an
average of 0.0 so the report still goes out and shows the gap.$ git commit
[main 64cf8e4] Return 0.0 when averaging an empty list
1 file changed, 2 insertions(+)If you prefer the command line, git commit -m 'Subject' -m 'Body' turns each -m into its own paragraph. If your team tracks work in GitHub issues, mention the issue in the body; a line such as Fixes #42 closes issue 42 once the commit reaches the default branch.
05. Step 4: Commit the formatting change and drop the debug line
Repeat the loop for the second idea: run git add -p report.py again, answer y for the formatting hunk and n for the debug hunk, check git diff --staged, then commit with this message:
Align names and amounts in the report
Readers compare totals by eye in the email; fixed-width columns
make the figures line up. Amounts now always show two decimals.The debug line is all that is left, and you do not want it. git restore report.py copies the staged version of the file, which now matches the last commit, back over the working tree. Check with git diff first: edits discarded this way were never committed, so Git cannot bring them back.
$ git commit
[main f8e994d] Align names and amounts in the report
1 file changed, 1 insertion(+), 1 deletion(-)
$ git diff
diff --git a/report.py b/report.py
index 524bc94..cd08f9c 100644
--- a/report.py
+++ b/report.py
@@ -22,6 +22,7 @@ def main():
summary = summarise(sales)
for name, value in summary.items():
print(format_line(name, value))
+ print("DEBUG", name, value)
if __name__ == "__main__":
$ git restore report.py
$ git status
On branch main
nothing to commit, working tree clean
$ git log --oneline
f8e994d (HEAD -> main) Align names and amounts in the report
64cf8e4 Return 0.0 when averaging an empty list
f6a907c Ignore Python caches and the local .env file
c10f55a Add daily sales reportThree new commits, three ideas. A reviewer can read each one on its own. If the new column format breaks someone's email filter, the formatting commit can be undone on its own while the fix stays. And git log --oneline now reads like a short changelog.
06. Check your understanding
07. Apply it
Next time your working tree holds more than one idea:
- Run
git status --shortandgit diff --stat, and write down the separate changes you can see. - Make sure the project has a
.gitignorecovering build output, dependencies, local environment files and data that does not belong in Git. - Use
git add -pto build one commit per idea, readinggit diff --stagedbefore each commit. - Write each message in your editor: an imperative subject of about 50 characters, a blank line, and a body that says why.
Then run git log --oneline -15 on a project you know and pick two weak subject lines. Rewrite them on paper (do not change shared history) and note what information was missing.
08. Review prompt
Without looking back, give three reasons why focused commits are worth the effort, state the conventions for a subject line, and explain what git add -p lets you do that git add <file> cannot.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.