非エンジニアでも知らないとヤバイGit Part3

はじめに

今回は競合の解決について説明する。
前回までの記事はこちら
非エンジニアでも知らないとヤバイGit Part1
非エンジニアでも知らないとヤバイGit Part2

競合の発生

リモートリポジトリとローカルリポジトリで同じ箇所を変更していた場合に競合が発生する。
このような場合はどちらの変更を採用するかを自動的に判断することができないためにエラーが発生する。

競合を作る

同じリモートリポジトリを共有している2人のユーザー、User1とUser2を用意する。
まずはUser1でindex.phpにコードを追加する。

画像
Gitを簡単に使用できるGUI、SourceTreeでコミット・プッシュを行う。(コミットメッセージ:おはようございます。を追加)

画像
次に、User1が追加したものと異なるコードを、User2で同じ箇所に追加する。

画像
準備ができたのでターミナルからGitの操作をする。
まず、変更したファイルをステージングに追加する。
[sql]
git add (ファイル名)
git add index.php
[/sql]
次にコミットメッセージを入力してコミットする。
[sql]
git commit -m ‘コミットメッセージ’
git commit -m ‘Good Morning!を追加’
[/sql]
この状態でプッシュするとこのようなエラーが発生する。
[sql]git push[/sql]
[sql]
To https://bitbucket.org/username/test.git
! [rejected] master -> master (fetch first)
error: failed to push some refs to ‘https://username@bitbucket.org/username/test.git’
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., ‘git pull …’) before pushing again.
hint: See the ‘Note about fast-forwards’ in ‘git push –help’ for details.
[/sql]
これで競合が発生した。

競合の解決

他のユーザーがプッシュしたものがあると書かれているので、まずはプルする。
[sql]git pull[/sql]
[sql]
remote: Counting objects: 3, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (3/3), done.
From https://bitbucket.org/username/test
4754cf1..f75253f master -> origin/master
Auto-merging index.php
CONFLICT (content): Merge conflict in index.php
Automatic merge failed; fix conflicts and then commit the result.
[/sql]
index.phpで競合が発生してると書かれている。
エディターで競合しているファイルを開くと競合箇所が表示されている。

画像
今回はUser2の変更内容で競合を解決する。
ピンク色のUse meボタンを押して、競合を解決し再び対象のファイルをステージングに追加し、コミットメッセージに競合解決したことがわかるようにメッセージを入力し、プッシュする。
[sql]
git add index.php
git commit -m ‘競合を解決’
git push
[/sql]
User1のSourceTreeでプルをして変更を確認。

画像
User1のローカルリポジトリのindex.php

画像

最後に

今回は競合について説明した。
次回はSourceTreeについて説明する。

関連記事