diff options
Diffstat (limited to 'src/var.sh')
-rw-r--r-- | src/var.sh | 75 |
1 files changed, 75 insertions, 0 deletions
diff --git a/src/var.sh b/src/var.sh new file mode 100644 index 0000000..d0c7df5 --- /dev/null +++ b/src/var.sh | |||
@@ -0,0 +1,75 @@ | |||
1 | die() | ||
2 | { | ||
3 | if [ "$*" ]; then | ||
4 | printf 'Error: %s\n' "$*" >&2 | ||
5 | else | ||
6 | echo 'Error: fatal error' >&2 | ||
7 | fi | ||
8 | exit 1 | ||
9 | } | ||
10 | |||
11 | nosex() | ||
12 | { | ||
13 | case $- in | ||
14 | *x*) set +x; "$@"; set -x;; | ||
15 | *) "$@";; | ||
16 | esac | ||
17 | } | ||
18 | |||
19 | _nonempty() | ||
20 | { | ||
21 | printf '[ "${%s}" ] || die \"mandatory parameter is empty: %s\";\n' "$1" "$1" | ||
22 | } | ||
23 | |||
24 | _mandatory() | ||
25 | { | ||
26 | printf '[ $# -ge %d ] || die \"mandatory parameter is missing: %s\";\n' "$2" "$1" | ||
27 | } | ||
28 | |||
29 | _assign() | ||
30 | { | ||
31 | printf 'local %s="${%d}";\n' "$1" "$2" | ||
32 | } | ||
33 | |||
34 | _args() | ||
35 | { | ||
36 | local v i=1 check="$1" assign="$2" | ||
37 | shift | ||
38 | shift | ||
39 | for v; do | ||
40 | $assign "$v" "$i" | ||
41 | $check "$v" "$i" | ||
42 | i=$((i+1)) | ||
43 | done | ||
44 | } | ||
45 | |||
46 | _ARGS() | ||
47 | { | ||
48 | echo eval "$(_args _mandatory _assign "$@")" | ||
49 | } | ||
50 | |||
51 | _ARGS_NONEMPTY() | ||
52 | { | ||
53 | echo eval "$(_args _nonempty _assign "$@")" | ||
54 | } | ||
55 | |||
56 | _ARGS_OPTIONAL() | ||
57 | { | ||
58 | echo eval "$(_args : _assign "$@")" | ||
59 | } | ||
60 | |||
61 | _NONEMPTY() | ||
62 | { | ||
63 | echo eval "$(_args _nonempty : "$@")" | ||
64 | } | ||
65 | |||
66 | ARGS() { nosex _ARGS "$@"; } | ||
67 | ARGS_NONEMPTY() { nosex _ARGS_NONEMPTY "$@"; } | ||
68 | ARGS_OPTIONAL() { nosex _ARGS_OPTIONAL "$@"; } | ||
69 | NONEMPTY() { nosex _NONEMPTY "$@"; } | ||
70 | |||
71 | ARGS_NE() { ARGS_NONEMPTY "$@"; } | ||
72 | |||
73 | if [ "${0#-}" = bash ]; then | ||
74 | export -f die _nonempty _mandatory _args ARGS ARGS_NONEMPTY ARGS_OPTIONAL | ||
75 | fi | ||