git-gc-preserve: improve error handling

Return exit code
- 1 for general failures
- 2 if the repository path cannot be determined

In case git gc itself fails use its exit code to exit git-gc-preserve.

Release-Notes: skip
Change-Id: Ifc4487b191b1aa3dea6d60e7c7b2f7171fe38f9c
diff --git a/contrib/git-gc-preserve b/contrib/git-gc-preserve
index 54b8fca..73717fe 100755
--- a/contrib/git-gc-preserve
+++ b/contrib/git-gc-preserve
@@ -13,7 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-usage() { # error_message
+usage() { # exit code
   cat <<-EOF
 NAME
     git-gc-preserve - Run git gc and preserve old packs to avoid races for JGit
@@ -28,6 +28,14 @@
     repository since it does not attempt to implement the file locking
     which git gc --auto does [3].
 
+    Failure Exit Codes
+        1: General failure
+        2: Couldn't determine repository path. If the current working directory
+           is outside of the working tree of the git repository use git option
+           --git-dir to pass the root path of the repository.
+           E.g.
+              $ git --git-dir ~/git/foo gc-preserve
+
     [1] https://git.eclipse.org/r/c/jgit/jgit/+/87969
     [2] https://git.eclipse.org/r/c/jgit/jgit/+/122288
     [3] https://github.com/git/git/commit/64a99eb4760de2ce2f0c04e146c0a55c34f50f20
@@ -49,7 +57,7 @@
       across missing objects which might be caused by a concurrent run of
       git gc.
 EOF
-  exit
+  exit "$1"
 }
 
 # prune preserved packs if gc.prunepreserved == true
@@ -74,7 +82,7 @@
     return 0
   fi
   local packdir=$1/objects/pack
-  pushd "$packdir" >/dev/null || exit
+  pushd "$packdir" >/dev/null || exit 1
   mkdir -p preserved
   printf "Preserving packs: "
   count=0
@@ -85,7 +93,7 @@
     fi
   done
   echo "$count, done."
-  popd >/dev/null || exit
+  popd >/dev/null || exit 1
 }
 
 # pack-0...2.pack to pack-0...2.old-pack
@@ -100,7 +108,7 @@
 
 while [ $# -gt 0 ] ; do
     case "$1" in
-        -u|-h)  usage ;;
+        -u|-h)  usage 0 ;;
     esac
     shift
 done
@@ -108,10 +116,9 @@
 
 repopath=$(git rev-parse --git-dir)
 if [ -z "$repopath" ]; then
-  usage
-  exit $?
+  usage 2
 fi
 
 prune_preserved "$repopath"
 preserve_packs "$repopath"
-git gc ${args:+"$args"}
+git gc ${args:+"$args"} || { echo "git gc failed"; exit "$?"; }