Accidental Force 推送数据 Loss
错误信息
WARNING: force-pushed 到主要, overwriting N 提交
快速摘要
force 推送到 shared 分支 overwrote 提交那个 others 有 pushed. overwritten 提交可能是 recoverable.
为什么发生
git 推送 --force 是运行 on shared 分支 (e.g. 主要)
rebase or amend 是 followed 通过 force 推送到 shared 分支
分支 protection 是不启用 on remote
最小示例
git rebase main
git push --force origin main # overwrites teammates' commits!# Recovery: a teammate who has the lost commits pushes them
git push origin main # from the teammate's machine
# Prevention: use --force-with-lease
git push --force-with-lease origin main # rejected if others have pushed
# Enable branch protection on GitHub to prevent force push to mainForce 推送到 shared 分支 destroys others' 提交. Recover 从 teammates' 局部复制 or reflog. Prevent 使用 --force-使用-lease and 分支 protection.
如何诊断
检查 remote's reflog (如果 accessible) for 上一个 HEAD
Ask teammates for 它们的局部提交 hashes 那个是 overwritten
检查 GitHub's activity log or 事件 API for 上一个状态
如何修复
如果 teammate 有 lost 提交 locally, 它们能推送它们再次
On GitHub, force-pushed 提交可能 still 是 accessible 通过 hash 直到 garbage 集合
Recover 从 reflog: git reflog on remote or teammate's machine
启用分支 protection 到 prevent future force pushes 到 shared 分支
如何预防
从不 force 推送到 shared 分支 (主要, develop)
Use --force-使用-lease 相反的 --force
启用分支 protection 规则 on GitHub/GitLab
Use feature 分支 for history-rewriting 工作