miyohideの日記

技術的なメモなどを記しています

2019年2月22日(金)

今日は打ち合わせもないし、じっくりとドキュメントを読んだりコード書いたりするぞ!って思っていたのに色々とトラブルが...

git checkout ours/theirs

今までGitでconflictした場合ちまちまと手で直していたんですが、「自分のもので上書きしたい」とか「リモートに上がっているもので上書きしたい」という場合にはgit checkout --oursgit checkout --theirsが使えるよということを知りました。きっかけは以下のQiitaの記事。

qiita.com

自分でもやってみました。

まずは、準備。2つのブランチで同じファイルを編集・コミットしておく。

$ mkdir git_checkout_test
$ cd git_checkout_test/
$ git init
Initialized empty Git repository in /Users/miyohide/work/tmp/git_checkout_test/.git/
$ git commit --allow-empty -m "initial commit"
[master (root-commit) f46fa43] initial commit
$ touch file
$ git add .
$ git commit -m "add file"
[master 1b32c4a] add file
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 file
$ git checkout -b a_branch
Switched to a new branch 'a_branch'
$ echo "a branch 1" >> file
$ git commit -a -m "a branch commit 1"
[a_branch aea8c0c] a branch commit 1
 1 file changed, 1 insertion(+)
$ echo "a branch 2" >> file
$ git commit -a -m "a branch commit 2"
[a_branch 76fb789] a branch commit 2
 1 file changed, 1 insertion(+)
$ echo "a branch 3" >> file
$ git commit -a -m "a branch commit 3"
[a_branch 1321b44] a branch commit 3
 1 file changed, 1 insertion(+)
$git checkout -b b_branch master
Switched to a new branch 'b_branch'
$ echo "b branch 1" >> file
$ git commit -a -m "b branch commit 1"
[b_branch ec7500b] b branch commit 1
 1 file changed, 1 insertion(+)
$ echo "b branch 2" >> file
$ git commit -a -m "b branch commit 2"
[b_branch 7242dbc] b branch commit 2
 1 file changed, 1 insertion(+)
$ echo "b branch 3" >> file
$ git commit -a -m "b branch commit 3"
[b_branch 96e1d8a] b branch commit 3
 1 file changed, 1 insertion(+)
$ git checkout master
Switched to branch 'master'
$ git log --graph --all --format="%x09%x09%h %d %s"
*               96e1d8a  (b_branch) b branch commit 3
*               7242dbc  b branch commit 2
*               ec7500b  b branch commit 1
| *             1321b44  (a_branch) a branch commit 3
| *             76fb789  a branch commit 2
| *             aea8c0c  a branch commit 1
|/
*               1b32c4a  (HEAD -> master) add file
*               f46fa43  initial commit
$

ここでa_branchb_branchのものをmergeしようとするとconflictを起こします。

$ git checkout a_branch
Switched to branch 'a_branch'
$ git merge b_branch
Auto-merging file
CONFLICT (content): Merge conflict in file
Automatic merge failed; fix conflicts and then commit the result.
$ cat file
<<<<<<< HEAD
a branch 1
a branch 2
a branch 3
=======
b branch 1
b branch 2
b branch 3
>>>>>>> b_branch
$

ここで今回学んだこと。git checkout --oursを使うと、自分たちのもの、つまりa_branchのものが採用されます。

$ git checkout --ours file
$ cat file
a branch 1
a branch 2
a branch 3
$

一方、git checkout --theirsを使うと、他方の、つまりb_branchのものが採用されます。

$ git checkout --theirs file
$ cat file
b branch 1
b branch 2
b branch 3
$