2.8 Undo safely — restore and amend rules
Mistakes happen. Use the smallest safe undo.
| Situation | Safe habit | Command sketch |
|---|---|---|
| Bad edit, file not staged | Throw away working tree changes to last commit | git restore <file> |
| Staged by mistake | Unstage, keep edits | git restore --staged <file> |
| Last commit message typo, not pushed | Amend message only | git commit --amend -m "New message" |
| Forgot a file in last commit, not pushed | Stage file, amend | git add <file> then git commit --amend --no-edit |
| Already pushed to a shared branch | Do not rewrite; add a new commit that fixes the issue | new commit |
Why so careful with amend? Amend rewrites the last commit id. If others already pulled the old id, history forks and pain starts. Rule for this course: amend only if you have not pushed, or if you are alone on a learning branch your trainer said is safe.
# discard unstaged edits to one file (cannot undo easily — be sure)
git restore app.py
# unstage
git restore --staged app.py
Ravindra Bagale's Tip
Khup students git commit --amend pushed branch var vaprtat aani force push chi garaj padte. Team repos madhe he avoid kara. Navi fix commit takne safer aahe. Lakshat theva!
Practice task
Break a file on purpose, run git restore to fix it, then stage a bad file and unstage with git restore --staged. Write one sentence on when you would refuse to amend.