背景
開(kāi)發(fā)過(guò)程中可能有多個(gè)commit,直接合并到master分支會(huì)讓master分支的git log看起來(lái)非常錯(cuò)亂。有一種做法就是在合并到master分支之前,在自己開(kāi)發(fā)分支上將多次提交的commit合并成一個(gè)。
git squash
第一步:新建一個(gè)等待合并到master的squash分支
project-name git:(dev-branch) git checkout master
project-name git:(master) git checkout -b squash-branch
第二步:將dev分支合并到squash分支中并提交
project-name git:(squash-branch) git merge --squash dev-branch
project-name git:(squash-branch) git add .
project-name git:(squash-branch) git commit -m 'xxx'
project-name git:(squash-branch) git push
此時(shí)不論dev-branch中有多少個(gè)commit,squash-branch中都只有一個(gè)commit
第三步:在gitlab上提MR給項(xiàng)目owner,
project-name git:(squash-branch) git checkout master
project-name git:(master) git merge --no-ff squash-branch
此時(shí)master分支上合并進(jìn)來(lái)的也只有一個(gè)commit
git rebase
俗稱變基操作,實(shí)際操作中,若是多人協(xié)作開(kāi)發(fā),則有可能會(huì)發(fā)生沖突。
第一步:git log查看一下歷史

比如這次開(kāi)發(fā)commit了三次,現(xiàn)在要合并和三個(gè)commit,先找到第一次提交commit的hash:
d1a5ec....................
第二步:git rebase - i d1a5ec................

此時(shí)可以看到三次提交的commit信息,第二個(gè)紅框標(biāo)注的是接下來(lái)要用的命令
第三步:將所有的pick換為s,然后wq保存
注意:d(drop)會(huì)丟棄commit!??!操作要非常小心??!

第四步:這里展示了所有的commit信息,手動(dòng)刪除你不想要的。

只留自己想提交的信息

第五步:git push -f 強(qiáng)制推送 -f必須要
第六步:git log命令查看是否生效
自己去試吧~
番外:
git rebase -i --root 可改變master的第一個(gè)commit
遇到不能刪分支的情況,先切換到master分支,再用-D刪除
$ git checkout master
$ git branch -d Test_Branch
If above command gives you error - The branch 'Test_Branch' is not fully merged. If you are sure you want to delete it and still you want to delete it, then you can force delete it using -D instead of -d, as:
$ git branch -D Test_Branch
To delete Test_Branch from remote as well, execute:
git push origin --delete Test_Branch
對(duì)于已經(jīng)提交上去的commit,可通過(guò)amend去修改,覆蓋最后一次commit
git commit --amend -m "New commit message"
git push -f // 強(qiáng)制提交