1
0
Fork 0
mirror of https://github.com/notwa/rc synced 2024-11-05 05:39:02 -08:00
rc/sh/argc

63 lines
1.5 KiB
Text
Raw Normal View History

#!/usr/bin/env sh
# YES_ZSH
# YES_BASH
# YES_DASH
# YES_ASH
2021-08-01 07:35:26 -07:00
argc() { ### @- validate the number of arguments in a function.
### ```sh
2021-08-01 07:35:26 -07:00
### # usage: myfunc() { argc -(eq|le|ge) [0-9] "$0" "$@" || return; }
###
### myfunc() {
2021-07-31 23:32:43 -07:00
### # use one of the following:
### argc -eq N "$0" "$@" || return
### argc -le N "$0" "$@" || return
### argc -ge N "$0" "$@" || return
### # where N is an integer between 0 and 9.
### }
### ```
2021-07-31 23:32:43 -07:00
# local usage='usage: myfunc() { %s -(eq|lt|gt|le|ge) [0-9] "$0" "$@" || return; }\n'
local usage='usage: myfunc() { %s -(eq|le|ge) [0-9] "$0" "$@" || return; }\n'
# note that $zero can be empty, but must be set.
if [ $# -lt 3 ] || [ -z "$1" ] || [ -z "$2" ] || [ "${3+x}" != x ]; then
printf "$usage" argc >&2
return 2
fi
2021-07-31 23:32:43 -07:00
local cond="$1"; shift
local want="$1"; shift
local zero="$1"; shift
2021-07-31 23:32:43 -07:00
local many='' plural=''
[ "$want" = 1 ] || plural='s'
case "$cond" in
'-eq') many='exactly';;
# '-lt') many='fewer than';;
# '-gt') many='more than';;
'-le') many='at most';;
'-ge') many='at least';;
*)
printf "$usage" argc >&2
return 2;;
esac
case "$want" in
2021-07-31 23:32:43 -07:00
[0-9]) :;; # no error, continue.
*)
2021-07-31 23:32:43 -07:00
printf "$usage" argc >&2
return 2;;
esac
2021-07-31 23:32:43 -07:00
if [ ! $# "$cond" "$want" ]; then
local err="expected $many $want argument$plural, got"
printf '%s: %s %s\n' "$zero" "$err" "$#" >&2
return 1
fi
return 0
}
[ -n "${preload+-}" ] || argc "$@"