使用 Git 已经好几年了,却始终只是熟悉一些经常使用的操做。对于 Git Rebase 却不多用到,直到这一次,不得不用。html
上线构建的过程当中扫了一眼代码变动,忽然发现, commit
提交居然多达 62
次。咱们来看看都提交了什么东西:git
这里咱们先不说 git
提交规范,就单纯这么屡次无用的 commit
就很让人不舒服。可能不少人以为无所谓,无非是多了一些提交纪录。shell
然而,并不是如此,你可能听过破窗效应,编程也是如此!编程
1.不利于代码 review
设想一下,你要作 code review
,结果一个很小的功能,提交了 60
屡次,会不会有一些崩溃?网络
2.会形成分支污染框架
你的项目充满了无用的 commit
纪录,若是有一天线上出现了紧急问题,你须要回滚代码,却发现海量的 commit
须要一条条来看。tcp
遵循项目规范才能提升团队协做效率,而不是为所欲为。学习
基于上面所说问题,咱们不难想到:每一次功能开发, 对多个 commit 进行合并处理。this
这时候就须要用到 git rebase
了。这个命令没有太难,不经常使用可能源于不熟悉,因此咱们来经过示例学习一下。spa
1.咱们来合并最近的 4 次提交纪录,执行:
git rebase -i HEAD~4
2.这时候,会自动进入 vi
编辑模式:
s cacc52da add: qrcode s f072ef48 update: indexeddb hack s 4e84901a feat: add indexedDB floder s 8f33126c feat: add test2.js # Rebase 5f2452b2..8f33126c onto 5f2452b2 (4 commands) # # Commands: # p, pick = use commit # r, reword = use commit, but edit the commit message # e, edit = use commit, but stop for amending # s, squash = use commit, but meld into previous commit # f, fixup = like "squash", but discard this commit's log message # x, exec = run command (the rest of the line) using shell # d, drop = remove commit # # These lines can be re-ordered; they are executed from top to bottom. # # If you remove a line here THAT COMMIT WILL BE LOST. # # However, if you remove everything, the rebase will be aborted. #
有几个命令须要注意一下:
按照如上命令来修改你的提交纪录:
s cacc52da add: qrcode s f072ef48 update: indexeddb hack s 4e84901a feat: add indexedDB floder p 8f33126c feat: add test2.js
3.若是保存的时候,你碰到了这个错误:
error: cannot 'squash' without a previous commit
注意不要合并先前提交的东西,也就是已经提交远程分支的纪录。
4.若是你异常退出了 vi
窗口,没关系张:
git rebase --edit-todo
这时候会一直处在这个编辑的模式里,咱们能够回去继续编辑,修改完保存一下:
git rebase --continue
5.查看结果
git log
三次提交合并成了一次,减小了无用的提交信息。
1.咱们先从 master
分支切出一个 dev
分支,进行开发:
git:(master) git checkout -b feature1
2.这时候,你的同事完成了一次 hotfix
,并合并入了 master
分支,此时 master
已经领先于你的 feature1
分支了:
3.恰巧,咱们想要同步 master
分支的改动,首先想到了 merge
,执行:
git:(feature1) git merge master
图中绿色的点就是咱们合并以后的结果,执行:
git:(feature1) git log
就会在记录里发现一些 merge
的信息,可是咱们以为这样污染了 commit
记录,想要保持一份干净的 commit
,怎么办呢?这时候, git rebase
就派上用场了。
4.让咱们来试试 git rebase
,先回退到同事 hotfix
后合并 master
的步骤:
5.使用 rebase
后来看看结果:
git:(feature1) git rebase master
这里补充一点: rebase
作了什么操做呢?
首先, git
会把 feature1
分支里面的每一个 commit
取消掉;
其次,把上面的操做临时保存成 patch
文件,存在 .git/rebase
目录下;
而后,把 feature1
分支更新到最新的 master
分支;
最后,把上面保存的 patch
文件应用到 feature1
分支上;
从 commit
记录咱们能够看出来, feature1
分支是基于 hotfix
合并后的 master
,天然而然的成为了最领先的分支,并且没有 merge
的 commit
记录,是否是感受很舒服了。
6.在 rebase
的过程当中,也许会出现冲突 conflict
。在这种状况, git
会中止 rebase
并会让你去解决冲突。在解决完冲突后,用 git add
命令去更新这些内容。
注意,你无需执行 git-commit,只要执行 continue
git rebase --continue
这样 git
会继续应用余下的 patch
补丁文件。
7.在任什么时候候,咱们均可以用 --abort
参数来终止 rebase
的行动,而且分支会回到 rebase
开始前的状态。
git rebase —abort
以上就是本文的所有内容,但愿本文的内容对你们的学习或者工做能带来必定的帮助,也但愿你们多多支持 码农网