Summary of Git Undo Operations: Differences Between reset, revert, and restore
Git provides three undo tools: `reset`, `revert`, and `restore`. They have similar functions but different scenarios, so you need to choose based on the situation: - **git reset**: Adjusts the branch pointer and discards partial commits. There are three modes: `--mixed` (default, reverts the pointer and staging area, preserves the working directory), `--soft` (only reverts the pointer, preserves changes), and `--hard` (complete rollback, most dangerous). It is suitable for quick rollbacks of local unpushed changes. `--hard` is strictly prohibited for already pushed branches. - **git revert**: Creates a new commit to reverse the changes, preserving the original history. It has a simple syntax (e.g., `git revert HEAD~1`). It safely rolls back pushed branches without destroying the team's history. - **git restore**: Precisely restores files without affecting the branch. It can undo staging (`git restore --staged <file>`) or restore a single file to a historical version (`git restore --source=HEAD~1 <file>`). It replaces the old `git checkout --` and has a clearer semantic meaning. **Differences**: `reset` adjusts the branch pointer (risky), `revert` adds undo commits (safe), and `restore` restores individual files (precise). Decision mnemonic: For local unpushed changes... (Note: The original Chinese ends with "决策口诀:本地未推用" which is incomplete; the translation assumes the intended context of "For local unpushed changes, use...".)
Read More