我想推送我的本地文件,并将它们放在远程仓库中,而不必处理 merge 冲突。我只希望我的本地版本优先于远程版本。
我如何使用 Git 执行此操作?
最佳答案
您应该能够使用
将您的本地修订强制到远程仓库git push -f <remote> <branch>
(例如 git push -f origin master
)。离开 <remote>
和 <branch>
将强制推送所有已设置 --set-upstream
的本地分支。
请注意,如果其他人共享此存储库,他们的修订历史将与新的冲突。如果他们在更改点之后有任何本地提交,他们将变得无效。
更新:我想添加一个旁注。如果您正在创建其他人将审查的更改,那么创建一个包含这些更改的分支并定期 rebase 以使它们与主要开发分支保持同步的情况并不少见。让其他开发者知道这会定期发生,这样他们就会知道会发生什么。
更新 2:由于越来越多的观众,我想添加一些额外的信息,说明当您的 upstream
确实遇到强制推送时该怎么做。
假设我已经克隆了您的存储库并添加了一些这样的提交:
D----E topic / A----B----C development
但后来 development
分支被 rebase
击中,这将导致我在运行 git pull
时收到如下错误:
Unpacking objects: 100% (3/3), done. From <repo-location> * branch development -> FETCH_HEAD Auto-merging <files> CONFLICT (content): Merge conflict in <locations> Automatic merge failed; fix conflicts and then commit the result.
在这里我可以修复冲突和 commit
,但这会给我留下非常丑陋的提交历史:
C----D----E----F topic / / A----B--------------C' development
使用 git pull --force
可能看起来很诱人,但要小心,因为这会让您陷入搁浅的提交:
D----E topic A----B----C' development
所以最好的选择可能是做一个 git pull --rebase
。这将要求我像以前一样解决任何冲突,但对于每个步骤,我将使用 git rebase --continue
而不是提交。最后,提交历史看起来会好得多:
D'---E' topic / A----B----C' development
更新 3:您还可以使用 --force-with-lease
选项作为“更安全”的强制
推,as mentioned by Cupcake in his
answer:
Force pushing with a "lease" allows the force push to fail if there are new commits on the remote that you didn't expect (technically, if you haven't fetched them into your remote-tracking branch yet), which is useful if you don't want to accidentally overwrite someone else's commits that you didn't even know about yet, and you just want to overwrite your own:
git push <remote> <branch> --force-with-lease
You can learn more details about how to use
--force-with-lease
by reading any of the following:
关于git - 强制 "git push"覆盖远程文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10510462/