1. 当Git说"branches have diverged"时究竟发生了什么?
那天下午,我正在调试一个CNN模型的训练过程,随手加了几行日志输出。这看起来是个再普通不过的修改:
bash复制git add ml/train_cnn.py
git commit -m "debug: add logs"
git push
然而Git的响应却让我愣住了:
code复制! [rejected] kylin/3.3.1-demo -> kylin/3.3.1-demo (fetch first)
error: failed to push some refs to 'http://xxx/algorithm/DeepLearning.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally.
这个场景相信很多开发者都遇到过——你的本地提交突然无法推送了。表面上看这是个简单的冲突,但实际上Git在向我们传递一个更重要的信息:我们的代码历史已经分叉了。
1.1 理解分支分叉的本质
执行git pull后,更详细的提示出现了:
code复制You have divergent branches and need to specify how to reconcile them.
Your branch and 'origin/kylin/3.3.1-demo' have diverged,
and have 1 and 20 different commits each.
这行输出包含了三个关键信息:
- 本地分支比远程分支多了1个提交(我的debug日志)
- 远程分支比本地分支多了20个提交(同事们的修改)
- Git不知道该如何协调这两个分支的历史
用图形表示就是:
code复制A --- B --- C --- D --- ... --- T (origin)
\
E (local)
这里有个重要细节:Git其实并不关心代码内容是否冲突,它只关心提交历史的结构。
