1
0
Fork 0
mirror of https://github.com/notwa/rc synced 2024-11-13 20:39:04 -08:00
rc/sh/argc
Connor Olding d5f3f14d72 merge compatibility lines
RIP meaningful last-modified dates
2024-03-26 15:08:14 -07:00

64 lines
1.5 KiB
Bash
Executable file

#!/usr/bin/env sh
# YES_ZSH YES_BASH YES_DASH YES_ASH
argc() { ### @- validate the number of arguments in a function.
### ```sh
### # usage: myfunc() { argc $# -(eq|le|ge) [0-9] "$0" || return; }
###
### myfunc() {
### # 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.
### }
### ```
local usage='usage: myfunc() { %s $# -(eq|le|ge) [0-9] "$0" || return; }\n'
# note that $zero can be empty, but must be set.
if [ $# -ne 4 ] || [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ]; then
printf "$usage" argc >&2
return 1
fi
local argc="$1"; shift
local cond="$1"; shift
local want="$1"; shift
local zero="$1"; shift
local many='' plural=''
[ "$want" = 1 ] || plural='s'
if [ "$argc" != "${argc%%[!0-9]*}" ]; then
printf "$usage" argc >&2
return 1
fi
case "$cond" in
('-eq') many='exactly';;
('-le') many='at most';;
('-ge') many='at least';;
(*)
printf "$usage" argc >&2
return 1;;
esac
case "$want" in
([0-9]) :;; # no error, continue.
(*)
printf "$usage" argc >&2
return 1;;
esac
if [ "$argc" "$cond" "$want" ] 2>/dev/null; then
:
else
local err="expected $many $want argument$plural, got"
printf '%s: %s %s\n' "$zero" "$err" "$argc" >&2
return 64
fi
return 0
}
[ -n "${preload+-}" ] || argc "$@"