git merge和git merge --no-ff的區別 圖解易懂

在很多介紹GItFlow工作流的文章裏面,都會推薦在合併分支的時候加上--no-ff參數, 而我們在合併的時候,有時git也會提示 使用了 fast-forward, 這裏我將介紹一下merge的三種狀態及 git merge 和 git merge --no-ff 的區別

Git merge的時候,有幾種合併方式可以選擇

--ff
When the merge resolves as a fast-forward, only update the branch pointer, without creating a merge commit. This is the default behavior.

--no-ff
Create a merge commit even when the merge resolves as a fast-forward. This is the default behaviour when merging an annotated (and possibly signed) tag.

--squash
--no-squash
Produce the working tree and index state as if a real merge happened (except for the merge information), but do not actually make a commit, move the HEAD, or record $GIT_DIR/MERGE_HEAD (to cause the next git commit command to create a merge commit). This allows you to create a single commit on top of the current branch whose effect is the same as merging another branch (or more in case of an octopus).

With --no-squash perform the merge and commit the result. This option can be used to override --squash.

而我們平常什麼都不加的時候,則使用默認的 --ff , 即 fast-forward 方式

看過官方註釋後,我們用一張圖來簡單描畫一下相應的行爲

 

 

fast-forward

Git 合併兩個分支時,如果順着一個分支走下去可以到達另一個分支的話,那麼 Git 在合併兩者時,只會簡單地把指針右移,叫做“快進”(fast-forward)不過這種情況如果刪除分支,則會丟失merge分支信息。

–squash

把一些不必要commit進行壓縮,比如說,你的feature在開發的時候寫的commit很亂,那麼我們合併的時候不希望把這些歷史commit帶過來,於是使用–squash進行合併,此時文件已經同合併後一樣了,但不移動HEAD,不提交。需要進行一次額外的commit來“總結”一下,然後完成最終的合併。

–no-ff

關閉fast-forward模式,在提交的時候,會創建一個merge的commit信息,然後合併的和master分支
merge的不同行爲,向後看,其實最終都會將代碼合併到master分支,而區別僅僅只是分支上的簡潔清晰的問題,然後,向前看,也就是我們使用reset 的時候,就會發現,不同的行爲就帶來了不同的影響

 

 

上圖是使用 merge --no-ff的時候的效果,此時git reset HEAD^ --hard 的時候,整個分支會回退到 dev2-commit-2

 

 

上圖是使用 fast-forward 模式的時候,即 git merge ,這時候 git reset HEAD^ --hard,整個分支會回退到 dev1-commit-3

通常我們把 master 作爲主分支,上面存放的都是比較穩定的代碼,提交頻率也很低,而 develop 是用來開發特性的,上面會存在許多零碎的提交,快進式合併會把 develop 的提交歷史混入到 master 中,攪亂 master 的提交歷史。所以如果你根本不在意提交歷史,也不愛管 master 乾不乾淨,那麼 –no-ff 其實沒什麼用。不過,如果某一次 master 出現了問題,你需要回退到上個版本的時候,比如上例,你就會發現退一個版本到了 commint-3,而不是想要的 commit-2,因爲 feature 的歷史合併進了 master 裏。這也就是很多人都會推薦 –no-ff 的原因了吧。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章