【Git】ローカルでコンフリクトを解決してみる

初めに

Gitでコンフリクトが発生した場合の解決方法を調べ、実際に試してみました。

コンフリクトが起きる状況とは?

If you changed the same part of the same file differently in the two branches you’re merging, Git won’t be able to merge them cleanly.

引用:https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging#_basic_merge_conflicts

リファレンスを確認したところ、コンフリクトは、 2つのブランチで同じファイルの同じ箇所に変更をマージしようとする時に起きるようです。

コンフリクトの解決を実践してみる

1.準備

developブランチにファイルを作成し、 作業ブランチをブランチを2つ作ります。

1.1.ファイルを作成
(wether.textファイルを作成しています。)

//wether.text
明日の天気は"晴れ"です!!

1.2.developブランチから、feature/wether1ブランチと、feature/wether2ブランチを切ります。

$git branch
  develop
  feature/wether1
  feature/wether2

2作業ブランチでファイルを編集する

2.1.feature/wether1ブランチを編集
(天気を"曇り"に編集しています。)

//wether.text
明日の天気は"曇り"です!!

2.2.feature/wether2ブランチ
(天気を"雨"に編集しています。)

//wether.text
明日の天気は"雨"です!!

3.マージ

developブランチに、feature/wether1とfeature/wether2をマージする。
3.1.developブランチに、feature/wether1をマージ

//ターミナル
$git merge feature/wether1
//wether.text
明日の天気は"曇り"です!!

3.2.developブランチに、feature/wether2をマージ

//ターミナル
$git merge feature/wether2
Auto-merging wether.text
CONFLICT (content): Merge conflict in develop.text
Automatic merge failed; fix conflicts and then commit the result.
//wether.text
<<<<<<< HEAD
明日の天気は"曇り"です!!
=======
明日の天気は"雨"です!!
>>>>>>> feature/wether2

上記のようにコンフリクトが起こります。

4.コンフリクトを解決

コンフリクトした箇所を反映したい形に修正しコミットします。
4.1.wether.textを修正

//wether.text
明日の天気は"雨"です!!

4.2.ステージングに追加

//ターミナル
$git add wether.text
$git status
On branch develop
All conflicts fixed but you are still merging.
 (use "git commit" to conclude merge)

修正をアドしてからステータスを確認すると、 コンフリクトが解決されていることがわかります。 ここまできたら、コミットして完了です。

4.3.コミット

//ターミナル
$git commit -m "コンフリクトを修正"

//最後にステータスを確認してみます
$git status
On branch develop
nothing to commit, working tree clean

最後に

今回は、ローカルでコンフリクトを起こし解決しました。 次はリモートリポジトリで起こったコンフリクトの解決方法や、ブランチ戦略についても調べたり、学んでいきたいと思っています。

参考