Subject: [PATCH] contrib/subtree: Split history with empty trees correctly (was: Re: BUG: git subtree split gets confused on removed and readded directory)

From: Marcus Brinkmann <[email-masked]>
Date: Wed, 20 Jan 2016 02:17:58 +0100

'git subtree split' will fail if the history of the subtree has empty
tree commits (or trees that are considered empty, such as submodules).
This fix keeps track of this condition and correctly follows the history
over such commits.

Signed-off-by: Marcus Brinkmann <[email-masked]>
---
 contrib/subtree/git-subtree.sh | 20 ++++++++++++++------
 1 file changed, 14 insertions(+), 6 deletions(-)

diff --git a/contrib/subtree/git-subtree.sh b/contrib/subtree/git-subtree.sh
index edf36f8..b68828b 100755
--- a/contrib/subtree/git-subtree.sh
+++ b/contrib/subtree/git-subtree.sh
@@ -36,6 +36,8 @@ PATH=$PATH:$(git --exec-path)

 require_work_tree

+EMPTY_TREE=`git hash-object -t tree /dev/null`
+
 quiet=
 branch=
 debug=
@@ -449,7 +451,8 @@ copy_or_skip()
 	rev="$1"
 	tree="$2"
 	newparents="$3"
-	assert [ -n "$tree" ]
+
+	[ -z "$tree" ] && tree=$EMPTY_TREE

 	identical=
 	nonidentical=
@@ -603,6 +606,7 @@ cmd_split()
 	revmax=$(eval "$grl" | wc -l)
 	revcount=0
 	createcount=0
+	found_first_commit=
 	eval "$grl" |
 	while read rev parents; do
 		revcount=$(($revcount + 1))
@@ -625,12 +629,16 @@ cmd_split()
 		
 		# ugly.  is there no better way to tell if this is a subtree
 		# vs. a mainline commit?  Does it matter?
-		if [ -z $tree ]; then
-			set_notree $rev
-			if [ -n "$newparents" ]; then
-				cache_set $rev $rev
+		if [ -z $found_first_commit ]; then
+			if [ -z $tree ]; then
+				set_notree $rev
+				if [ -n "$newparents" ]; then
+					cache_set $rev $rev
+				fi
+				continue
+			else
+				found_first_commit=yes
 			fi
-			continue
 		fi

 		newrev=$(copy_or_skip "$rev" "$tree" "$newparents") || exit $?
-- 
2.5.0