昨日改代码时遇到一个比较蛋疼的场景,简单展开一下:
背景:手头的一个代码仓库,每个分支的 push 都会触发一次 CI/CD,构建、部署到一个单独的测试环境,为了保证测试环境及时同步最新代码,CI 流程中会有一个步骤,检查当前 push 的分支是否已合并 master 的改动。
假设这个仓库有三个分支:
master
分支(所有代码都应基于它去修改)
feature-1
分支(我正在开发的)
feature-2
分支(其他人开发的另一个功能)
另一个人 feature-2
正式发布,然后合并到了 master
,我的 feature-1
开发的时候,需要同步 master
的最新代码才可正常部署测试环境。
问题来了,feature-2
与 feature-1
都同时大面积改动了相同的几个模块,产生大面积的合并冲突,一时半会难以快速解决;但又希望能先把 feature-1
先部署到测试环境给相关人先用着。
与其让人干等着解决冲突,有无绕过 CI 的 master 合并检查的姿势?把工作流程变的异步非阻塞一些。
带着这个问题 Google 一番,发现了 git merge -s ours master
的操作,大意是合并时忽略 master 的代码,只用自己这一侧的改动,但 commit 的父子关系能包含到 master。
If you want to do something like this but not have Git even try to merge changes from the other side in, there is a more draconian option, which is the “ours” merge strategy. This is different from the “ours” recursive merge option.
This will basically do a fake merge. It will record a new merge commit with both branches as parents, but it will not even look at the branch you’re merging in. It will simply record as the result of the merge the exact code in your current branch.
$ git merge -s ours mundo
Merge made by the 'ours' strategy.
$ git diff HEAD HEAD~
$
You can see that there is no difference between the branch we were on and the result of the merge.
This can often be useful to basically trick Git into thinking that a branch is already merged when doing a merge later on. For example, say you branched off a release branch and have done some work on it that you will want to merge back into your master branch at some point. In the meantime some bugfix on master needs to be backported into your release branch. You can merge the bugfix branch into the release branch and also merge -s ours the same branch into your master branch (even though the fix is already there) so when you later merge the release branch again, there are no conflicts from the bugfix.
参考:
所以最终操作就变成了:
# 开一个备份分支
$ git checkout -b feature-1-debug
# 合并远程的 master(虚假的合并)
$ git fetch
$ git merge -s ours origin/master
# 推上远端,触发 CI 构建
$ git push -u origin feature-1-debug
当然,解决完冲突还是要切回原分支的,这里也做一个记录,抛砖引玉~