git merge和git merge --no-ff的區別


在很多介紹GItFlow工作流的文章里面,都會推薦在合並分支的時候加上--no-ff參數, 而我們在合並的時候,

有時git也會提示 使用了 fast-forward,這里我將介紹一下merge的三種狀態及 git merge 和 git merge --no-ff

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

 1 --ff
 2 When the merge resolves as a fast-forward, only update the branch pointer, without creating a merge commit. This is the default behavior.
 4 --no-ff
 5 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.
 7 --squash
 8 --no-squash
 9 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).
11 With --no-squash perform the merge and commit the result. This option can be used to override --squash.

而我們平常什么都不加的時候,則使用默認的 --ff , 即 fast-forward 方式。看過官方注釋后,我們用一張圖來

簡單描畫一下相應的行為

 

  1. fast-forward

    Git 合並兩個分支時,如果順着一個分支走下去可以到達另一個分支的話,那么 Git 在合並兩者時,只會簡單地把指針右移,

    叫做“快進”(fast-forward)不過這種情況如果刪除分支,則會丟失merge分支信息。

  2. –squash

    把一些不必要commit進行壓縮,比如說,你的feature在開發的時候寫的commit很亂,那么我們合並的時候不希望把這些歷

    史commit帶過來,於是使用–squash進行合並,此時文件已經同合並后一樣了,但不移動HEAD,不提交。需要進行一次額

    外的commit來“總結”一下,然后完成最終的合並。

  3. –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 的原因了吧。

文章來源:https://tyloafer.github.io/posts/132/

參考文章:https://yanhaijing.com/git/2017/07/14/four-method-for-git-merge/,圖解4種git合並分支方法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM