Git客户端提交代码与Git服务器端有冲突的解决方法
问题描述
当你在向服务器上提交代码时出错,如下:
wcs@wcsMacBook-Pro knowledge % git push
To http://192.168.0.19/wangchangshao/knowledge.git
! [rejected] main -> main (fetch first)
error: failed to push some refs to 'http://192.168.0.19/wangchangshao/knowledge.git'
hint: Updates were rejected because the remote contains work that you do not
hint: have locally. This is usually caused by another repository pushing to
hint: the same ref. If you want to integrate the remote changes, use
hint: 'git pull' before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
让你先要git pull,可是git pull时也是出错,如下:
wcs@wcsMacBook-Pro knowledge % git pull
remote: Enumerating objects: 4, done.
remote: Counting objects: 100% (4/4), done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 3 (delta 1), reused 0 (delta 0), pack-reused 0 (from 0)
Unpacking objects: 100% (3/3), 860 bytes | 215.00 KiB/s, done.
From http://192.168.0.19/wangchangshao/knowledge
fc3713d..3095ff7 main -> origin/main
hint: You have divergent branches and need to specify how to reconcile them.
hint: You can do so by running one of the following commands sometime before
hint: your next pull:
hint:
hint: git config pull.rebase false # merge
hint: git config pull.rebase true # rebase
hint: git config pull.ff only # fast-forward only
hint:
hint: You can replace "git config" with "git config --global" to set a default
hint: preference for all repositories. You can also pass --rebase, --no-rebase,
hint: or --ff-only on the command line to override the configured default per
hint: invocation.
fatal: Need to specify how to reconcile divergent branches.
这个提示意味着 *你的本地分支和远程分支有分叉,需要指定如何处理冲突的分支历史。以下是解决方案:***
快速解决方法
1. 合并方式(保留双方历史)
git pull --no-rebase
或直接:
git pull
2. 变基方式(将你的提交放在远程最新提交之上)
git pull --rebase
这会重写历史,让提交历史更线性整洁
3. 仅快进合并(最安全)
git pull --ff-only
如果无法快进合并,这个命令会失败,需要你手动处理
推荐做法
根据你的需求设置默认行为:
如果你是团队协作,建议用合并方式:
# 设置为默认使用合并(推荐给初学者)
git config --global pull.rebase false
# 然后拉取
git pull
如果你喜欢整洁的线性历史,用变基方式:
# 设置为默认使用变基
git config --global pull.rebase true
# 然后拉取
git pull
或者设置只允许快进合并(最严格):
git config --global pull.ff only
三种方式的区别
| 方式 | 效果 | 适用场景 |
|---|---|---|
| merge(合并) | 创建新的合并提交,保留所有历史 | 团队协作,需要看到完整合并历史 |
| rebase(变基) | 将你的提交重新应用到远程最新提交后,历史线性 | 个人项目,想要整洁的历史记录 |
| ff-only(仅快进) | 只有能直接快进时才成功,否则失败 | 想要保持分支完全同步,避免复杂合并 |
实际工作流程建议
- 先保存你的工作(如果有未提交的修改):
git stash # 暂存修改
git pull --rebase # 拉取并变基
git stash pop # 恢复修改
- 如果遇到冲突,Git会提示你解决冲突,然后:
# 如果是用 rebase 方式
git add . # 添加解决后的文件
git rebase --continue # 继续变基
# 如果是用 merge 方式
git add . # 添加解决后的文件
git commit # 提交合并
简单总结:如果是团队项目,用 merge;如果是个人项目或想要整洁历史,用 rebase;如果不确定,先用 merge。