无尘阁日记

无尘阁日记

Git Push 被拒绝?解析原因及最佳解决方案!
2025-02-28

问题:

 ! [rejected]            feature/ZPYPR-dev -> feature/ZPYPR-dev (fetch first)

error: failed to push some refs to 'http://bitbucket.zpy360.com/scm/zpypr/zpy-pro-backend.git'

hint: Updates were rejected because the remote contains work that you do

hint: not have locally. This is usually caused by another repository pushing

hint: to the same ref. You may want to first integrate the remote changes

hint: (e.g., 'git pull ...') before pushing again.

hint: See the 'Note about fast-forwards' in 'git push --help' for details.

分析下咋解决


解决:

你的 Git push 失败 了,错误信息如下:

[rejected] feature/ZPYPR-dev -> feature/ZPYPR-dev (fetch first)error: failed to push some refs to 'http://bitbucket.zpy360.com/scm/zpypr/zpy-pro-backend.git'hint: Updates were rejected because the remote contains work that you dohint: not have locally. This is usually caused by another repository pushinghint: to the same ref. You may want to first integrate the remote changeshint: (e.g., 'git pull ...') before pushing again.

这表明 远程分支 feature/ZPYPR-dev 上已经有了你本地没有的提交,你需要先同步远程分支的变更,再进行 push


解决方案

方法 1:使用 git pull --rebase

推荐使用 rebase 方式来拉取最新代码,以保持提交历史的整洁:

git pull --rebase origin feature/ZPYPR-dev
  • --rebase 会 把你的本地提交应用到最新的远程分支之上,避免产生额外的合并提交(merge commit)。

  • 如果有冲突,需要手动解决冲突后,再执行:

    git rebase --continue

然后重新 push

git push origin feature/ZPYPR-dev

方法 2:如果不想 rebase,使用 git pull --merge

如果你不熟悉 rebase,可以使用 普通合并(merge) 方式:

git pull origin feature/ZPYPR-dev

然后处理冲突(如果有),再 commit

git commit -m "Resolved merge conflicts"git push origin feature/ZPYPR-dev

⚠️ 注意:这种方式会在 Git 历史中创建一个 “Merge commit”,如果你希望保持历史整洁,建议用 rebase


方法 3:强制推送(谨慎使用!)

如果你确定远程的更改可以被覆盖(如你是唯一开发者,或者远程的变更是无用的),可以使用 强制推送

git push --force origin feature/ZPYPR-dev

⚠️ 警告--force 会覆盖远程分支,导致其他人提交的代码丢失,不推荐随意使用!
如果要保留远程的提交,但仍然强制推送,可以用 --force-with-lease(更安全):

git push --force-with-lease origin feature/ZPYPR-dev

最佳实践

  1. 推荐使用 git pull --rebase,保证提交历史整洁。

  2. 如果 rebase 失败,就用 git pull --merge,但历史会有额外的合并提交。

  3. 不要随便用 --force,除非你完全确定远程分支的更改可以被覆盖。

这样你就能成功 push 代码了! 🚀