1. 程式人生 > >Git分支合並

Git分支合並

指向 mode .cn 一次 git add lan 當我 warn file

當我們用Git協同工作時,通常是有多條分支的,例如,master,dev,feature1等。master分支是主分支,是我們最重要的分支,dev分支是開發分支,在dev分支上完成開發工作的,如果dev開發完畢了,就得用master分支去合並dev分支。這個時候就需要merge操作了。

下面就讓我們了解一個完成的開發到合並的流程。

1.建立新的分支dev,創建新文件abab.txt,提交。

$ git checkout -b dev
Switched to a new branch ‘dev‘
$ touch abab.txt
$ echo "abab" >abab.txt
$ git add .
warning: LF will be replaced by CRLF in abab.txt.
The file will have its original line endings in your working directory.

$ git commit -m "add abab.txt"
[dev d5ada67] add abab.txt
warning: LF will be replaced by CRLF in abab.txt.
The file will have its original line endings in your working directory.
 1 file changed, 1 insertion(+)
 create mode 100644 abab.txt

  2.切換到master分支,然後合並feature1分支。

$ git checkout master
Branch master set up to track remote branch master from origin.
Switched to a new branch ‘master‘

$ git merge dev
Updating 064968e..d5ada67
Fast-forward
 2.txt    | 2 +-
 abab.txt | 1 +
 2 files changed, 2 insertions(+), 1 deletion(-)
 create mode 100644 abab.txt

  可以看到合並成功了,並且使用的是Fast-forward模式的合並。

3.查看合並分支情況

$ git log --graph --pretty=oneline --abbrev-commit
* d5ada67 add abab.txt
* e416f28 add something new in 2.txt
* 064968e add dev.txt in dev

  可以看到在dev中commit -m的信息直接到master中了,從這個分支合並的圖中根本看不出是從別的分支中合並過來的,就在是在master分支中提交的一樣。這就是Fast-forward合並的情況。

4.刪除分支

$ git branch -d dev

以下用圖來表明上述整個過程。

初始狀態:在master分支下,HEAD指向最新的版本

技術分享

建立dev分支,HEAD指向dev的最新的版本

技術分享

在dev分支中提交abab.txt

技術分享

在master分支中合並dev分支

技術分享

刪除dev分支

技術分享

可以看到master分支在合並的時候,master是直接指到dev分支上去的。並沒有在自己的分支上去做一份commit。能否不采用fast-forwards合並呢?

下面來看不采用fast-forwards合並的情況。

省略建立分支dev2,創建文件nba.txt,提交的過程,直接到master中合並dev2的時候。

$ git merge --no-ff -m "merge with no-ff" dev2
Merge made by the ‘recursive‘ strategy.
 nba.txt | 1 +
 1 file changed, 1 insertion(+)
 create mode 100644 nba.txt

  使用--no-ff可以指定不使用fast-forwards方式合並。

查看合並情況。

$ git log --graph --pretty=oneline --abbrev-commit
*   21494a8 merge with no-ff
|| * db0d081 add nba
|/
* d5ada67 add abab.txt
* e416f28 add something new in 2.txt
* 064968e add dev.txt in dev

  與之前使用fast-forwards合並的情況一對比,就發現這兩種情況的不同了,no-ff的合並是能看到明顯的與其他分支合並的情況的。其他的分支進行的修改就是“add nba”。並且使用no-ff合並相當於在master合並了dev2後,又自己commit了一次。這種方法比ff好的 地方在於辦證了master主線的完整性,但是缺點就是不如ff那麽快。

以下是合並的圖解

技術分享

總結一下:1.當你的分支是有新的功能點的時候,系統合並默認是采用ff模式的。

2.可以使用--no-ff來強制不采用ff模式合並。這樣可以保證master主線的完整性。

參考:https://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000/0013758410364457b9e3d821f4244beb0fd69c61a185ae0000

https://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000/001375840038939c291467cc7c747b1810aab2fb8863508000

Git分支合並