Engineering Toolkit, lesson 6
Undoing things in Git
Match each mistake to the undo that fixes it without losing work.
"Commits and the staging area" and "Branches, merges and conflicts": the staging area, HEAD and HEAD~1.
Part 1. Before you commit: restore and stash
Most mistakes happen before anything is committed. You tried an idea in count.py and it made things worse, and you also edited the README, which you want to keep.
$ git status --short
M README.md
M count.py
$ git diff count.py
diff --git a/count.py b/count.py
index 53b8476..1bbdd40 100644
--- a/count.py
+++ b/count.py
@@ -5,5 +5,5 @@ from collections import Counter
text = open(sys.argv[1]).read().lower()
words = re.findall(r"[a-z']+", text)
print("words:", len(words))
-for word, n in Counter(words).most_common(3):
+for word, n in Counter(words).most_common(30):
print(word, n)
$ git restore count.py
$ git status --short
M README.mdYour turn
You run git restore count.py on a file holding an afternoon of edits you never staged or committed. Can you get the edits back?
git restore replaces the file with the last committed version, with no question asked. If in doubt, git stash first: it saves the edits and cleans the folder in one step.git restore --staged is the gentler one: it takes a file out of the next commit and leaves your edits alone. git stash sets all your changes aside, so you get a clean folder (to switch branch, or pull) without committing half-done work. git stash pop brings them back.
$ git add README.md
$ git restore --staged README.md
$ git status --short
M README.md
$ git stash
Saved working directory and index state WIP on main: a24cc41 Leave out environments, secrets and data
$ git status --short
$ git stash pop
On branch main
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: README.md
no changes added to commit (use "git add" and/or "git commit -a")
Dropped refs/stash@{0} (a67a53ce222dad950e8b7350a26929c9d808c1c7)Stash
A shelf for uncommitted changes. git stash saves them and cleans the working tree, git stash list shows what's on the shelf, and git stash pop puts the newest back.
Part 2. The last commit: amend and reset
Keep going with Pro
You've done the first part. Pro opens the rest of this lesson, and every other one.
- The last commit: amend and reset
- Already shared: revert
- When a commit seems lost: the reflog
Engineering Toolkit overviewSpotted a mistake? Tell us.