From e5f522d610d34914e3fcf8b23de1b771c467196e Mon Sep 17 00:00:00 2001
From: Jens Lehmann <Jens.Lehmann@web.de>
Date: Sun, 6 Mar 2011 23:13:36 +0100
Subject: [PATCH] submodule update: Don't fetch when the submodule commit is
 already present

If the commit to be checked out on "git submodule update" has already been
fetched in the submodule there is no need to run "git fetch" again. Since
"git fetch" recently learned recursion (and the new on-demand mode to
fetch commits recorded in the superproject is enabled by default) this
will happen pretty often, thereby making the unconditional fetch during
"git submodule update" unnecessary.

If the commit is not present in the submodule (e.g. the user disabled the
fetch on-demand mode) the fetch will be run as before.

Signed-off-by: Jens Lehmann <Jens.Lehmann@web.de>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
---
 git-submodule.sh            |  5 ++++-
 t/t7406-submodule-update.sh | 20 ++++++++++++++++++++
 2 files changed, 24 insertions(+), 1 deletion(-)

diff --git a/git-submodule.sh b/git-submodule.sh
index 8b905897176..514d2eb7ab9 100755
--- a/git-submodule.sh
+++ b/git-submodule.sh
@@ -464,8 +464,11 @@ cmd_update()
 
 			if test -z "$nofetch"
 			then
+				# Run fetch only if $sha1 isn't present or it
+				# is not reachable from a ref.
 				(clear_local_git_env; cd "$path" &&
-					git-fetch) ||
+					((rev=$(git rev-list -n 1 $sha1 --not --all 2>/dev/null) &&
+					 test -z "$rev") || git-fetch)) ||
 				die "Unable to fetch in submodule path '$path'"
 			fi
 
diff --git a/t/t7406-submodule-update.sh b/t/t7406-submodule-update.sh
index bfb4975e940..ee3eec51571 100755
--- a/t/t7406-submodule-update.sh
+++ b/t/t7406-submodule-update.sh
@@ -74,6 +74,26 @@ test_expect_success 'submodule update detaching the HEAD ' '
 	)
 '
 
+apos="'";
+test_expect_success 'submodule update does not fetch already present commits' '
+	(cd submodule &&
+	  echo line3 >> file &&
+	  git add file &&
+	  test_tick &&
+	  git commit -m "upstream line3"
+	) &&
+	(cd super/submodule &&
+	  head=$(git rev-parse --verify HEAD) &&
+	  echo "Submodule path ${apos}submodule$apos: checked out $apos$head$apos" > ../../expected &&
+	  git reset --hard HEAD~1
+	) &&
+	(cd super &&
+	  git submodule update > ../actual 2> ../actual.err
+	) &&
+	test_cmp expected actual &&
+	! test -s actual.err
+'
+
 test_expect_success 'submodule update --rebase staying on master' '
 	(cd super/submodule &&
 	  git checkout master