Git Fundamentals
Every chapter so far has been about writing Python. This one is different on purpose: it's about the tool nearly every professional developer uses to track, share, and recover that code — git. There's no new Python syntax here. Instead, you'll run real shell and git commands against a small Python project, and every command sequence and output shown in this chapter was actually run, not invented, so what you see here is exactly what git will show you too.
How to read this chapter
- Sub-topic 1 covers why version control exists at all — the real problems it solves.
- Sub-topic 2 covers the core workflow:
init,add,commit,status,diff,log, and the staging area. - Sub-topic 3 covers branching — git's lightweight, pointer-based model, and a realistic feature-branch workflow.
- Sub-topic 4 covers merging — fast-forward vs. three-way merges, and resolving a real conflict by hand.
- Sub-topic 5 covers rebase — what it does differently from merge, and the rule about not rebasing shared history.
- Sub-topic 6 covers undoing things safely:
restore,reset,revert, stashing, and recovering a "lost" commit withreflog. - A note on every command and output shown in this chapter: all of it was captured by actually running git, against a small sample project (a task-list command-line tool), in a scratch directory. Commit hashes will differ if you run the same commands yourself — git generates a fresh hash from the commit's exact content and timestamp every time — but the shape of the output (what git prints, in what format) will match.
1. Why version control matters
- Without version control, "undo" only goes back as far as your editor's in-memory history — close the file, and that history is gone.
- There's no reliable way to see when a change was made, why, or by whom — especially once more than one person touches the same code.
- There's no safe way to try something risky and back out cleanly if it doesn't work.
Before git, a surprisingly common (and surprisingly recent, in some teams) way to "version" a project looked like this:
project/
project_final/
project_final_v2/
project_final_ACTUALLY_final/
project_final_ACTUALLY_final_fixed/
Each folder is a full, separate copy of the entire project, made by hand, whenever someone remembered to save one before making a risky change. There's no record of what changed between any two of these folders — only a full diff, done manually, file by file, if anyone ever needs to know. And if two people are both editing copies of the same project, there's no way to combine their work except by hand, comparing files and re-typing changes into a merged version.
.git folder holding the entire history of every tracked change — every commit, branch, and the data needed to reconstruct any past version. A folder becomes a repository the moment you run git init inside it.
Git solves the three problems above directly. Every meaningful change is recorded as a commit — a permanent, timestamped, authored snapshot you can always return to. Multiple people (or multiple lines of work by the same person) can proceed independently on branches and be combined later without hand-editing anything. And because every commit is kept forever by default, "try something risky" is close to free — the real starting point is never actually at risk. The rest of this chapter builds up exactly how, starting with the core workflow every other git feature is built on top of.
The production-hotfix scenario from the hook is the single most common real-world reason teams reach for branching specifically (covered in full in Sub-topic 3): the fix branches off the last known-stable commit, gets tested and shipped completely independently of the in-progress feature work, and the feature branch is untouched and unaffected the whole time.
- Without version control, undo history is temporary, there's no reliable record of who changed what and when, and there's no clean way to isolate risky or in-progress work.
- A git repository is a project folder with a hidden
.gitfolder tracking its full history. - Git's core building blocks — commits and branches — are designed specifically to solve these problems, and the rest of this chapter covers each one in turn.
Go Deeper: is git the only version control system?
No — git is the dominant one today (and what GitHub, GitLab, and Bitbucket are all built around), but older systems like Subversion (SVN) and Mercurial exist and are still used in some organizations. What makes git specifically well-suited to modern collaborative work is that it's distributed: every clone of a repository has the entire history, not just a pointer to a central server, which is part of why branching and merging in git are fast, local operations rather than something that requires a network round-trip.
- Manual folder-copying as "version control" loses history, has no audit trail, and makes combining independent work a manual, error-prone process.
- A repository is a project folder git is tracking, via a hidden
.gitfolder holding its full history. - Commits and branches are git's answer to isolating risky/in-progress work from stable, shippable work.
2. The core git workflow
git initturns a folder into a repository.git addstages changes;git commitpermanently records the staged changes as a snapshot.git status,git diff, andgit logare how you constantly check what's changed, what's staged, and what's already been committed.
init, add, commit, status, diff, log — are what you'll type more than any other git commands, by far. Branching and merging (Sub-topics 3-4) are built entirely on top of the commits this workflow creates.
Every example in this chapter uses the same small sample project: a task-list command-line tool, tasks.py. Starting from an empty folder, git init creates the repository:
$ git init -b main
$ git status
Initialized empty Git repository in /path/to/task-cli/.git/
On branch main
No commits yet
nothing to commit (create/copy files and use "git add" to track)
git add copies a file's current state into the staging area; git commit then takes only what's staged and turns it into a permanent snapshot. This two-step split exists so you can build a commit out of exactly the changes you want — even if your working folder currently has other, unrelated edits sitting alongside them, unstaged.
With the repo created, here's tasks.py written for the first time, and git add staging it:
def add_task(tasks, description):
tasks.append({"description": description, "done": False})
return tasks
def list_tasks(tasks):
for i, task in enumerate(tasks, start=1):
mark = "x" if task["done"] else " "
print(f"[{mark}] {i}. {task['description']}")
$ git add tasks.py
$ git status
On branch main
No commits yet
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: tasks.py
Notice git status is doing exactly the job it's meant for: reporting where things stand right now, without changing anything. tasks.py is staged ("Changes to be committed") but not yet part of any permanent history. That happens with git commit:
$ git commit -m "Add basic task add/list functions"
$ git log
[main (root-commit) 5d9184b] Add basic task add/list functions
1 file changed, 9 insertions(+)
create mode 100644 tasks.py
commit 5d9184b3f9ef2bf67fca4240d18c87a449e3fa5e
Author: Dev <dev@example.com>
Date: Sat Jul 11 09:56:39 2026 +0000
Add basic task add/list functions
Thought process: before touching git at all, the actual engineering decision is what belongs in this commit versus a later one — a good commit is one coherent, reviewable change with a message describing the "why," not a dump of everything that happened to be edited that day. Here, "add basic task add/list functions" is deliberately scoped to just those two functions, so the history stays readable later.
Write the prompt you'd give an AI assistant to help resolve this git situation:
Show a strong version of this prompt
I just ran `git init -b main` in a new project folder and wrote a file called tasks.py containing two related functions, add_task() and list_tasks(). Walk me through the exact git commands to check what git currently sees as changed, stage the new file, and commit it with a clear, descriptive commit message — and explain what "staging" actually does here versus committing directly.
git commit's own output already summarizes the change (1 file, 9 insertions); git log then shows the permanent record: a unique commit hash (5d9184b3f9..., git's built-in shorthand for it is the first 7 characters, 5d9184b), the author, the timestamp, and the message. That hash is git's real identity for this commit — two commits are considered "the same" only if their hash matches exactly.
git log can walk backward through it. A commit's hash is calculated from its exact content, its parent, its author, and its timestamp, which is why even a one-character difference produces a completely different hash.
Now watch git diff and git status work together as changes are made, before anything is staged. Here, tasks.py gets a new function added:
$ git diff
diff --git a/tasks.py b/tasks.py
index 1c1b568..515188f 100644
--- a/tasks.py
+++ b/tasks.py
@@ -7,3 +7,8 @@ def list_tasks(tasks):
for i, task in enumerate(tasks, start=1):
mark = "x" if task["done"] else " "
print(f"[{mark}] {i}. {task['description']}")
+
+
+def complete_task(tasks, index):
+ tasks[index - 1]["done"] = True
+ return tasks
git diff with no arguments shows exactly this: unstaged changes, line by line, with + for additions and - for removals — the map of what would be staged next, if you ran git add. After staging and committing this change too, git log --oneline gives a compact, one-line-per-commit view that's far more useful than the full git log once history grows past a couple of commits:
$ git add tasks.py
$ git commit -m "Add complete_task function"
$ git log --oneline
[main c8e706b] Add complete_task function
1 file changed, 5 insertions(+)
c8e706b Add complete_task function
5d9184b Add basic task add/list functions
git initcreates a repository;git add <file>stages a change;git commit -m "..."permanently records everything currently staged.git statusshows what's staged, unstaged, and untracked, right now — it never changes anything itself.git diffshows the exact line-by-line content of unstaged changes;git log(or the more compactgit log --oneline) shows the permanent commit history.
Go Deeper: what does git diff --staged show?
Plain git diff only shows unstaged changes — the difference between your working files and what's staged. Once you run git add, those changes disappear from git diff's output (there's no unstaged difference anymore) and instead show up under git diff --staged (also spelled git diff --cached), which compares what's staged against the last commit. This distinction matters most once you're staging changes incrementally, a few files at a time, rather than all at once.
git init,git add,git commitare how a change becomes a permanent snapshot, via the staging area in between.- A commit is a full snapshot plus a pointer to its parent, identified by a unique hash calculated from its content.
git status/git diff/git logare read-only tools for seeing exactly where things stand — use them constantly, not just when something looks wrong.
3. Branching
- A branch is just a movable pointer to a commit — creating one is instant and nearly free, unlike copying an entire project folder.
git branch <name>creates a branch;git switch <name>moves to it;git switch -c <name>does both at once.- Branches let independent lines of work — a feature, a hotfix, an experiment — proceed without touching each other until you explicitly combine them.
Here's the sample project with two commits on main so far. git branch (no arguments) lists existing branches, with a * marking the current one:
$ git branch feature/delete-task
$ git branch
feature/delete-task
* main
git switch moves your working files to match a different branch's latest commit:
$ git switch feature/delete-task
$ git branch
Switched to branch 'feature/delete-task'
* feature/delete-task
main
Now a commit made here only moves feature/delete-task's pointer forward — main stays exactly where it was:
$ git add tasks.py
$ git commit -m "Add delete_task function"
$ git log --oneline --all --graph
* a16051c Add delete_task function
* c8e706b Add complete_task function
* 5d9184b Add basic task add/list functions
Thought process: the decision that matters isn't the branch command syntax, it's when to branch at all — any change that isn't trivial and one-line deserves its own branch, named after what it does, so it can be reviewed, tested, and merged (or abandoned) independently of whatever else is happening on main.
Write the prompt you'd give an AI assistant to help resolve this git situation:
Show a strong version of this prompt
I have a git repo on the main branch with a couple of existing commits. I want to start work on a new function, delete_task(), without touching main until it's done. What's the exact git command to create a new branch called feature/delete-task and switch to it in one step, versus creating it and switching separately? Also explain what actually happens internally when I commit while on that branch — does main's pointer move too?
Real feature-branch work almost never happens with two separate commands, though — git switch -c <name> creates and switches in a single step, which is the version you'll use most often:
$ git switch -c feature/priority
Switched to a new branch 'feature/priority'
This is exactly the hotfix scenario from the hook, mapped onto real commands: if a production bug appeared right now, git switch main followed by git switch -c hotfix/urgent-fix would branch off main's current, stable commit — totally unaffected by whatever's half-finished on feature/priority, because that work only exists on feature/priority's own commits.
- A branch is a movable pointer to a commit, not a copy of the project — creating one is instant.
git branch <name>creates without switching;git switch <name>switches;git switch -c <name>does both.- Committing while on a branch only moves that branch's own pointer forward — other branches are completely unaffected until explicitly merged.
Go Deeper: what's git checkout, and why does this chapter use git switch instead?
git checkout is the older, original command for switching branches — and it still works. But checkout is also overloaded to do several unrelated things (switching branches, restoring files, checking out specific commits), which made it a common source of mistakes. Git 2.23 introduced git switch (for branches) and git restore (for files, covered in Sub-topic 6) specifically to split those responsibilities into two clearer, harder-to-misuse commands. You'll still see git checkout in a lot of existing tutorials and older codebases' documentation, so it's worth recognizing, even though switch/restore is the more precise modern choice.
- Branches are cheap, movable pointers to commits — not full copies of the project.
git switch -c <name>is the common one-step way to start a new line of work.- Work on one branch never affects another branch's commits until they're explicitly merged — the exact mechanism behind isolating a hotfix from in-progress feature work.
4. Merging
- A fast-forward merge happens when the target branch hasn't moved since the branch being merged split off — git just moves the pointer forward, no new commit needed.
- A three-way merge happens when both branches have new commits — git creates a new merge commit with two parents, combining both histories.
- A merge conflict happens when both branches changed the same lines differently — git can't guess which version is correct, so it stops and asks you to decide.
First, the simple case. feature/delete-task has one commit main doesn't have yet, and main hasn't moved since they split — merging it in is a pure fast-forward:
$ git switch main
$ git merge feature/delete-task
Switched to branch 'main'
Updating c8e706b..a16051c
Fast-forward
tasks.py | 5 +++++
1 file changed, 5 insertions(+)
With the merge done, the feature branch's job is finished — deleting it is routine cleanup, not a risk, since its commits now live permanently on main:
$ git branch -d feature/delete-task
Deleted branch feature/delete-task (was a16051c).
Now the more common real-world case: both main and a feature branch pick up new commits, editing the same function in different ways. On feature/priority, add_task() gains a priority parameter; on main at the same time, add_task() gains input validation:
$ git switch main
$ git merge feature/priority
Auto-merging tasks.py
CONFLICT (content): Merge conflict in tasks.py
Automatic merge failed; fix conflicts and then commit the result.
Opening tasks.py now shows git's conflict markers, sitting directly in the file:
<<<<<<< HEAD
def add_task(tasks, description):
if not description.strip():
raise ValueError("description cannot be empty")
tasks.append({"description": description, "done": False})
=======
def add_task(tasks, description, priority="normal"):
tasks.append({"description": description, "done": False, "priority": priority})
>>>>>>> feature/priority
return tasks
This reads as two competing versions of the same lines: everything between <<<<<<< HEAD and ======= is what's currently on main (the branch you're merging into); everything between ======= and >>>>>>> feature/priority is what's coming in from the branch you're merging from. Resolving a conflict by hand means editing the file back to one final, correct version and deleting the markers — here, both changes are genuinely worth keeping:
def add_task(tasks, description, priority="normal"):
if not description.strip():
raise ValueError("description cannot be empty")
tasks.append({"description": description, "done": False, "priority": priority})
return tasks
Thought process: resolving a conflict is a code decision, not a git decision — git can't know that keeping both the validation check and the priority parameter is correct here. The actual judgment call is reading both versions, understanding what each one was trying to achieve, and writing a version of the function that honors both intents rather than blindly picking one side.
Write the prompt you'd give an AI assistant to help resolve this git situation:
Show a strong version of this prompt
I'm mid-merge in git and have a conflict in tasks.py. Here are the conflict markers:
<<<<<<< HEAD
def add_task(tasks, description):
if not description.strip():
raise ValueError("description cannot be empty")
tasks.append({"description": description, "done": False})
=======
def add_task(tasks, description, priority="normal"):
tasks.append({"description": description, "done": False, "priority": priority})
>>>>>>> feature/priority
return tasks
The HEAD side added input validation; the feature/priority side added a priority parameter. Write a single resolved version of add_task() that keeps both changes correctly, then tell me the exact git commands to mark the file resolved and finish the merge.
Once the file looks right, git add tells git the conflict is resolved for that file (the same command as normal staging — there's no special "resolve" command), and git commit finishes the merge, creating a merge commit:
$ git add tasks.py
$ git commit -m "Merge feature/priority into main"
$ git log --oneline --graph --all
* 7a0e1c6 Merge feature/priority into main
|\
| * c2a1f02 Add priority field to add_task
* | e488a27 Validate description is not empty in add_task
|/
* a16051c Add delete_task function
* c8e706b Add complete_task function
* 5d9184b Add basic task add/list functions
git log --graph visualizes this directly: the branching and rejoining lines (|\ and |/) show exactly where history split and came back together.
- A fast-forward merge just moves a pointer forward — no new commit, no conflict possible, since one branch's history is a strict continuation of the other's.
- A three-way merge creates a merge commit with two parents, combining genuinely divergent history.
- A merge conflict happens only on lines both branches changed differently; resolving it means hand-editing the file to a single correct version, then
git add+git committo finish.
Go Deeper: what if you want to back out of a conflicted merge entirely?
git merge --abort cancels an in-progress merge and returns everything to exactly how it was right before git merge was run — conflict markers gone, no merge commit made. It's the safe escape hatch for "I started this merge and realized I'm not ready to resolve it right now," and it's completely safe to use any time before the final git commit that finishes the merge.
- Fast-forward: target branch hasn't moved, so git just advances the pointer — no merge commit.
- Three-way merge: both branches have new commits, so git creates a merge commit with two parents.
- A conflict marks the exact overlapping lines git can't auto-resolve; fix by hand,
git add, thengit commit(orgit merge --abortto cancel entirely).
5. Rebase
git rebasereplays your branch's commits one by one on top of another branch's latest commit, instead of merging the two histories together.- The result is a straight, linear history — no merge commit, no
|\/|/lines in the graph. - Never rebase commits that other people already have — rebase rewrites commit hashes, which breaks history for anyone who already pulled the originals.
Starting from a branch that's diverged from main — feature/tags has one commit main doesn't have, and main has since gained one commit of its own:
$ git log --oneline --graph --all
* 5ac2893 Add clear_completed function
| * 09713a7 Add tag_task function
|/
* 7a0e1c6 Merge feature/priority into main
...
A merge here would create another merge commit, same as Sub-topic 4. Rebase takes a different approach — while on feature/tags, git rebase main replays its one commit as if it had been written starting from main's current tip:
$ git switch feature/tags
$ git rebase main
Rebasing (1/1)
Auto-merging tasks.py
CONFLICT (content): Merge conflict in tasks.py
error: could not apply 09713a7... Add tag_task function
hint: Resolve all conflicts manually, mark them as resolved with
hint: "git add/rm <conflicted_files>", then run "git rebase --continue".
hint: You can instead skip this commit: run "git rebase --skip".
hint: To abort and get back to the state before "git rebase", run "git rebase --abort".
Rebase conflicts look and resolve identically to merge conflicts — same <<<<<<</=======/>>>>>>> markers, same fix-by-hand-then-git add process. The one difference is the command that continues afterward:
$ git add tasks.py
$ git rebase --continue
$ git log --oneline --graph --all
[detached HEAD 5c3d617] Add tag_task function
Successfully rebased and updated refs/heads/feature/tags.
* 5c3d617 Add tag_task function
* 5ac2893 Add clear_completed function
* 7a0e1c6 Merge feature/priority into main
...
Rebase can also be used interactively to clean up a branch's own commits before sharing them — combining two "work in progress" commits into one clean commit, for example. Here, two rough commits get squashed into one:
$ git log --oneline -2
f1d489f wip 2
bb70699 wip
$ git rebase -i HEAD~2
# in the editor that opens, change the second commit's
# "pick" to "squash" (or its shorthand, "s"), then save
Rebasing (2/2)
[detached HEAD 67cd467] wip
Successfully rebased and updated refs/heads/main.
$ git commit --amend -m "Add task_count and pending_count helpers"
$ git log --oneline -3
abaf902 Add task_count and pending_count helpers
5c3d617 Add tag_task function
5ac2893 Add clear_completed function
Two messy commits ("wip", "wip 2") became one clean, well-described commit — exactly the kind of history cleanup interactive rebase is for, when it's done before a branch is shared with anyone else.
Thought process: the judgment call here isn't "how do I run rebase" — it's "should I rebase this at all." The rule that decides it: has anyone else already pulled or based work on these exact commits? If yes, rebasing rewrites hashes they already have, and their next pull turns into a confusing mess of duplicated, conflicting history. If the commits are still purely local and unpushed (or on a solo feature branch nobody else has touched), rebasing to clean up history before sharing it is exactly the right move.
Write the prompt you'd give an AI assistant to help resolve this git situation:
Show a strong version of this prompt
I have two commits on my local feature branch, "wip" and "wip 2", that nobody else has pulled or seen. I want to combine them into one clean commit with a descriptive message before I push and open a pull request. Walk me through git rebase -i HEAD~2 step by step: what the interactive editor shows, how "squash" works, and how to reword the final combined commit message. Also confirm this is safe specifically because these commits are still unpushed and local-only.
git rebase <branch>replays your branch's commits on top of another branch's tip, producing a linear history with no merge commit.- Rebase conflicts resolve the same way as merge conflicts, just followed by
git rebase --continueinstead of a plain commit. - Interactive rebase (
git rebase -i) can reorder, reword, or squash local commits — genuinely useful for cleaning up history, but only before it's shared with anyone else.
Go Deeper: how do you back out of a rebase gone wrong?
git rebase --abort, at any point before it finishes, returns the branch to exactly where it was before the rebase started — same safety net as git merge --abort. And even after a rebase completes, git reflog (covered next, in Sub-topic 6) still has a record of where the branch pointed beforehand, so a completed-but-regretted rebase is still recoverable, as long as it hasn't been pushed and garbage-collected elsewhere.
- Rebase replays commits on a new base instead of merging two histories, producing a straight line with no merge commit.
- Every replayed commit gets a new hash — rebase doesn't move commits, it recreates them.
- Rule: rebase only local, unshared commits. Once a commit is shared, use merge (or, for undoing,
revert— next up).
6. Undoing things safely
git status/git diffare always the first step — know exactly what state you're in before undoing anything.git restorediscards uncommitted file changes;git resetmoves your branch pointer (with three modes controlling what happens to the changes);git revertundoes a commit by creating a new, opposite commit.git stashtemporarily shelves uncommitted work;git reflogcan recover a commit that looks "lost" after a hard reset.
git status would have warned you about, if you'd checked first.
git restore <file> discards uncommitted changes to a file, resetting it back to its last committed state. It's the safe tool for "I started editing this and want to throw the edit away entirely":
$ git status
$ git restore tasks.py
$ git status
On branch main
Changes not staged for commit:
modified: tasks.py
On branch main
nothing to commit, working tree clean
HEAD is git's name for "the commit you're currently on" — almost always the tip of whatever branch is checked out. Commands throughout this section reference it directly: HEAD~1 means "one commit before HEAD," which is how you address specific past commits without knowing their hash.
git reset is more powerful and more commonly misunderstood — it moves your branch's pointer to a different commit, and has three modes controlling what happens to the difference. Starting from a commit that turned out to be a mistake:
$ git reset --soft HEAD~1
$ git status
On branch main
Changes to be committed:
modified: tasks.py
$ git commit -m "Add broken_feature (bug)"
$ git reset HEAD~1
$ git status
Unstaged changes after reset:
M tasks.py
On branch main
Changes not staged for commit:
modified: tasks.py
$ git add tasks.py && git commit -m "Add broken_feature (bug)"
$ git reset --hard HEAD~1
$ git status
HEAD is now at abaf902 Add task_count and pending_count helpers
On branch main
nothing to commit, working tree clean
Laid out side by side, the pattern is exactly what the flag names suggest:
commit undone? changes staged? changes in working files?
--soft yes yes yes
--mixed (default) yes no yes
--hard yes no no -- gone
--hard is the only one of the three that can genuinely discard work — and it's exactly why git status before running it matters: if there are changes you actually wanted, --hard deletes them with no confirmation prompt.
git reset moves your branch pointer backward, and (depending on mode) can erase commits from the branch's history entirely. git revert never removes anything — it moves your branch pointer forward, adding a brand-new commit whose change is the exact opposite of the one being undone. This is why revert is the safe choice for anything already shared: the original mistaken commit stays in history (so nobody's pulled history breaks), and everyone who pulls afterward just sees the fix as a new, ordinary commit.
$ git add tasks.py && git commit -m "Add broken_feature (bug)"
$ git revert --no-edit HEAD
$ git log --oneline -3
[main b2351e5] Revert "Add broken_feature (bug)"
1 file changed, 4 deletions(-)
b2351e5 Revert "Add broken_feature (bug)"
54f6b44 Add broken_feature (bug)
abaf902 Add task_count and pending_count helpers
Thought process: the decision tree here is short and worth memorizing: is this change even committed yet? If not, restore (or reset --mixed to unstage first). Is the commit still purely local, never pushed or shared? Reset is fine. Has it already been pushed, or could someone else already have it? Revert, always — reset on shared history is the single most common way git history gets genuinely, painfully broken for a whole team.
Write the prompt you'd give an AI assistant to help resolve this git situation:
Show a strong version of this prompt
I pushed a commit called "Add broken_feature (bug)" to a shared branch, and I think a teammate may have already pulled it. I need to undo the change safely without rewriting history they already have. Explain why git revert HEAD is the right tool here instead of git reset --hard HEAD~1, what revert actually does to the commit history (does it delete the original commit?), and give me the exact command including how to skip the default commit-message editor.
For a shorter interruption — uncommitted work you're not ready to commit, but need to set aside to switch tasks — git stash is the tool:
$ git status
$ git stash
$ git status
$ git stash list
On branch main
Changes not staged for commit:
modified: tasks.py
Saved working directory and index state WIP on main: b2351e5 Revert "Add broken_feature (bug)"
On branch main
nothing to commit, working tree clean
stash@{0}: WIP on main: b2351e5 Revert "Add broken_feature (bug)"
The working tree is clean again, but nothing was lost — git stash pop brings the exact same change back and removes it from the stash list:
$ git stash pop
On branch main
Changes not staged for commit:
modified: tasks.py
Dropped refs/stash@{0} (733fd7639926cab2ec521e93108af0e4a77a410f)
Finally, the safety net behind all of this: git reflog keeps a record of every place HEAD has pointed, including commits a --hard reset just made unreachable from any branch. Here, a real commit gets hard-reset away, then recovered:
$ git commit -m "Add important_feature: sort tasks"
$ git reset --hard HEAD~1
$ git log --oneline -1
HEAD is now at b2351e5 Revert "Add broken_feature (bug)"
b2351e5 Revert "Add broken_feature (bug)"
$ git reflog
b2351e5 HEAD@{0}: reset: moving to HEAD~1
e230a4a HEAD@{1}: commit: Add important_feature: sort tasks
b2351e5 HEAD@{2}: reset: moving to HEAD
...
$ git reset --hard e230a4a
$ git log --oneline -1
HEAD is now at e230a4a Add important_feature: sort tasks
e230a4a Add important_feature: sort tasks
git reflog is a local, personal log of every point HEAD has moved to on your machine — every commit, checkout, reset, and rebase step. It's separate from your project's actual commit history, isn't shared when you push, and by default entries expire after about 90 days. What it means in practice: a commit is essentially never truly "lost" the moment after a mistaken reset --hard, as long as you catch it before the reflog entry expires and check git reflog for its hash.
git restore <file>discards uncommitted changes to that file; checkgit status/git difffirst, since it can't be undone once run.git resetmoves your branch pointer, with--soft/--mixed(default)/--hardcontrolling whether changes stay staged, stay unstaged, or are discarded entirely.git revertis the safe undo for shared history — it adds a new commit rather than rewriting anything.git stashtemporarily shelves uncommitted work;git stash popbrings it back.git reflogcan recover a commit that a hard reset made unreachable, as long as it hasn't expired from the reflog yet.
Go Deeper: does reflog protect you forever?
No — reflog entries eventually expire (90 days for reachable commits by default, 30 for unreachable ones), and at that point git's garbage collector can permanently delete commits nothing references anymore. In practice, this is almost never a problem: most "I lost a commit" panics happen minutes after the mistake, well within the reflog's window. It's also worth knowing reflog is entirely local — it never gets pushed, so it can't help recover a mistake made only on a remote repository, only ones made on your own machine.
git status/git difffirst, always — know what you're about to undo before undoing it.restorefor uncommitted file changes;reset(soft/mixed/hard) for moving your branch pointer with different consequences for staged/working changes;revertfor safely undoing anything already shared.stashshelves work temporarily;reflogis the recovery net for a commit that looks lost after a hard reset.
- Every professional software team uses git (or a system built on it, like GitHub/GitLab) as the backbone of how code gets written, reviewed, and shipped — the branch/commit/merge workflow in this chapter is not optional professional knowledge, it's table stakes.
- The "isolate a hotfix from in-progress feature work" scenario from this chapter's hook happens constantly on real teams, and it's specifically branching (Sub-topic 3) that makes it routine instead of a crisis.
- Teams that allow rebasing local, unshared commits but require
revertfor anything already merged to a shared branch are applying exactly the rule from Sub-topic 5/6 — it's one of the most common actual team git policies, not a theoretical distinction.
Points to Remember
- Version control replaces manual folder-copying with permanent, queryable commit history and a clean way to isolate independent lines of work.
- The core workflow —
init,add,commit,status,diff,log— is built around the staging area: a deliberate holding zone between working files and a permanent snapshot. - Branches are cheap, movable pointers to commits, not copies of the project — this is what makes isolating a hotfix from in-progress feature work fast and routine.
- Merging combines diverged branches: a fast-forward when possible, a two-parent merge commit otherwise, and a conflict exactly where both sides changed the same lines differently.
- Rebase replays commits onto a new base for a linear history, but rewrites commit hashes — safe only for commits nobody else has already pulled.
restore,reset(soft/mixed/hard), andreverteach undo something different, with different safety guarantees;stashshelves work temporarily;reflogis the recovery net when a hard reset removes more than intended.