🐍 Python for Everyone

← Back to all chapters

Chapter 28 of 33 Intermediate 75 min read

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

Picture this: you've been mid-way through a new feature for two days — half-finished, half-broken, code deliberately in a messy state while you figure it out. Then a customer reports a bug in production that needs a fix today, built on top of the last stable version, not your half-broken feature. Without version control, those two states of the code — "stable, needs a quick fix" and "in-progress, currently broken" — live in the same files, tangled together, with no way to cleanly separate them. This chapter is about the tool that makes that a non-problem.
Sub-topic 1 of 6

1. Why version control matters

At a glance
  • 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.
Why this matters: every one of these problems compounds the moment more than one person — or even one person working on more than one thing at once — touches the same codebase. Git exists because "just keep careful copies of your folder" stops working almost immediately in real, collaborative software work.

Before git, a surprisingly common (and surprisingly recent, in some teams) way to "version" a project looked like this:

a familiar, git-free folder listing
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.

What is... a repository? A repository (or "repo") is a project folder that git is tracking. It contains your actual files, plus a hidden .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.

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.

Quick recap
  • 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 .git folder holding its full history.
  • Commits and branches are git's answer to isolating risky/in-progress work from stable, shippable work.
Sub-topic 2 of 6

2. The core git workflow

At a glance
  • git init turns a folder into a repository.
  • git add stages changes; git commit permanently records the staged changes as a snapshot.
  • git status, git diff, and git log are how you constantly check what's changed, what's staged, and what's already been committed.
Why this matters: these six commands — 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:

terminal
$ git init -b main
$ git status
actual output
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)
What is... the staging area? The staging area (also called "the index") is a holding zone between your working files and a commit. 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:

tasks.py
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']}")
terminal
$ git add tasks.py
$ git status
actual output
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:

