Subject: [PATCH] mergetool: add an option for writing to a temporary directory

From: David Aguilar <[email-masked]>
Date: Sat, 11 Oct 2014 10:04:45 -0700

Teach mergetool to write files in a temporary directory when
'mergetool.writeToTemp' is true.

This is helpful for tools such as Eclipse which cannot cope with
multiple copies of the same file in the worktree.

Suggested-by: Charles Bailey <[email-masked]>
Signed-off-by: David Aguilar <[email-masked]>
---
This patch is dependent on my previous mergetool patches:
"use more conservative temporary..." and the subsequent --tool-help
series.

 Documentation/config.txt |  6 ++++++
 git-mergetool.sh         | 35 +++++++++++++++++++++++++++++++----
 2 files changed, 37 insertions(+), 4 deletions(-)

diff --git a/Documentation/config.txt b/Documentation/config.txt
index 04a1e2f..be6cf35 100644
--- a/Documentation/config.txt
+++ b/Documentation/config.txt
@@ -1768,6 +1768,12 @@ mergetool.keepTemporaries::
 	preserved, otherwise they will be removed after the tool has
 	exited. Defaults to `false`.
 
+mergetool.writeToTemp::
+	Git writes temporary 'BASE', 'LOCAL', and 'REMOTE' versions of
+	conflicting files in the worktree by default.  Git will attempt
+	to use a temporary directory for these files when set `true`.
+	Defaults to `false`.
+
 mergetool.prompt::
 	Prompt before each invocation of the merge resolution program.
 
diff --git a/git-mergetool.sh b/git-mergetool.sh
index 10782b8..2b788c5 100755
--- a/git-mergetool.sh
+++ b/git-mergetool.sh
@@ -37,6 +37,19 @@ base_present () {
 	test -n "$base_mode"
 }
 
+mergetool_tmpdir_init () {
+	if test "$(git config --bool mergetool.writeToTemp)" != true
+	then
+		MERGETOOL_TMPDIR=.
+		return 0
+	fi
+	if MERGETOOL_TMPDIR=$(mktemp -d -t "git-mergetool-XXXXXX" 2>/dev/null)
+	then
+		return 0
+	fi
+	die "error: mktemp is needed when 'mergetool.writeToTemp' is true"
+}
+
 cleanup_temp_files () {
 	if test "$1" = --save-backup
 	then
@@ -46,6 +59,10 @@ cleanup_temp_files () {
 	else
 		rm -f -- "$LOCAL" "$REMOTE" "$BASE" "$BACKUP"
 	fi
+	if test "$MERGETOOL_TMPDIR" != "."
+	then
+		rmdir "$MERGETOOL_TMPDIR"
+	fi
 }
 
 describe_file () {
@@ -235,10 +252,20 @@ merge_file () {
 		BASE=$MERGED
 		ext=
 	fi
-	BACKUP="./${BASE}_BACKUP_$$$ext"
-	LOCAL="./${BASE}_LOCAL_$$$ext"
-	REMOTE="./${BASE}_REMOTE_$$$ext"
-	BASE="./${BASE}_BASE_$$$ext"
+
+	mergetool_tmpdir_init
+
+	if test "$MERGETOOL_TMPDIR" != "."
+	then
+		# If we're using a temporary directory then write to the
+		# top-level of that directory.
+		BASE=${BASE##*/}
+	fi
+
+	BACKUP="$MERGETOOL_TMPDIR/${BASE}_BACKUP_$$$ext"
+	LOCAL="$MERGETOOL_TMPDIR/${BASE}_LOCAL_$$$ext"
+	REMOTE="$MERGETOOL_TMPDIR/${BASE}_REMOTE_$$$ext"
+	BASE="$MERGETOOL_TMPDIR/${BASE}_BASE_$$$ext"
 
 	base_mode=$(git ls-files -u -- "$MERGED" | awk '{if ($3==1) print $1;}')
 	local_mode=$(git ls-files -u -- "$MERGED" | awk '{if ($3==2) print $1;}')
-- 
2.1.2.379.gc4e1e0c