LoginSignup
22
21

More than 5 years have passed since last update.

Gitの基礎 競合の解決

Last updated at Posted at 2018-03-03

競合の解決

マージをしてると競合が発生しできない時があります。
競合が起きるのは以下のような場合です。

  • masterでtest.txtを編集しコミット
  • 他ブランチでtest.txtの同一の箇所を編集しコミット
  • masterからマージ

このような場合はどっちのコミットを優先し残すかわからないためマージができません。
実際に競合を起こして見ましょう

$ git log --graph --oneline --all
* 4060b6b (testBranch) edit test
| * b728329 (HEAD -> master) edit test
|/  
* 29a0d87 wite branch
* 8b01a71 first commit
$ git merge testBranch
Auto-merging test
CONFLICT (content): Merge conflict in test
Automatic merge failed; fix conflicts and then commit the result.

競合が起きましたどこで競合の解決の仕方は以下の流れになります

  1. 競合したファイルの確認 git status git diff
  2. 競合したファイルの修正 gitcheckout --ours or gitcheckout --theirs (file)
  3. コミット git commit

競合したファイルの確認

まずどこのファイルで競合しているかをgit statusで確認しましょう

$ git status
On branch master
You have unmerged paths.
  (fix conflicts and run "git commit")
  (use "git merge --abort" to abort the merge)

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

    both modified:   test

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

$ more test 
<<<<<<< HEAD
test braaaaaaaaaaaagraph
=======
test bfffffffffffngh
>>>>>>> testBranch
hoge

<<<<<<< HEADで書かれているのがHEADの内容(今回はmaster)
>>>>>>> testBranchで書かれているのがマージ先での内容です

見にくい時は
git diff HEADで最終コミットとの差分を
git diff MERGE_HEADでマージ先との差分を
git diff --baseでマージの起点との差分が見れます

競合したファイルの修正

競合の解決はエディタ(emacs)で編集して直してもいいですが
どっちのブランチを優先するかわかっている時は'git checkout'を使いましょう。

  • git checkout --ours "ファイル名"で現在のブランチを
  • git checkout --theirs "ファイル名"でマージ先のブランチを

優先します。
今回はmasterを優先して見ましょう

bash-3.2$ git checkout --ours test
bash-3.2$ more test 
test braaaaaaaaaaaagraph
hoge

testファイルがmasterの方になったのがわかります。

コミット

最後にコミットを行ってマージは完了です

$ git add test
$ git commit -m "merge"
[master addfe61] merge
bash-3.2$ git log --oneline --all
addfe61 (HEAD -> master) merge
4060b6b (testBranch) edit test
b728329 edit test
29a0d87 wite branch
8b01a71 first commit

おわりに

競合の解決は意外と簡単なものです
競合が起きた時にこの記事を思い出してくれると幸いです

22
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
21