Git - 合併衝突



在 Git 中合併分支

合併是將一個分支的更改整合到另一個分支的過程。在單獨的分支上開發功能或修復錯誤後,通常會將該分支合併回主分支,以將這些更改包含在主程式碼庫中。

處理合併衝突

分支合併並不總是按計劃進行。如果 **auth-module** 分支和 **bugfix** 分支都對同一檔案的同一部分進行了不同的編輯,則 Git 會遇到合併衝突。

這就是它的表現方式

$ git merge auth-module
Auto-merging index.html
CONFLICT (content): Merge conflict in index.html
Automatic merge failed; fix conflicts and then commit the result.

Git 報告 `index.html` 檔案中的衝突並停止合併過程。

它等待我們手動解決衝突,透過編輯檔案而不是自動建立新的合併提交。

我們可以使用 **git status** 檢視哪些檔案存在衝突

$ git status
On branch master
You have unmerged paths.
  (fix conflicts and run "git commit")

Unmerged paths:
  (use "git add ..." to mark resolution)

    both modified:      index.html

no changes added to commit (use "git add" and/or "git commit -a")

當 Git 在合併期間發現衝突的更改時,它會將受影響的檔案標記為未合併,並在檔案中新增衝突標記以識別衝突的部分。

`index.html` 中的衝突部分可能如下所示

<<<<<<< HEAD:index.html
<header>
  <h1>Welcome to our Website</h1>
</header>
=======
<header>
  <h1>Welcome to the Best Website</h1>
</header>
 >>>>>>> feature/update-header:index.html

在上面的示例中

  • 衝突表明 `index.html` 標題部分中的 <h1> 標籤已被 feature/update-header 分支和 master 分支 (**HEAD**) 不一致地修改。

  • 我們必須手動編輯檔案以決定保留哪些更改以及如何合併它們,以解決此衝突。

  • 例如,我們可以選擇透過修改 `index.html` 以包含這兩個概念來合併修改。

<header>
  <h1>Welcome to our Website</h1>
</header>

在解決 `index.html` 中的衝突後,我們應該從檔案中刪除衝突標記 (**\\\<<<\, =======, 和 >>>>>>**)。

接下來,使用 **git add** 暫存檔案並將其標記為已解決在 Git 中。

$ git add index.html

在所有衝突檔案都已暫存後,接下來提交合並。

$ git commit

如果我們更願意使用圖形工具,可以使用 **git mergetool** 啟動一個可視化合並工具,以幫助解決衝突。

$ git mergetool
This message is displayed because 'merge.tool' is not configured.
See 'git mergetool --tool-help' or 'git help config' for more details.
'git mergetool' will now attempt to use one of the following tools:
opendiff kdiff3 tkdiff xxdiff meld tortoisemerge gvimdiff diffuse diffmerge ecmerge p4merge araxis bc3 codecompare vimdiff emerge
Merging:
index.html

Normal merge conflict for 'index.html':
  {local}: modified file
  {remote}: modified file
Hit return to start merge resolution tool (opendiff):
  • 一旦我們使用指定的工具解決衝突並關閉視窗,Git 會要求我們驗證合併是否成功。

  • 如果收到確認,Git 會自動暫存已解決的檔案並將其標記為已解決。

  • 透過再次執行 git status,我們可以確認衝突的狀態。

$ git status
On branch master
All conflicts fixed but you are still merging.
  (use "git commit" to conclude merge)

Changes to be committed:

    modified:   index.html

一旦確保所有衝突都已處理並暫存,使用 **git commit** 將完成合並提交。

通常,預設提交訊息類似於以下內容

    Merge branch 'feature/auth-module'

Conflicts:
    index.html

# It seems like you're committing a merge.
# If this isn't correct, please remove the file
# .git/MERGE_HEAD and try again.

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
# On branch master
# All conflicts fixed but you are still merging.
#
# Changes to be committed:
#   modified:   index.html
廣告

© . All rights reserved.