Talk about merge and rebase



Two major tools for merging code

There are two ways to integrate changes from one branch into another: merge and rebase.

Merge

Merge is a relatively common method of use. It will perform a three-way merge between the latest snapshot of the two branches and the latest common ancestor of the two, and the result of the merge is a new commit object. The benefit of this merged branch is that it has a timeline that shows the context of each branch. Operation command:

git checkout feature

git merge master

or merge into one sentence: git merge master feature

The new merge commit in the feature branch connects the history of the two branches together. You'll end up with a branching structure like this:



The downside of merge is also obvious, the feature branch will introduce a foreign merge commit every time you merge upstream changes. This more or less pollutes your branch history if master is very active. When we participate in the development of a relatively large project, it will increase the difficulty of understanding the project history. As shown in the figure below, it is difficult for you to find the relationship between each branch.



Rebase

The rebase operation is translated into rebase. My language is not very good, so I don't understand the meaning very well. The value of rebase is that you can move the changes committed in the current branch to another branch and replay them. Creates a new commit for each commit on the original branch, rewriting the project's history and does not result in a merge commit. Operation command:

git checkout feature

git rebase master

rebase的原理是回到两个分支最近的共同祖先,根据当前分支(也就是要进行衍合的分支 experiment)后续的历次提交对象,生成一系列文件补丁,然后以基底分支(也就是主干分支 master)最后一个提交对象为新的出发点,逐个应用之前准备好的补丁文件,最后会生成一个新的合并提交对象,从而改写 experiment 的提交历史,使它成为 master 分支的直接下游。视图如下:



rebase最大的好处是你的项目历史会非常整洁。它不像git merge 那样引入不必要的合并提交,导致看起来眼花缭乱。相反,rebase会让目历史呈现出完美的线性——你可以从项目终点到起点浏览而不需要任何的Fork。这让你更容易使用git log 、git bisect 和gitk 来查看项目历史。

不过,这种简单的提交历史会带来两个后果:安全性和可跟踪性。如果你违反了Rebase黄金法则,重写项目历史可能会给你的协作工作流带来灾难性的影响。此外,rebase不会有合并提交中附带的信息,所以你看不到feature分支中并入了上游的哪些更改。这可能不方便确认之前代码变更的背景和原因。

Rebase的黄金法则

一句话:绝不要在公共的分支上使用它。

比如说,如果你把master分支rebase到你的feature分支上会发生什么:



这次rebase将master分支上的所有提交都移到了feature分支后面。问题是它只发生在你的代码仓库中,其他所有的开发者还在原来的master上工作。因为rebase引起了新的提交,Git会认为你的master分支和其他人的master已经分叉了。

同步两个master分支的唯一办法是把它们merge到一起,导致一个额外的合并提交和两堆包含同样更改的提交。不用说,这会让人非常困惑。

总结:如果把rebase当成一种在推送之前清理提交历史的手段,而且仅仅rebase那些尚未公开的提交对象,就没问题。如果rebase那些已经公开的提交对象,并且已经有人基于这些提交对象开展了后续开发工作的话,就会出现叫人沮丧的麻烦。多人协作的项目,估计还是要继续老老实实的merge代码

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326686734&siteId=291194637