意外提交到了错误的分支
快速摘要
你将工作提交到了错误的分支 —— 提交在 main 上但应该在功能分支上,你需要安全地重新定位它。
为什么发生
开始工作前忘记创建或切换到功能分支,直接提交到了 main
之前的 git checkout 让你留在意外的分支上,提交前未用 git branch 验证
自动化工具或 IDE 代表你提交到了当前检出的分支而你未察觉
最小示例
✗ 错误代码
git checkout main
git commit -m 'new feature' # oops, should be on feature branch
git push origin main # pushed to wrong branch!✓ 修复代码
git branch feature/new # create feature branch at current commit
git checkout main
git reset --hard HEAD~1 # remove commit from main
git checkout feature/new # commit is now only on feature/new在当前提交创建分支保留工作,然后将 main 回退一个提交以移除它,新分支上仍保留该提交。
如何诊断
运行 git branch --show-current 确认当前分支,git log --oneline -3 查看最近提交
检查 git log --oneline main..HEAD 或 git log --oneline HEAD..main 了解与 main 的分歧
如果不是最近的提交,使用 git reflog 找到需要移动的确切提交哈希
如何修复
从当前提交创建新分支 git branch feature/new,然后 git checkout main && git reset --hard HEAD~1 将 main 回退
使用 git cherry-pick 将提交复制到正确分支,然后回退错误分支以移除它
如果已推送,在本地重置 main 后用 git push --force-with-lease 强制推送修正的分支
如何预防
提交前始终检查 git branch --show-current,并在 main 上设置分支保护规则防止直接提交
配置 IDE 或 shell 提示符醒目显示当前分支,避免提交到错误分支
相关资源
相关课程
- Branching Workflow
学习分支最佳实践。