Git-Rebase变基的应用
使用 Git 已经好几年了,却始终只是熟悉一些常用的操作。对于 Git Rebase 却很少用到,知道需要进行一些特殊操作,不得不用到git rebase,用过之后发现真的很好用。
一、合并多个commit提交
最近换公司,在git管理中,要求把dev自己的开发分支多个commit,合并成一个commit,之前从来没有这种操作啊,经过了解,原来是通过git rebase实现的
比如我们在自己的开发分支进行了多次提交,现在我们要合并最近的几次
git rebase -i HEAD~4 //合并几个就写几
或者
git rebase -i [commitId]
2.这时候,会自动进入 vi 编辑模式:
pick cacc52da add: qrcode pick f072ef48 update: indexeddb hack pick 4e84901a feat: add indexedDB floder pick 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. #
把除了第一个pick(执行当前commit),全部改为s(合并到上一个commit),按照如上命令来修改你的提交纪录
注意不要合并先前提交的东西,也就是已经提交远程分支的纪录,否则保存的时候,会这个错误:
error: cannot 'squash' without a previous commit
4.如果你异常退出了 vi 窗口,不要紧张:
git rebase --edit-todo
这时候会一直处在这个编辑的模式里,我们可以回去继续编辑,修改完保存一下:
git rebase --continue
5.查看结果
git log
6.合并提交
//切换到主分支 git cherry-pick [commitId]
三次提交合并成了一次,减少了无用的提交信息。
二、分支合并
我们先从 master 分支切出一个 dev 分支,进行开发:
git:(master) git checkout -b feature1
这时候,你的同事完成了一次 hotfix,并合并入了 master 分支,此时 master 已经领先于你的 feature1 分支了,我们想要同步 master 分支的改动,首先想到了 merge,执行:
git:(feature1) git merge master
就会在记录里发现一些 merge 的信息,但是我们觉得这样污染了 commit 记录,想要保持一份干净的 commit,git rebase 就派上用场了。
使用 rebase 后来看看结果:
git:(feature1) git rebase master
这里补充一点:rebase 做了什么操作呢?
首先,git 会把 feature1 分支里面的每个 commit 取消掉;
其次,把上面的操作临时保存成 patch 文件,存在 .git/rebase 目录下;
然后,把 feature1 分支更新到最新的 master 分支;
最后,把上面保存的 patch 文件应用到 feature1 分支上;
从 commit 记录我们可以看出来,feature1 分支是基于 hotfix 合并后的 master ,自然而然的成为了最领先的分支,而且没有 merge 的 commit 记录,是不是感觉很舒服了。
在 rebase 的过程中,也许会出现冲突 conflict。在这种情况,git 会停止 rebase 并会让你去解决冲突。在解决完冲突后,用 git add 命令去更新这些内容。
注意,你无需执行 git-commit,只要执行 continue
git rebase --continue
在任何时候,我们都可以用 --abort 参数来终止 rebase 的行动,并且分支会回到 rebase 开始前的状态。这样 git 会继续应用余下的 patch 补丁文件。
git rebase —abort
三、更多 Rebase 的使用场景
git-rebase 存在的价值是:对一个分支做「变基」操作。
1.当我们在一个过时的分支上面开发的时候,执行 rebase 以此同步 master 分支最新变动;
2.假如我们要启动一个放置了很久的并行工作,现在有时间来继续这件事情,很显然这个分支已经落后了。这时候需要在最新的基准上面开始工作,所以 rebase 是最合适的选择。
四、注意?
只要你的分支上需要 rebase 的所有 commits 历史还没有被 push 过,就可以安全地使用 git-rebase来操作。
浙公网安备 33010602011771号