# Undoing changes: revert, reset, stash and reflog

Pick the right undo every time: discard an edit, unstage a file, take back a local commit with reset, undo a pushed one with revert, set work aside with stash, recover with reflog.

Course: [Git & GitHub](https://devops.rajeev.pro/courses/git), lesson 8. About 35 minutes, intermediate. Source: https://devops.rajeev.pro/courses/git/08-undoing-changes

## What you will learn

- Choose the right undo for where the mistake is (working folder, staging, local commit or pushed commit)
- Undo a pushed commit safely with git revert
- Use reset --soft, --mixed and --hard, and say exactly what each one keeps
- Put unfinished work aside with git stash and bring it back
- Recover "lost" commits and branches with git reflog

## Which undo?

**The moment this lesson is for.** It's 6 p.m. You've just committed a change that breaks the build,
or deleted a file you needed, or pushed a password. Your first instinct is to panic, and your
second is to delete the folder and clone again. Both are wrong. Git almost never loses anything that
was committed, and it has a precise undo for every kind of mistake. The trick is choosing the right
one, because some undos are safe on a shared branch and some quietly break your teammates' copies.

Every undo starts with one question: **where is the mistake now?** The answer picks the command:

| The mistake is…                          | Undo with                                  | Safe after pushing?           |
| ---------------------------------------- | ------------------------------------------ | ----------------------------- |
| an edit you haven't staged               | `git restore file`                         | n/a (never left your machine) |
| staged, not committed                    | `git restore --staged file`                | n/a                           |
| the last commit, message or missing file | `git commit --amend` (_Rewriting history_) | no                            |
| in local commits, not pushed             | `git reset`                                | no                            |
| in a pushed commit                       | `git revert`                               | **yes**                       |
| "I just lost something"                  | `git reflog`                               | it's local                    |

The dividing line is **pushed**. Before pushing, you may rewrite your own history freely. After pushing,
other people have those commits, so you add new commits instead of removing old ones.

## Revert: undo a commit everyone has

**Why not just delete the bad commit?** Because your teammates already have it. If you remove a
commit from `main` and force-push, their copies still contain it. Their next push either brings it
back or fails with confusing errors, and anyone who built on top of it is now working on history
that no longer exists. Revert avoids all of that.

`git revert` makes a **new commit** that does the opposite of an old one: lines that were added are
removed, and lines that were removed come back. History only grows, so nobody's clone is
disturbed, and the log even records that the change was undone and when:

```sh
$ git log --oneline
26ec4e7 Lower the timeout to 1 second
5a5f6da Add config
5b4574d Add app
$ git revert --no-edit HEAD
[main f390571] Revert "Lower the timeout to 1 second"
 1 file changed, 1 insertion(+), 1 deletion(-)
$ git log --oneline -2
f390571 Revert "Lower the timeout to 1 second"
26ec4e7 Lower the timeout to 1 second
$ cat config.py
TIMEOUT = 30
$ git push
```

Revert any commit by ID, not only the last: `git revert 26ec4e7`. To revert a merge commit, say which
parent is the "main line": `git revert -m 1 <merge-commit>`. On GitHub, every merged pull request has a
**Revert** button that opens a pull request doing exactly this.

> **During an incident.** When a deploy breaks production, revert first and investigate second. A revert is reviewed, small and goes through the normal pipeline. The fix can come later, without the pressure of a live outage.

> **Video.** [Git Tutorial #30: How to Revert a Git Commit Using Git Revert | Learn Git with GitKraken](https://www.youtube.com/watch?v=w4hvcI_4WNQ) (GitKraken)

## Reset: move your branch back

`git reset` moves your current branch to another commit, as if the later commits had never happened.
Its three modes differ only in what they do with the changes from those commits:

> **Figure.** Animated. In each mode, git reset HEAD~1 moves main back from commit B to commit A. With --soft, B's changes go to the staging area, ready to commit again. With --mixed, the default, they go to the working folder as unstaged edits. With --hard, they are thrown away; commit B itself can still be found with git reflog, but uncommitted edits cannot.
>
> All three move the branch back. They differ in where the changes land: staged, kept, or thrown away.

```sh
$ git reset --soft HEAD~1         # undo the commit, keep its changes staged
$ git status --short
M  app.py
$ git reset HEAD~1                # --mixed (default): undo the commit, keep changes unstaged
$ git status --short
 M app.py
$ git reset --hard HEAD~1         # undo the commit and throw its changes away
HEAD is now at d62b38c Commit A
```

| Mode      | Use it to                                                                                |
| --------- | ---------------------------------------------------------------------------------------- |
| `--soft`  | combine your last few commits into one: `git reset --soft HEAD~3`, then one `git commit` |
| `--mixed` | redo the last commit differently: split it, or leave a file out                          |
| `--hard`  | throw away local commits and edits entirely: start again from a known point              |

`HEAD~1` means one commit before HEAD; `HEAD~3` is three back. `git reset --hard origin/main` is the
classic "make my branch exactly match GitHub's", and it deletes anything you had that GitHub doesn't.

> **Two ways to really lose work.** `git reset --hard` and `git restore` delete **uncommitted** edits, and Git can't bring those back: they were never saved. Run `git status` first, and commit or stash anything you might want. And never reset a branch others have pulled: use revert there.

## Stash: put work aside

You're halfway through something when your lead messages: "can you look at this production bug right
now?". Your changes aren't ready to commit, and Git won't let you switch branches while they're in
the way. You could make a "wip" commit, but then you have to remember to undo it.

`git stash` is the clean answer. It saves your uncommitted changes on a shelf and puts your working
folder back to the last commit, so you can switch branches, fix the bug, come back and take your
changes off the shelf exactly as they were:

```sh
$ git stash                        # tracked changes only
Saved working directory and index state WIP on main: 0bb860e B3
$ git status --short
?? new.py
$ git stash -u -m "half-done search"   # -u: include untracked (new) files, -m: a label
$ git stash list
stash@{0}: On main: half-done search
stash@{1}: WIP on main: 0bb860e B3
$ git stash show -p stash@{1}      # what's in it
$ git stash pop                    # apply the newest and remove it from the list
$ git stash apply stash@{1}        # apply one, but keep it in the list
$ git stash drop stash@{1}         # delete one
```

Without `-u`, new files stay behind in your folder; that's the most common stash surprise. Stashes are
for minutes or hours, not weeks: anything longer belongs on a branch (`git stash branch fix/x` turns a
stash into one).

> **Video.** [Git Tutorial #14: What is Git Stash and How to Use It | Learn Git with GitKraken](https://www.youtube.com/watch?v=Ie1EXmd9k0s) (GitKraken)

## Reflog: your safety net

Git quietly records every place `HEAD` has been: every commit, checkout, reset, rebase and merge. That
log, the **reflog**, is how you get back "lost" commits:

```sh
$ git reset --hard HEAD~1          # oops: B3 is gone from the branch
HEAD is now at d62b38c Commit A
$ git reflog -3
d62b38c HEAD@{0}: reset: moving to HEAD~1
0bb860e HEAD@{1}: commit: B3
d62b38c HEAD@{2}: reset: moving to HEAD~1
$ git reset --hard HEAD@{1}        # go back to where HEAD was one step ago
HEAD is now at 0bb860e B3
```

It works for a deleted branch too: `git branch -D spike` printed `(was 1bae2b4)`, so
`git branch spike 1bae2b4` brings it back. If you didn't see the ID, look for the last commit on that
branch in `git reflog`.

The reflog is **local** (it's not pushed or cloned) and entries expire, by default after 90 days. A
commit that was committed is almost never truly lost within that time; it's just unlabelled.

## Mission: A bad deploy and a bad reset

A commit lowered a timeout and broke production after it was pushed. Undo it the safe way. Then, while tidying up locally, you hard-reset away a good commit by mistake. Get it back. End with the timeout restored and no work lost.

- You need: Any folder, plus a bare repository standing in for GitHub
- You'll have: TIMEOUT = 30 on main, and the 'Add retries' commit recovered

```sh
$ git init --bare remote.git && git clone remote.git shop && cd shop
$ echo "TIMEOUT = 30" > config.py && git add . && git commit -m "Add config" && git push -u origin main
$ echo "TIMEOUT = 1" > config.py && git commit -am "Lower the timeout to 1 second" && git push
$ git revert --no-edit HEAD && git push            # 1. production fix: a new commit
$ cat config.py
TIMEOUT = 30
$ echo "RETRIES = 3" >> config.py && git commit -am "Add retries"
$ git reset --hard HEAD~1                          # 2. the mistake
$ grep -c RETRIES config.py
0
$ git reflog -2
5c40083 HEAD@{0}: reset: moving to HEAD~1
be5be3f HEAD@{1}: commit: Add retries
$ git reset --hard HEAD@{1}                        # 3. the recovery
$ grep RETRIES config.py && git push
RETRIES = 3
$ git log --oneline
```

The final log reads: Add retries, Revert "Lower the timeout…", Lower the timeout…, Add config. The bad
commit is still in history, deliberately: it records what happened, and the revert records the fix.

## Try it

- Commit a bad change, push it to a test remote, and undo it with `git revert HEAD`.
- Make two commits, then compare `git reset --soft HEAD~1` with `git reset HEAD~1` using `git status`.
- Stash an edit with a message using `git stash -m`, list it, and bring it back with `git stash pop`.
- Run `git reset --hard HEAD~1`, then find the lost commit in `git reflog` and restore it.
- Delete a branch with `git branch -D`, then recreate it from the ID Git printed.
- Read `git reflog -10` and explain each line.

## Quiz

1. A commit that broke production is already on main and pushed. How do you undo it?
   - git reset --hard HEAD~1 and force-push
   - **git revert <commit>, which adds a new commit that undoes it, then push** (answer)
   - Delete the repository
   - git stash
   Why: revert keeps history intact, so nobody's clone breaks. Resetting a shared branch rewrites history under your teammates.

2. What does git reset --soft HEAD~1 do?
   - Deletes the last commit and its changes
   - **Moves the branch back one commit and keeps its changes staged** (answer)
   - Unstages everything
   - Reverts the last commit
   Why: soft: changes stay staged. mixed (the default): changes stay in your files but unstaged. hard: changes are thrown away.

3. Which reset can lose work that Git can't recover?
   - --soft
   - --mixed
   - **--hard, for uncommitted changes in your working folder** (answer)
   - None of them
   Why: Committed work can come back through the reflog. Uncommitted edits that --hard throws away were never saved in Git, so they are gone.

4. You need to switch branches urgently, but your current work is half done. What do you do?
   - Commit it as "wip" to main
   - **git stash (with -u to include new files), switch, and git stash pop later** (answer)
   - Copy the folder
   - git reset --hard
   Why: stash saves your changes and cleans the working folder. pop puts them back and removes the stash.

5. You ran git reset --hard and lost two commits. How do you get them back?
   - You can't
   - **Find the commit before the reset in git reflog, then git reset --hard HEAD@{1} (or that ID)** (answer)
   - git revert HEAD
   - git stash pop
   Why: The reflog records every position HEAD has been in, locally, for about 90 days. The commits still exist; you just need their ID.

## Resources

- [Pro Git: undoing things](https://git-scm.com/book/en/v2/Git-Basics-Undoing-Things) (Pro Git)
- [Pro Git: reset demystified](https://git-scm.com/book/en/v2/Git-Tools-Reset-Demystified) (Pro Git)
- [Pro Git: stashing and cleaning](https://git-scm.com/book/en/v2/Git-Tools-Stashing-and-Cleaning) (Pro Git)
- [git-reflog documentation](https://git-scm.com/docs/git-reflog) (Git)
- [Oh Shit, Git!?!](https://ohshitgit.com/) (Katie Sylor-Miller)
