The Art of Undoing
Concept:
git log shows your commit history β add --oneline --graph --all for a visual tree of all branches. git diff shows what changed (Working Dir vs Staging, or --staged for Staging vs last commit). Undoing maps to the 4 areas: 'git restore' discards Working Dir changes, 'git restore --staged' unstages, 'git reset' undoes local commits, and 'git revert' safely undoes pushed commits by creating a new undo-commit.
Socrates:
You have committed and pushed many times. But tell me β have you ever needed to undo a commit?
Student:
Yes! And it was terrifying. I never knew which command to use.
Socrates:
Because you did not have the map. Remember our four areas? Each undo command targets a specific area. If you know which area you want to roll back, the command reveals itself.
Student:
So if I changed a file but haven't staged it yet?
Socrates:
Then the damage is in the Working Directory. 'git restore' discards those changes. What if you already staged the file?
Student:
'git restore --staged' to move it back out of Staging?
Socrates:
You learn quickly. And what if you already committed?
Student:
That's where I always got lost.
Socrates:
Two paths. If the commit is only local β never pushed β you can rewrite history with 'git reset'. Soft keeps your changes staged. Mixed puts them back in the Working Directory. Hard... erases everything.
Student:
And if I already pushed?
Socrates:
Then you must not rewrite history β your teammates have already received it. Instead, 'git revert' creates a new commit that reverses the damage. The mistake stays in history, but its effects are undone. Honest and safe.
Student:
So revert is for shared work, reset is for local mistakes?
Socrates:
Now you have the complete picture. But first β let us also look at history. 'git log --oneline --graph --all' shows you the full tree of your repository. And 'git diff' shows exactly what changed. Know where you are before you try to undo. Now β a bad commit awaits you. Fix it safely.
Example Code:
Inspecting:
git log --oneline --graph --all # visual history
git diff # Working Dir vs Staging
git diff --staged # Staging vs last commit
git show <hash> # what changed in one commit
Undoing (mapped to the 4 areas):
ββββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββ
β What you want to undo β Command β
ββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββ€
β Working Dir changes β git restore <file> β
β Staged file (back to unstaged) β git restore --staged <file> β
β Last commit (keep staged) β git reset --soft HEAD~1 β
β Last commit (keep in Work Dir) β git reset --mixed HEAD~1 β
β Last commit (discard all) β οΈ β git reset --hard HEAD~1 β
β Pushed commit (safe for team) β git revert HEAD β
ββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββ
Your Assignment
A bad commit has been made. Use 'git revert HEAD' to undo it safely, then check the log shows the revert.
Git Console
git>