From 3590a53ed1f4da611625d722ba3a8ac9707664f7 Mon Sep 17 00:00:00 2001
From: Leah Rowe <leah@libreboot.org>
Date: Wed, 17 Jul 2024 13:01:12 +0100
Subject: [PATCH] git.sh: cache git downloads to repo/

do it based on the URL, e.g. https://review.coreboot.org/coreboot
becomes repo/coreboot

the downside is if you have two projects with repo urls specifying
the same string at the end, but this isn't the case at the moment
and likely won't be the case, but it's a theoretical issue.

this saves on bandwidth when downloading identical submodule repos
between multiple trees within the same multi-tree project

for example, coreboot 3rdparty/vboot is no longer downloaded more
than once, instead cloned locally on subsequent downloads.

if repo/DIR exists, git-pull is attempted, but errors do not result
in a non-zero exit, by design.

Signed-off-by: Leah Rowe <leah@libreboot.org>
---
 .gitignore     |  1 +
 include/git.sh | 10 +++++++++-
 2 files changed, 10 insertions(+), 1 deletion(-)

diff --git a/.gitignore b/.gitignore
index ccf4d01..0d03069 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +1,7 @@
 *~
 *.o
 /cbmk.err.log
+/repo/
 /docs/
 /util/dell-flash-unlock/dell_flash_unlock
 /TODO
diff --git a/include/git.sh b/include/git.sh
index 58f62ef..25db40b 100644
--- a/include/git.sh
+++ b/include/git.sh
@@ -103,7 +103,15 @@ fetch_submodule()
 
 tmpclone()
 {
-	git clone $1 "$3" || git clone $2 "$3" || $err "!clone $1 $2 $3 $4 $5"
+	repodir="repo/${1##*/}"
+	x_ mkdir -p "repo"
+	if [ -d "$repodir" ]; then
+		git -C "$repodir" pull || :
+	else
+		git clone $1 "$repodir" || git clone $2 "$repodir" || \
+		    $err "!clone $1 $2 $repodir $4 $5"
+	fi
+	git clone "$repodir" "$3" || $err "!clone $repodir $3"
 	git -C "$3" reset --hard "$4" || $err "!reset $1 $2 $3 $4 $5"
 	git_am_patches "$3" "$5"
 }