GIT - 5.9 Time travel with reset and reflog
This lesson is about time-travelling through your Git history using git reset and recovering "lost" commits with git reflog. The starting point is a clean repository on master. We modify coucou.html, add a line, stage it with git add ., and modify it again so we have changes in both the index and the working directory at the same time.
The three reset modes
Sometimes we want to rewind HEAD to a previous commit. git reset can do this in three different flavors:
--soft— only movesHEAD. The staging area and working directory are left untouched.--mixed(default) — movesHEADand resets the staging area, but keeps changes in the working directory.--hard— the most destructive: movesHEAD, wipes the staging area and the working directory back to the target commit's state.
We can try each one in turn:
git reset --soft <commit-hash>
git reset --mixed <commit-hash>
git reset --hard <commit-hash>
After --soft, git hist shows HEAD at the chosen commit while all our edits remain staged. After --mixed, the changes are unstaged but still present in the working directory. After --hard, the working directory is empty — every pending change is gone.
Rescuing lost commits with git reflog
A hard reset feels scary because git log stops listing the discarded commits — they look gone forever. But Git keeps a private journal of every move HEAD has ever made:
git reflog
While git log lists commit hashes from the project's history, git reflog lists every action that has ever moved HEAD: commits, resets, checkouts, branch switches, etc. From that list we can pick the hash of the previous tip — say the commit right before the hard reset — and replay it:
git reset --hard <previous-head-hash>
Running git hist shows the history is fully restored. The combo reset + reflog gives total control over time travel inside your repository — and is the standard trick to recover from accidental hard resets.