合并代码还在用git merge吗?互联网公司都用git rebase!
你知道的越多,不知道的就越多,业余的像一棵小草!
你来,我们一起精进!你不来,我和你的竞争对手一起精进!
编辑:业余草
juejin.cn/post/7001409038307033119
推荐:https://www.xttblog.com/?p=5302
据我所知,绝大部分程序员在合并代码时使用 git merge,不少人不知道 git rebase 怎么用。当然也包括我微信群里的部分网友,基于群友的讨论。我整理了本文,希望大家喜欢。不喜欢的可以轻喷!
git merge 和 git rebase的区别
目的都是将一个分支的 commit 合并到到另外一个分支中去。
git merge
在gitlab上新建一个项目,push一个test文件上去

在本地修改test文件做两次commit,每次commit都在文件中加一句修改



在远程仓库中直接修改文件并 commit,模拟其他开发者的 commit。


4.如果此时我push本地的提交到远程,就会被拒绝,因为远程和本地已经各自有commit了,我们常规的做法是git pull一下,在本地解决冲突,然后继续push,本质上git pull = git fetch + git merge
。
产生冲突:


处理冲突:

重新走add commit 然后push,可以看到必须将合并当作一个新的commit:

git rebase
如果我们此时采用git pull --rebase,也就是=git fetch + git rebase
。
一样本地commit2次,远程commit2次


使用可以看到git pull --rebase,还是会提示我们去处理冲突,但是从git log 上可以看出明显已经发生了rebase,也就是变基,本地分支基于了远程的最新commit,而不是上次的本地commit。


处理冲突,每处理完一次本地commit冲突,用git add标记冲突已处理完,用git rebase --continue继续处理下一个本地commit,也可以先用git rebase -i将本地的commit合并为一个commit,这样git pull --rebase就能一次处理所有的冲突。

push到远程之后,在分支图可以明显看到,跟merge的区别在于,rebase不会产生分支,并且也不会产生新的提交。

总结
merge 是一个合并操作,会将两个分支的修改合并在一起,默认操作的情况下会提交合并中修改的内容。 merge 的提交历史记录了实际发生过什么,关注点在真实的提交历史上面。 rebase 并没有进行合并操作,只是提取了当前分支的修改,将其复制在了目标分支的最新提交后面。 rebase 操作会丢弃当前分支已提交的 commit,故不要在已经 push 到远程,和其他人正在协作开发的分支上执行 rebase 操作。 merge 与 rebase 都是很好的分支合并命令,没有好坏之分,使用哪一个应由团队的实际开发需求及场景决定。 如果比较关注commit时间的话,还是用git merge,rebase会打乱时间线是不可避免的。
评论