chiark / gitweb /
factor out checks into function
[topgit.git] / tg.sh
diff --git a/tg.sh b/tg.sh
index 4dcc15eff90bcc581980336b94d44f40e2385759..f8c8de4ba859d76d254580ef88041b3bdce05f19 100644 (file)
--- a/tg.sh
+++ b/tg.sh
@@ -17,6 +17,20 @@ die()
        exit 1
 }
 
+# Make sure we are in the worktree, not under .git; die otherwise
+ensure_git_repo_or_die()
+{
+       local is_inside_repo is_inside_git_dir
+       is_inside_repo=1
+       is_inside_git_dir=$(git rev-parse --is-inside-git-dir 2>/dev/null) ||
+               is_inside_repo=0
+
+       case "$is_inside_repo/$is_inside_git_dir" in
+       0*) die "Cannot run outside of a Git repository.";;
+       1/true) die "Cannot run from inside \`.git\` hierarchy, please switch to work-tree.";;
+       esac
+}
+
 # setup_hook NAME
 setup_hook()
 {
@@ -63,8 +77,8 @@ measure_branch()
        _bname="$1"; _base="$2"
        [ -n "$_base" ] || _base="refs/top-bases/$_bname"
        # The caller should've verified $name is valid
-       _commits="$(git rev-list "$_bname" ^"$_base" | wc -l)"
-       _nmcommits="$(git rev-list --no-merges "$_bname" ^"$_base" | wc -l)"
+       _commits="$(git rev-list "$_bname" ^"$_base" -- | wc -l)"
+       _nmcommits="$(git rev-list --no-merges "$_bname" ^"$_base" -- | wc -l)"
        if [ $_commits -gt 1 ]; then
                _suffix="commits"
        else
@@ -209,6 +223,12 @@ switch_to_base()
 do_help()
 {
        if [ -z "$1" ] ; then
+               # This is currently invoked in all kinds of circumstances,
+               # including when the user made a usage error. Should we end up
+               # providing more than a short help message, then we should
+               # differentiate.
+               # Petr's comment: http://marc.info/?l=git&m=122718711327376&w=2
+
                ## Build available commands list for help output
 
                cmds=
@@ -232,6 +252,8 @@ do_help()
                fi
        else
                echo "`basename $0`: no help for $1" 1>&2
+               do_help
+               exit 1
        fi
 }
 
@@ -241,6 +263,8 @@ do_help()
 [ -d "@cmddir@" ] ||
        die "No command directory: '@cmddir@'"
 
+ensure_git_repo_or_die
+
 ## Initial setup
 
 set -e
@@ -261,7 +285,13 @@ setup_hook "pre-commit"
 [ -z "$tg__include" ] || return 0
 
 if [ "$1" = "-r" ]; then
-       shift; base_remote="$1"; shift
+       shift
+       if [ -z "$1" ]; then
+               echo "Option -r requires an argument." >&2
+               do_help
+               exit 1
+       fi
+       base_remote="$1"; shift
        tg="$tg -r $base_remote"
 fi
 
@@ -279,7 +309,10 @@ help|--help|-h)
 *)
        [ -r "@cmddir@"/tg-$cmd ] || {
                echo "Unknown subcommand: $cmd" >&2
+               do_help
                exit 1
        }
        . "@cmddir@"/tg-$cmd;;
 esac
+
+# vim:noet