summaryrefslogtreecommitdiff
path: root/var.sh
blob: d0c7df56a6243584851907eab56c47cb88505a61 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
die()
{
    if [ "$*" ]; then
        printf 'Error: %s\n' "$*" >&2
    else
        echo 'Error: fatal error' >&2
    fi
    exit 1
}

nosex()
{
    case $- in
        *x*) set +x; "$@"; set -x;;
        *) "$@";;
    esac
}

_nonempty()
{
    printf '[ "${%s}" ] || die \"mandatory parameter is empty: %s\";\n' "$1" "$1"
}

_mandatory()
{
    printf '[ $# -ge %d ] || die \"mandatory parameter is missing: %s\";\n' "$2" "$1"
}

_assign()
{
    printf 'local %s="${%d}";\n' "$1" "$2"
}

_args()
{
    local v i=1 check="$1" assign="$2"
    shift
    shift
    for v; do
        $assign "$v" "$i"
        $check "$v" "$i"
        i=$((i+1))
    done
}

_ARGS()
{
    echo eval "$(_args _mandatory _assign "$@")"
}

_ARGS_NONEMPTY()
{
    echo eval "$(_args _nonempty _assign "$@")"
}

_ARGS_OPTIONAL()
{
    echo eval "$(_args : _assign "$@")"
}

_NONEMPTY()
{
    echo eval "$(_args _nonempty : "$@")"
}

ARGS()          { nosex _ARGS "$@"; }
ARGS_NONEMPTY() { nosex _ARGS_NONEMPTY "$@"; }
ARGS_OPTIONAL() { nosex _ARGS_OPTIONAL "$@"; }
NONEMPTY()      { nosex _NONEMPTY "$@"; }

ARGS_NE() { ARGS_NONEMPTY "$@"; }

if [ "${0#-}" = bash ]; then
    export -f die _nonempty _mandatory _args ARGS ARGS_NONEMPTY ARGS_OPTIONAL
fi