使用 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
以上就是本文的所有內容,但願本文的內容對你們的學習或者工做能帶來必定的幫助,也但願你們多多支持 碼農網