Subject: Re: How to automatically correct an almost correct auto-merge?

From: SZEDER Gábor <[email-masked]>
Date: Sat, 17 Dec 2011 12:07:06 +0100

On Fri, Dec 16, 2011 at 03:39:27PM -0500, Seth Robertson wrote:
> 
> > How can I teach git to produce the correct merge result when
> > performing the same merge later on?
> 
> Custom merge driver.
> 
> Type `man gitattributes` and search for "custom merge driver"
> 
> Your merge driver can have whatever policy you can program, on a per
> file basis.

Thanks for the pointer, I knew it must be possible with git somehow.

For future reference, here's what I did to handle the minimal receipe
posted in my earlier email:

I stored the diff between the original and semantically almost correct
merge result and the fixed version in the file "patch", then put
together the little script below and configured it as custom merge
driver for the file "file", as described in the documentation.  The
script uses 'git merge-file' to perform the real merge, and then
applies the fixup patch (after rewriting the paths, because during the
merge the patch should be applied to the current file the merge driver
is working with instead of the original "file").  Of course, "file"
might be modified by other merges before or after the problematic
merge, but the fixup patch should not be applied in those cases.  The
two greps and the conditions make sure that the patch is applied only
if both "code blocks" are in the file and they are in the wrong order.

Unfortunately, applying a patch is more sensitive to matching context,
so it will fail easily when there are other changes in the
neighborhood, but at least it will fail loudly, and then I'll know I
have to fix it up manually.  We'll see, how it will cope with real
source code.

Thanks,
Gábor

#!/bin/sh

f="file"

git merge-file "$1" "$2" "$3"

a_line="$(grep -n '^a$' "$1" |cut -d: -f1)"
c_line="$(grep -n '^c$' "$1" |cut -d: -f1)"

if [ -n "$a_line" -a -n "$c_line" ] && [ "$c_line" -lt "$a_line" ]; then 
	echo "Fixing incorrect auto-merge result of '$f'"
	sed -e "s%^diff --git a/$f b/$f%diff --git a/$1 b/$1%" \
		-e "s%^--- a/$f%--- a/$1%" \
		-e "s%^+++ b/$f%+++ b/$1%" patch \
		|git apply
fi