Can git tell me if a merge will conflict without actually merging? [duplicate]
Solution 1:
As noted previously, pass in the --no-commit
flag, but to avoid a fast-forward commit, also pass in --no-ff
, like so:
$ git merge --no-commit --no-ff $BRANCH
To examine the staged changes:
$ git diff --cached
And you can undo the merge, even if it is a fast-forward merge:
$ git merge --abort
Solution 2:
I just had to implement a method that automatically finds conflicts between a repository and its remote. This solution does the merge in memory so it won't touch the index, nor the working tree. I think this is the safest possible way you can solve this problem. Here's how it works:
- Fetch the remote to your repository. For example:
git fetch origin master
- Run git merge-base:
git merge-base FETCH_HEAD master
- Run git merge-tree:
git merge-tree mergebase master FETCH_HEAD
(mergebase is the hexadecimal id that merge-base printed in the previous step)
Now suppose that you want to merge the remote master with your local master, but you can use any branches. git merge-tree
will execute the merge in memory and print the result to the standard output. Grep for the pattern <<
or >>
. Or you can print the output to a file and check that. If you find a line starting with 'changed in both' then most probably there will be a conflict.
Solution 3:
I'm assuming you just want to find out how much trouble you're getting yourself into prior to actually attempting the merge...and resetting to the last commit after a failed merge is relatively easy so I wouldn't be surprised if that is the intended approach.
That said, if you really don't want to touch your existing files in the working tree - you could create a patch and test it against the target branch. This also has the benefit of showing exactly what changes were made to which files - just open up the patch file in a text editor.
git checkout -b mycrazybranch
[change some stuff...]
git add .
git commit -m "changed some stuff"
git format-patch master --stdout > crazy.patch
git checkout master
git apply crazy.patch --check
[all good! cleanup...]
rm crazy.patch
As you can see, this will create a patch file, you can then test it with --check and see if there are any errors, then remove the patch file.
Solution 4:
You can do git merge --abort
after seeing that there are conflicts.
Solution 5:
As a summary of existed answers, there are two way to check if there would be merge conflicts
git format-patch $(git merge-base branch1 branch2)..branch2 --stdout | git apply --3way --check -
Note, your current branch should be branch1
when you run above command
Another way:
git merge --no-commit branch2
# check the return code here
git merge --abort