?分支的新建與合并
先引入一個實際開發的工作流:
- 開發某個網站。
- 為實現某個新的需求,創建一個分支。
- 在這個分支上開展工作。
正在此時,你突然接到一個電話說有個很嚴重的問題需要緊急修補。你將按照如下方式來處理:
- 切換到你的線上分支(production branch)。
- 為這個緊急任務新建一個分支,并在其中修復它。
- 在測試通過之后,切換到線上分支,然后合并這個修補分支,最后改動推送到線上分支。
- 切換回你最初工作的分支,繼續工作。
1. 新建分支
- 首先,模擬你正在你的項目上工作,并且在
master
分支上已經有了一些提交:
-
- 提交歷史圖:
- 提交歷史圖:
- 現在,你將解決項目中 #53 問題,需要創建一個分支并切換到該分支:
git checkout -b iss53
——(創建分支:git branch iss53
和 切換分支:git checkout iss53
的簡寫):
-
- 創建并切換后:
- 創建并切換后:
- 在新創建的分支上工作并做提交后:
git commit -a -m 'added a new footer [issue 53]'
-
- 提交
iss53
后:
- 提交
- 需要緊急修復 BUG(hotfix)時:
-
- 檢查工作目錄和暫存區是否還存在未提交的修改:
git status
- 切換回
master
分支:git checkout master
- 建立
hotfix
分支:git checkout -b hotfix
- 修復 Bug 后提交:
git commit -a -m 'fixed the Bug'
- 提交后:
- 檢查工作目錄和暫存區是否還存在未提交的修改:
- 將修改后的
hotfix
分支合并到master
分支:
-
git checkout master
:切換回master
分支。git merge hotfix
:合并hotfix
分支。- 這時會出現
Fast-forward
: 在合并時,如果一個分支是另一個分支的直接后繼,Git 會將指針直接向前推進,無需解決沖突,這種合并叫做“快進(fast-forward)”。 - 合并后,
master
被快進到hotfix
- 刪除
hotfix
:git branch -d hotfix
。 - 切換回工作分支—
iss53
分支:git checkout iss53
。 - 完成
iss53
工作后提交:git commit -a -m 'finished the new footer [issue53]'
。
-
-
- 提交
issue53
后的歷史記錄圖:
- 提交
-
2. 合并分支
模擬你已經完成了 iss53
的全部工作,并打算將其合并到 master
分支。
- 切換到
master
分支并合并iss53
:
-
- 合并前:
git checkout master
git merge iss53
- 合并后:
- 三方合并:當兩個分支的提交歷史分叉時,Git 需要做三方合并,使用兩個分支的末端快照和公共祖先來合并。與快進合并不同,Git 會創建一個新的合并提交,它有多個父提交。
- 刪除
iss53
分支:git branch -d iss53
。
- 合并前:
3. 遇到沖突時的合并分支
模擬合并時并不順利,出現了沖突:對同一個文件的同一個部分進行了不同的修改,Git 就沒法干凈的合并它們。
$ git merge iss53
Auto-merging index.html
CONFLICT (content): Merge conflict in index.html
Automatic merge failed; fix conflicts and then commit the result.
- 查看沖突:使用
git status
命令查看沖突的原因:
$ git status
On branch master
You have unmerged paths.(fix conflicts and run "git commit")Unmerged paths:(use "git add <file>..." to mark resolution)both modified: index.htmlno changes added to commit (use "git add" and/or "git commit -a")
- 解決沖突:
-
- 打開有沖突的文件,Git 會在沖突部分插入特殊標記:
<<<<<<< HEAD:index.html
<div id="footer">contact : email.support@github.com</div>
=======
<div id="footer">
please contact us at support@github.com
</div>
>>>>>>> iss53:index.html
-
- 你需要選擇保留一個版本的內容,或合并兩者的內容。解決后,刪除沖突標記(
<<<<<<<
,=======
,>>>>>>>
)。
- 你需要選擇保留一個版本的內容,或合并兩者的內容。解決后,刪除沖突標記(
- 標記沖突已解決:
-
git add
將解決后的沖突標記為已解決:git add index.hmtl
。
- 完成合并并提交:
-
git commit
完成合并并提交。- Git 會自動生成一個合并提交信息,例如:
Merge branch 'iss53'
Conflicts:index.html
- 使用圖形化工具(可選):
-
- 如果需要,可以運行 git mergetool 啟動圖形化工具來幫助解決沖突:
git mergetool
。
- 如果需要,可以運行 git mergetool 啟動圖形化工具來幫助解決沖突: