一、立即停止操作并检查状态
bash
git status # 查看当前工作区状态
git log --oneline # 检查提交历史
二、恢复被覆盖的代码
场景 1:未提交的本地修改被覆盖
bash
git reflog # 查看所有操作记录
git checkout <commit-hash> -- . # 恢复指定commit的所有文件
场景 2:已提交的代码被错误回滚
bash
git reflog # 找到被覆盖的commit哈希
git branch recover-branch <commit-hash> # 创建恢复分支
git checkout recover-branch # 切换到恢复分支
三、高级恢复技巧
- 恢复特定文件:
bash
git checkout <commit-hash> -- path/to/file
- 恢复整个目录:
bash
git checkout <commit-hash> -- directory/
四、处理远程仓库覆盖
情况 1:未推送到远程
bash
git reset --soft <commit-hash> # 重置到指定commit但保留修改
情况 2:已推送到远程
bash
git push origin +recover-branch # 强制推送恢复分支
git branch -D recover-branch # 删除临时分支
五、预防措施
- 回滚前备份代码:
bash
git checkout -b backup-branch # 创建备份分支
- 使用安全回滚命令:
bash
git revert <commit-hash> # 创建撤销提交而不是直接删除
- 定期备份 reflog:
bash
git config --global gc.reflogExpire "1 month" # 延长reflog保存时间
六、团队协作注意事项
- 如果覆盖了他人提交:
bash
git revert <bad-commit> # 创建新的撤销提交
git push --force-with-lease # 安全强制推送
- 通知团队成员:
bash
git log --graph --oneline --decorate # 提供操作记录