Accept count as '-X' as well, add usage and error handling

Also make shellcheck happy.
This commit is contained in:
Thomas Otto 2020-03-20 19:51:41 +01:00
parent 1985391134
commit 460a3e479c
2 changed files with 34 additions and 11 deletions

View file

@ -18,20 +18,43 @@ case $(uname -s) in
;;
esac
function ensure_integer() {
if ! [[ "$1" =~ ^[1-9][0-9]*$ ]]; then
echo "error: -n requires an integer argument."
exit 1
fi
}
function usage() {
echo "Usage: git recent [-n <num> | -<num>]"
echo " List latest local git branches, formatted real fancy."
}
COUNT=0
while getopts "n:" opt; do
case ${opt} in
n )
if ! [[ $OPTARG =~ ^[0-9]{1,}$ ]]; then
echo "-n should be an integer."
exit 1
fi
COUNT=${OPTARG}
while [[ $# -gt 0 ]]; do
case "$1" in
-n )
COUNT="$2"
ensure_integer "$COUNT"
shift
;;
-[1-9]* | -n[1-9]* )
COUNT="${1#-}"
COUNT="${COUNT#n}"
ensure_integer "$COUNT"
;;
-h | --h* )
usage
exit 0
;;
* )
echo "error: unknown argument '$1'"
usage
exit 1
;;
esac
shift
done
shift $((OPTIND-1))
format="\
%(HEAD) \
@ -48,7 +71,7 @@ lessopts="--tabs=4 --quit-if-one-screen --RAW-CONTROL-CHARS --no-init"
git for-each-ref \
--color=always \
--count=$COUNT \
--count="$COUNT" \
--sort=-committerdate \
"refs/heads/" \
--format="$format" \

View file

@ -7,7 +7,7 @@ Type `git recent` to see your latest local git branches
git recent
Optionally, add `-n<int>` to see the most recent `<n>` branches
Optionally, add `-n<num>` or `-<num>` to see only the `<num>` most recent branches:
git recent -n5