Chapter 2 · Git and GitHub
Commits, History and Diffs
- Page 5 of 22
- 18 min read
A repository is only as useful as its history is readable. Six months from now someone — very likely you — will ask why the classifier started calling neutral reviews negative, or which change made the API slower, or what the prompt looked like when the evaluation score was best. The answers are in the commits, if the messages say something and you know how to search them.
This page continues with the sentiment-api repository from Version Control and Your First Repository. You will write commit messages that explain themselves, read history with git log and git show, see exactly what changed with git diff, and finally open up a commit to see what it really is.
What you will learn
- How to write a good commit message: a short imperative subject and, when needed, a body that explains why
- How to read history with
git log(--oneline,--graph,--stat,-p, filters) andgit show - How to see changes with
git diff: unstaged, staged (--staged) and between any two commits - How to name commits: hashes,
HEAD,HEAD~1 - What a commit is inside: a snapshot (tree), its parent, author, message — and the hash computed from all of them
Catching up
If you followed the previous page, cd ~/projects/sentiment-api and carry on. If not, this block rebuilds the same repository with the same four commits (-q keeps Git quiet):
mkdir -p ~/projects/sentiment-api
cd ~/projects/sentiment-api
git init -q
cat > README.md <<'EOF'
# Sentiment API
A tiny sentiment classifier for course reviews, growing into a web API.
EOF
git add README.md
git commit -q -m "Add README"
cat > sentiment.py <<'EOF'
"""A tiny rule-based sentiment classifier: our stand-in for a real model."""
POSITIVE = {"good", "great", "clear", "love", "loved"}
NEGATIVE = {"bad", "hard", "slow", "confusing"}
def classify(text: str) -> str:
words = set(text.lower().replace(",", " ").split())
score = len(words & POSITIVE) - len(words & NEGATIVE)
if score > 0:
return "positive"
if score < 0:
return "negative"
return "neutral"
if __name__ == "__main__":
for review in ["Great course, loved it", "Setup was hard", "It was okay"]:
print(f"{review!r}: {classify(review)}")
EOF
git add sentiment.py
git commit -q -m "Add rule-based sentiment classifier"
cat >> README.md <<'EOF'
## Usage
python3 sentiment.py
EOF
git commit -q -a -m "Document how to run the classifier"
echo "Reviews come from the BitByte courses." >> README.md
git commit -q -a -m "Describe the data"
git log --oneline24c4e9d Describe the data
1b5d9ca Document how to run the classifier
7d030ed Add rule-based sentiment classifier
faa9787 Add READMEYour hashes will be different from the ones on this page — and that is expected. A commit's hash is computed from, among other things, the author and the exact time of the commit, so two people typing the same commands get different hashes. The end of this page shows exactly what goes into it.
Writing commit messages people can use
A commit message has a subject line and an optional body, separated by a blank line. The conventions most projects follow:
- Subject in the imperative, about 50 characters, no full stop: "Add retry to the weather client", as if completing the sentence "If applied, this commit will …". Git itself writes messages this way ("Merge branch …", "Revert …").
- Body explains why, not how: the diff already shows how. The body says what problem this solves, why this approach, and anything surprising. Wrap it at about 72 characters.
- One logical change per commit: a bug fix and a reformatting of the whole file are two commits. Small, focused commits are easy to review, to find, and to undo.
| Weak message | Better message | Why it is better |
|---|---|---|
update | Add negative words for setup problems | Says what changed |
fixed bug | Handle empty reviews in classify() | Says which bug, where |
changes to prompt | Ask the model to answer in Bangla when the question is in Bangla | The behaviour change is clear without opening the diff |
WIP, asdf, final | Lower spam threshold from 0.8 to 0.7 + a body with the eval result | Records the decision and the evidence for it |
Some teams also use Conventional Commits, a prefix that says what kind of change it is: feat: add /predict endpoint, fix: handle empty reviews, docs: …, test: …. Tools can then generate changelogs from the history. Follow whatever your team uses; for your own projects, a clear imperative subject is enough.
Seeing what changed: git diff
The classifier misses some common words. Open sentiment.py and extend the two word lists, so the file looks like this:
cat > sentiment.py <<'EOF'
"""A tiny rule-based sentiment classifier: our stand-in for a real model."""
POSITIVE = {"good", "great", "clear", "love", "loved", "excellent", "useful"}
NEGATIVE = {"bad", "hard", "slow", "confusing", "boring", "buggy"}
def classify(text: str) -> str:
words = set(text.lower().replace(",", " ").split())
score = len(words & POSITIVE) - len(words & NEGATIVE)
if score > 0:
return "positive"
if score < 0:
return "negative"
return "neutral"
if __name__ == "__main__":
for review in ["Great course, loved it", "Setup was hard", "It was okay"]:
print(f"{review!r}: {classify(review)}")
EOFBefore committing, look at exactly what you changed. git diff with no arguments compares the working tree with the staging area — in other words, it shows changes you have not staged yet:
git diffdiff --git a/sentiment.py b/sentiment.py
index a8bd313..a2307bd 100644
--- a/sentiment.py
+++ b/sentiment.py
@@ -1,7 +1,7 @@
"""A tiny rule-based sentiment classifier: our stand-in for a real model."""
-POSITIVE = {"good", "great", "clear", "love", "loved"}
-NEGATIVE = {"bad", "hard", "slow", "confusing"}
+POSITIVE = {"good", "great", "clear", "love", "loved", "excellent", "useful"}
+NEGATIVE = {"bad", "hard", "slow", "confusing", "boring", "buggy"}
def classify(text: str) -> str:How to read a diff:
--- a/…is the old version,+++ b/…the new one.@@ -1,7 +1,7 @@is a hunk header: this piece starts at line 1 and is 7 lines long in both the old and the new file. Only the changed area is shown, with up to three unchanged lines of context around it.- Lines starting with
-were removed, lines with+were added. Git works in whole lines, so changing one word shows as one line removed and one added.
Now stage the change and run git diff again:
git add sentiment.py
git diff
echo "--- staged:"
git diff --staged --stat--- staged:
sentiment.py | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)Plain git diff printed nothing — not because nothing changed, but because everything is staged now. git diff --staged (same as --cached) compares the staging area with the last commit: it is "what will go into the commit I am about to make". --stat summarises instead of showing every line. Running git diff --staged just before each commit is a habit that catches a lot of accidents.
Commit it with a subject and a body. Each -m adds a paragraph, so two -m options give a subject and a body:
git commit -m "Recognise more sentiment words" -m "Reviews often say \"excellent\", \"useful\", \"boring\" or \"buggy\", and the
classifier marked them neutral. Adding them fixes 4 of the 6 wrong
labels in last week's sample."[main 7e92094] Recognise more sentiment words
1 file changed, 2 insertions(+), 2 deletions(-)For longer messages, run git commit without -m: Git opens your editor (the core.editor from the previous page) with the staged changes listed in comments. Write the subject on the first line, a blank line, then the body; save and close to commit, or leave the message empty to cancel.
One more commit, touching two files, so the history has something to show:
mkdir -p data
cat > data/sample_reviews.txt <<'EOF'
Excellent examples, very useful
The videos were boring
Setup was hard and the notebook was buggy
Good pace
EOF
cat >> README.md <<'EOF'
Sample reviews for manual checks are in data/sample_reviews.txt.
EOF
git add data/sample_reviews.txt README.md
git commit -q -m "Add sample reviews for manual testing"
git log --oneline951898f Add sample reviews for manual testing
7e92094 Recognise more sentiment words
24c4e9d Describe the data
1b5d9ca Document how to run the classifier
7d030ed Add rule-based sentiment classifier
faa9787 Add READMEReading history: git log
Plain git log shows each commit in full, newest first:
git log -n 2commit 951898fcc84b264e32efe1ec5b04eddc98b0d5f5
Author: Nadia Rahman <[email protected]>
Date: Thu Jan 15 10:00:00 2026 +0600
Add sample reviews for manual testing
commit 7e92094399af689cba406cde21051b4af78d6aa0
Author: Nadia Rahman <[email protected]>
Date: Thu Jan 15 10:00:00 2026 +0600
Recognise more sentiment words
Reviews often say "excellent", "useful", "boring" or "buggy", and the
classifier marked them neutral. Adding them fixes 4 of the 6 wrong
labels in last week's sample.Each entry has the full 40-character hash, the author, the date and the whole message. (In a real terminal a long log opens in a pager: scroll with the arrow keys or Space, search with /word, press q to quit.) The options you will use most:
| Command | Shows |
|---|---|
git log --oneline | One line per commit: short hash and subject |
git log -n 3 | Only the last 3 commits |
git log --stat | Which files each commit changed, and how much |
git log -p | The full diff of each commit |
git log --graph --oneline --all | The history as a graph, with every branch |
git log -- sentiment.py | Only commits that changed this file |
git log --grep="sample" | Commits whose message contains a word |
git log --author="Nadia" | Commits by one person |
git log --stat -n 2
echo "--- commits that changed sentiment.py:"
git log --oneline -- sentiment.py
echo "--- messages mentioning 'sample':"
git log --oneline --grep="sample"commit 951898fcc84b264e32efe1ec5b04eddc98b0d5f5
Author: Nadia Rahman <[email protected]>
Date: Thu Jan 15 10:00:00 2026 +0600
Add sample reviews for manual testing
README.md | 1 +
data/sample_reviews.txt | 4 ++++
2 files changed, 5 insertions(+)
commit 7e92094399af689cba406cde21051b4af78d6aa0
Author: Nadia Rahman <[email protected]>
Date: Thu Jan 15 10:00:00 2026 +0600
Recognise more sentiment words
Reviews often say "excellent", "useful", "boring" or "buggy", and the
classifier marked them neutral. Adding them fixes 4 of the 6 wrong
labels in last week's sample.
sentiment.py | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
--- commits that changed sentiment.py:
7e92094 Recognise more sentiment words
7d030ed Add rule-based sentiment classifier
--- messages mentioning 'sample':
951898f Add sample reviews for manual testing
7e92094 Recognise more sentiment wordsThe --grep search found two commits: one whose subject says "sample", and one where the word appears only in the body ("last week's sample"). That is a small reason to write bodies — they are searchable.
--graph draws the history as a graph. Ours is a straight line, because we have one branch; in Branches, Merging and Merge Conflicts the same command shows lines splitting and joining. --format lets you choose the fields yourself:
git log --graph --oneline --all
git log --format="%h %ad %an %s" --date=short -n 3* 951898f Add sample reviews for manual testing
* 7e92094 Recognise more sentiment words
* 24c4e9d Describe the data
* 1b5d9ca Document how to run the classifier
* 7d030ed Add rule-based sentiment classifier
* faa9787 Add README
951898f 2026-01-15 Nadia Rahman Add sample reviews for manual testing
7e92094 2026-01-15 Nadia Rahman Recognise more sentiment words
24c4e9d 2026-01-15 Nadia Rahman Describe the data(%h short hash, %ad author date, %an author name, %s subject. All our dates are the same because the commits on this page were made with a fixed clock; yours show when you made them.)
Naming commits: hashes and HEAD
Any command that takes a commit accepts several kinds of names:
| Name | Means |
|---|---|
a2f6c1e (any unique start of a hash) | That commit. Seven characters are usually enough. |
HEAD | The commit you are on now (the latest on the current branch) |
HEAD~1 (or HEAD^) | Its parent, one commit back |
HEAD~3 | Three commits back |
main | The latest commit on branch main |
git show displays one commit — its message and its diff. With commit:path it shows a file as it was in that commit, without changing anything in your working tree:
git show HEAD~1
echo "--- README.md three commits ago:"
git show HEAD~3:README.mdcommit 7e92094399af689cba406cde21051b4af78d6aa0
Author: Nadia Rahman <[email protected]>
Date: Thu Jan 15 10:00:00 2026 +0600
Recognise more sentiment words
Reviews often say "excellent", "useful", "boring" or "buggy", and the
classifier marked them neutral. Adding them fixes 4 of the 6 wrong
labels in last week's sample.
diff --git a/sentiment.py b/sentiment.py
index a8bd313..a2307bd 100644
--- a/sentiment.py
+++ b/sentiment.py
@@ -1,7 +1,7 @@
"""A tiny rule-based sentiment classifier: our stand-in for a real model."""
-POSITIVE = {"good", "great", "clear", "love", "loved"}
-NEGATIVE = {"bad", "hard", "slow", "confusing"}
+POSITIVE = {"good", "great", "clear", "love", "loved", "excellent", "useful"}
+NEGATIVE = {"bad", "hard", "slow", "confusing", "boring", "buggy"}
def classify(text: str) -> str:
--- README.md three commits ago:
# Sentiment API
A tiny sentiment classifier for course reviews, growing into a web API.
## Usage
python3 sentiment.pyComparing any two commits
git diff A B shows what changed from A to B. Add -- path to limit it to some files, and --stat for a summary:
git diff --stat HEAD~3 HEAD
echo "---"
git diff HEAD~2 HEAD -- README.md README.md | 2 ++
data/sample_reviews.txt | 4 ++++
sentiment.py | 4 ++--
3 files changed, 8 insertions(+), 2 deletions(-)
---
diff --git a/README.md b/README.md
index 1390352..c2e74a7 100644
--- a/README.md
+++ b/README.md
@@ -6,3 +6,4 @@ A tiny sentiment classifier for course reviews, growing into a web API.
python3 sentiment.py
Reviews come from the BitByte courses.
+Sample reviews for manual checks are in data/sample_reviews.txt.The order matters: git diff HEAD~2 HEAD shows lines added since HEAD~2 with +; swap the two and the same lines appear with -. This is how you answer "what changed in the prompt between the release that scored well and today?": find both commits in git log, then git diff them, limited to the prompt file.
What a commit really is
Commands like git log and git diff make it look as if Git stores changes. It actually stores snapshots, and computes diffs when you ask. git cat-file -p prints Git's raw objects, so you can look inside:
git cat-file -p HEADtree 614f68153b9880f758fd84a600fb71f11fcca53f
parent 7e92094399af689cba406cde21051b4af78d6aa0
author Nadia Rahman <[email protected]> 1768449600 +0600
committer Nadia Rahman <[email protected]> 1768449600 +0600
Add sample reviews for manual testingThat is the entire commit:
- tree — the hash of a snapshot of the whole project folder at this moment;
- parent — the hash of the previous commit (the first commit has none; a merge commit has two);
- author and committer — name, email, the time as seconds since 1 January 1970, and the time zone (
+0600is Bangladesh time); - the message.
The tree lists the files and folders, each pointing to another object by its hash. A blob is a file's content:
git cat-file -p HEAD^{tree}
echo "---"
git cat-file -p HEAD:data100644 blob c2e74a78a3e118dff236b00d2b0977c75f8cb6ef README.md
040000 tree b8e4632751c6b9a2b848db88a6e0e01ed508966e data
100644 blob a2307bd19ca9f3c2ffc4ce463c48da041f8b08cc sentiment.py
---
100644 blob 6f3d65bcb322c260ee740242baf3652a6b63a18c sample_reviews.txtEvery one of these hashes is a SHA-1 checksum of the object's content. So a commit's hash depends on its tree (all the files), its parent's hash (and therefore the whole history before it), the author, the time and the message. Change a single byte anywhere and every hash after it changes. That is why Git history cannot be quietly altered, why two identical commits made at different times get different hashes, and why your hashes on this page differ from ours.
A file's content, on the other hand, hashes the same everywhere. Try it — everybody who runs this gets the same 40 characters:
echo "hello" | git hash-object --stdince013625030ba8dba906f756967f9e9ca394464aThe whole history so far, as Git sees it:
commit 1 commit 2 commit 3 ... commit 6 <-- main <-- HEAD
"Add README" <--- "Add rule- <---- "Document ... "Add sample
based ..." how ..." reviews ..."
| | | |
tree tree tree tree
| | | / | \
README.md README.md README.md README.md | data/
(blob) sentiment.py sentiment.py sentiment.py sample_reviews.txt
Each commit points back to its parent. Unchanged files are not copied:
trees in different commits point to the same blob.Storing snapshots sounds wasteful, but it is not: a file that did not change is the same blob, stored once and shared by every tree that contains it, and Git compresses everything. That design is what makes switching between versions and branches nearly instant.
Where this shows up in AI and backend work
- Debugging regressions: when a metric drops or an endpoint breaks,
git log -p -- pathon the relevant file, orgit diffbetween the last good and the first bad release, usually points straight at the cause. - Prompt and config history: keeping prompts in files means
git log --oneline -- prompts/is the full history of how your LLM's instructions evolved, with a reason for each change. - Code review: pull requests (later in this chapter) are diffs with discussion attached; reading diffs fluently is half of reviewing code.
- Traceability: logging the commit hash (
git rev-parse --short HEAD) with each training run or each deployed API version ties every result to the exact code that produced it.
Common mistakes
- "git diff shows nothing, but I changed files!" The changes are probably staged already. Use
git diff --staged, orgit statusto see where they are. - Messages like "update" or "fix". They make
git loguseless for finding anything. Say what changed and, when it is not obvious, why. - Mixing unrelated changes in one commit. A feature, a bug fix and reformatting in one commit cannot be reviewed or undone separately. Stage them separately with
git add <file>and make several commits. - Committing notebooks with all their outputs. A
.ipynbfile is JSON with outputs, images and execution counts inside, so its diffs are unreadable and it grows with every run. Clear outputs before committing (or use a tool such as nbstripout), and move code you keep into.pyfiles. - Getting stuck in the pager. A long
git logorgit diffwaits for you to scroll. Pressqto get the prompt back.
Try it yourself
- Easy: Show the last three commits in one-line form, then show the files changed by the latest commit only.
- Medium: Add the word
helpfultoPOSITIVEinsentiment.py(withsedor your editor). Before committing, show the staged diff in its compact--statform, then commit with a good message. - Hard: Make a commit whose message has a subject and a body, then print only the body of the latest commit with
git log -1 --format=%b, and only the files it touched withgit show --name-only --format= HEAD.
Answers
1. -n 3 limits the log; git show --stat summarises one commit:
git log --oneline -n 3
git show --stat --oneline HEAD951898f Add sample reviews for manual testing
7e92094 Recognise more sentiment words
24c4e9d Describe the data
951898f Add sample reviews for manual testing
README.md | 1 +
data/sample_reviews.txt | 4 ++++
2 files changed, 5 insertions(+)2. sed -i edits the file in place (on macOS write sed -i ''). The --stat line confirms that exactly one line changed:
sed -i 's/"excellent", "useful"}/"excellent", "useful", "helpful"}/' sentiment.py
git add sentiment.py
git diff --staged --stat
git commit -q -m "Treat 'helpful' as positive"
git log --oneline -n 1 sentiment.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
2efa0df Treat 'helpful' as positive3. %b is the body; --format= (empty) hides the commit header, leaving only the file names:
echo "Good pace, helpful mentors" >> data/sample_reviews.txt
git add data/sample_reviews.txt
git commit -q -m "Add a review that mentions mentors" -m "Covers the new 'helpful' word in manual checks."
git log -1 --format=%b
git show --name-only --format= HEADCovers the new 'helpful' word in manual checks.
data/sample_reviews.txtSummary
- Write commit subjects in the imperative, around 50 characters; add a body that explains why when it is not obvious; keep one logical change per commit.
git diffshows unstaged changes,git diff --stagedwhat you are about to commit,git diff A Bthe change between any two commits.git logreads history:--oneline,-n,--stat,-p,--graph --all,-- path,--grep,--author,--format.git showdisplays one commit, orcommit:patha file as it was.- Name commits by hash or relative to
HEAD(HEAD~1,HEAD~3). - A commit is a snapshot (tree) plus parent, author, committer and message; its hash covers all of that, so history is tamper-evident.
Next: .gitignore: Keeping Secrets and Junk Out makes sure .env files, virtual environments, caches, datasets and model files never get into your commits — and explains why a secret that was committed once must be treated as leaked.

