Lesson239 words
Recovering data with Git
Recover specific data by using Git commands
Most "lost" work in Git is not lost. Commits become unreachable rather than deleted, and remain until garbage collection.
| Situation | Command |
|---|---|
| Lost a commit after a reset or bad rebase | git reflog to find it, then git checkout or git reset |
| Deleted a branch | git reflog for its tip, then re-create with git branch |
| Want one commit from another branch | git cherry-pick |
| Undo a commit that is already pushed | git revert |
| Recover a deleted file from an earlier commit | git restore --source=<commit> <path> |
Reflog is the safety net
git reflog records where HEAD has been, including states no branch references any more. It is local and expires, so it saves you on your own machine and not on someone else's — and it is the first thing to reach for after a mistaken reset --hard.
Revert versus reset on shared history
| Effect | Safe on a shared branch? | |
|---|---|---|
git revert | Creates a new commit undoing the change | Yes |
git reset | Moves the branch pointer, rewriting history | No |
On anything others have pulled, use revert. Reset rewrites history under everyone's clones, which is the same reason force push is restricted on protected branches.
Primary sources