terminal
$ git commit -m "Add basic task add/list functions"
$ git log
actual output
[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.

What is... a commit, actually? A commit is a permanent, complete snapshot of every tracked file at the moment it was made — not just a diff. Each commit also stores a pointer to its parent commit (the one before it), which is how git reconstructs the entire history as a chain, and how 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:

terminal
$ git diff
actual output, after adding a complete_task() function to tasks.py
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:

terminal
$ git add tasks.py
$ git commit -m "Add complete_task function"
$ git log --oneline
actual output
[main c8e706b] Add complete_task function
 1 file changed, 5 insertions(+)
c8e706b Add complete_task function
5d9184b Add basic task add/list functions
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.

Quick recap
  • git init, git add, git commit are 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 log are read-only tools for seeing exactly where things stand — use them constantly, not just when something looks wrong.
Sub-topic 3 of 6

3. Branching

At a glance
  • 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.
Why this matters: this is the direct mechanism behind the hook's hotfix scenario — a branch made from main's last stable commit is completely isolated from whatever's in progress on a feature branch, right up until someone chooses to merge 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:

terminal
$ git branch feature/delete-task
$ git branch
actual output
  feature/delete-task
* main
What is... a branch, actually? A branch is nothing more than a lightweight, movable label pointing at one specific commit. When you make a new commit while on a branch, git just moves that branch's pointer forward to the new commit — it doesn't duplicate any files. This "pointer" model is exactly why creating a branch in git is instant, regardless of how large the project is, unlike copying an entire project folder by hand.

git switch moves your working files to match a different branch's latest commit:

terminal
$ git switch feature/delete-task
$ git branch
actual output
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:

terminal
$ git add tasks.py
$ git commit -m "Add delete_task function"
$ git log --oneline --all --graph
actual output -- two branch pointers, one shared history so far
* 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:

terminal
$ git switch -c feature/priority
actual output
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.

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.

Quick recap
  • 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.
Sub-topic 4 of 6

4. Merging

At a glance
  • 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.
Why this matters: merging is how the isolated work from Sub-topic 3 actually gets back together — and conflicts are not a sign something went wrong; they're git correctly refusing to silently guess at a decision only you can make.

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:

terminal
$ git switch main
$ git merge feature/delete-task
actual output
Switched to branch 'main'
Updating c8e706b..a16051c
Fast-forward
 tasks.py | 5 +++++
 1 file changed, 5 insertions(+)
What is... a fast-forward merge? When the branch you're merging into hasn't gained any commits since the branch you're merging from split off, there's nothing to actually combine — the feature branch's history is already a direct, unbroken continuation of main's. Git just slides main's pointer forward to match, with no merge commit created at all. It's called "fast-forward" because that's literally all that happens.

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:

terminal
$ git branch -d feature/delete-task
actual output
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:

terminal
$ git switch main
$ git merge feature/priority
actual output
Auto-merging tasks.py
CONFLICT (content): Merge conflict in tasks.py
Automatic merge failed; fix conflicts and then commit the result.
What is... a merge conflict? A merge conflict happens when both branches being merged changed the same lines of the same file in different, incompatible ways. Git can automatically combine changes to different parts of a file (or different files entirely) without any trouble — a conflict only happens on the specific overlapping lines where it genuinely can't tell which version you want, or whether you want both.

Opening tasks.py now shows git's conflict markers, sitting directly in the file:

tasks.py (mid-conflict)
<<<<<<< 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:

tasks.py (resolved)
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:

terminal
$ git add tasks.py
$ git commit -m "Merge feature/priority into main"
$ git log --oneline --graph --all
actual output -- note the merge commit has two parents
*   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
What is... a merge commit? A normal commit has exactly one parent. A merge commit is the one exception — it has two parents (the tip of each branch being merged), and its snapshot is the combined result of both histories, including any conflict resolutions made by hand. git log --graph visualizes this directly: the branching and rejoining lines (|\ and |/) show exactly where history split and came back together.
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.

Quick recap
  • 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, then git commit (or git merge --abort to cancel entirely).
Sub-topic 5 of 6

5. Rebase

At a glance
  • git rebase replays 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.
Why this matters: rebase and merge solve the same underlying problem (combining diverged branches) with genuinely different trade-offs — and the "don't rebase shared history" rule is one of the few git rules that causes real, team-wide pain when broken, not just a style preference.

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:

terminal
$ git log --oneline --graph --all
actual output -- diverged history
* 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:

terminal
$ git switch feature/tags
$ git rebase main
actual output -- a conflict during rebase, then resolving it
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:

terminal
$ git add tasks.py
$ git rebase --continue
$ git log --oneline --graph --all
actual output -- a straight line, no merge commit
[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
...
What is... "replaying" a commit? Rebase doesn't move the original commit — it can't, since a commit's hash is fixed by its content and parent (Sub-topic 2). Instead, for each commit being rebased, git computes the same change that commit represents, and applies it fresh on top of the new base, creating a brand-new commit with a new hash and a new parent. The code ends up the same; the commit's identity in git's history does not.

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:

terminal
$ 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
actual output after squashing and rewording the combined message
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.
The rule, stated plainly: never rebase commits that have already been pushed and could be in someone else's local history. If a commit only exists on your machine, rebasing it is safe cleanup. The instant it's shared (pushed, pulled by a teammate, merged into a shared branch), rewriting it with rebase creates two different versions of "the same" commit under different hashes — and everyone who already has the old version now has a diverging, conflicting history to untangle.
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.

Quick recap
  • 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).
Sub-topic 6 of 6

6. Undoing things safely

At a glance
  • git status/git diff are always the first step — know exactly what state you're in before undoing anything.
  • git restore discards uncommitted file changes; git reset moves your branch pointer (with three modes controlling what happens to the changes); git revert undoes a commit by creating a new, opposite commit.
  • git stash temporarily shelves uncommitted work; git reflog can recover a commit that looks "lost" after a hard reset.
Why this matters: these commands look similar and are frequently confused, but they have real, different consequences — picking the wrong one can quietly discard work that 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":

terminal
$ git status
$ git restore tasks.py
$ git status
actual output -- before and after restore
On branch main
Changes not staged for commit:
	modified:   tasks.py

On branch main
nothing to commit, working tree clean
What is... HEAD? 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:

terminal
$ git reset --soft HEAD~1
$ git status
actual output -- commit undone, changes kept staged
On branch main
Changes to be committed:
	modified:   tasks.py
terminal
$ git commit -m "Add broken_feature (bug)"
$ git reset HEAD~1
$ git status
actual output -- default (--mixed): commit undone, changes unstaged but kept
Unstaged changes after reset:
M	tasks.py
On branch main
Changes not staged for commit:
	modified:   tasks.py
terminal
$ git add tasks.py && git commit -m "Add broken_feature (bug)"
$ git reset --hard HEAD~1
$ git status
actual output -- commit AND the changes both gone
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:

git reset's three modes
              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.

What is... the real difference between reset and revert? 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.
terminal
$ git add tasks.py && git commit -m "Add broken_feature (bug)"
$ git revert --no-edit HEAD
$ git log --oneline -3
actual output -- a new commit undoing the last one, original still in history
[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:

terminal
$ git status
$ git stash
$ git status
$ git stash list
actual output
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:

terminal
$ git stash pop
actual output
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:

terminal
$ git commit -m "Add important_feature: sort tasks"
$ git reset --hard HEAD~1
$ git log --oneline -1
actual output -- the commit no longer shows in the log
HEAD is now at b2351e5 Revert "Add broken_feature (bug)"
b2351e5 Revert "Add broken_feature (bug)"
terminal
$ git reflog
actual output -- the "lost" commit's hash is still right there
b2351e5 HEAD@{0}: reset: moving to HEAD~1
e230a4a HEAD@{1}: commit: Add important_feature: sort tasks
b2351e5 HEAD@{2}: reset: moving to HEAD
...
terminal
$ git reset --hard e230a4a
$ git log --oneline -1
actual output -- fully recovered
HEAD is now at e230a4a Add important_feature: sort tasks
e230a4a Add important_feature: sort tasks
What is... reflog, precisely? 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.
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.

Quick recap
  • git status/git diff first, always — know what you're about to undo before undoing it.
  • restore for uncommitted file changes; reset (soft/mixed/hard) for moving your branch pointer with different consequences for staged/working changes; revert for safely undoing anything already shared.
  • stash shelves work temporarily; reflog is the recovery net for a commit that looks lost after a hard reset.
In the Real World

Points to Remember

← All Chapters Take the Quiz →