LoginSignup
154
148

More than 5 years have passed since last update.

git mergeでコンフリクトが発生するか前もって調べる方法

Posted at

利用シーン少なそうですが、mergeを実行する前にコンフリクトが起こるかどうかチェックしたくて調べたのでメモ。

git merge —no-commit

topic-branchをmasterにマージしようとしてコンフリクトするケースを想定します。

まず試してみたのは--no-commitオプション。

—no-commit付きでmerge
 (master) ✘ git merge topic-branch --no-commit
Auto-merging src/hello.py
CONFLICT (content): Merge conflict in src/hello.py
Automatic merge failed; fix conflicts and then commit the result.

これを付けておくとマージ時に自動コミットがされなくなりますが、コンフリクトが起こる場合もローカルファイルにはマージが実行されてしまいます。

git format-patch

予めパッチを用意しておくと、マージを適用する前にコンフリクトするかどうかをチェックすることができるようです。

バッチ作成
(topic-branch) ✘ git format-patch master  --stdout > test.patch #パッチ作成
(topic-branch) ✘ git checkout - 
Switched to branch 'master'
(master) ✘ git apply test.patch --check #パッチが適用できるかチェック
error: patch failed: src/hello.py:6
error: src/hello.py: patch does not apply

コンフリクトが起こる場合はエラーが発生するので未然に気づけるように。これならファイルに変更が加わってgit merge —abortする必要もなし。

毎回この手順を踏むのは面倒なのでコマンド一行でチェックできるようにします。

直前のbranchを現在のbranchにマージできるかチェックする
git format-patch `git rev-parse --abbrev-ref HEAD`..`git rev-parse --abbrev-ref @{-1}` --stdout | git apply --check

カレントブランチ(git rev-parse --abbrev-ref HEAD)と直前にcheckoutしていたbranch(git rev-parse --abbrev-ref @{-1})間での差分を出力して、パッチが適用できるかチェックしています。

hookとかに入れておけば、マージ先ブランチをcheckoutするタイミングでコンフリクトが発生するかチェックできて便利そう。

154
148
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
154
148