]> git.corax.cc Git - toolbox/commitdiff
include/opt: Make return values of opt_get() more helpful
authorMatthias Kruk <m@m10k.eu>
Thu, 11 Aug 2022 13:06:36 +0000 (22:06 +0900)
committerMatthias Kruk <m@m10k.eu>
Thu, 11 Aug 2022 13:06:36 +0000 (22:06 +0900)
The function `opt_get()` returns 0 when an option is valid but was
not set. This makes it impossible to distinguish if the value of
the option is the empty string or it does not have a value at all.
Further, it does not return an error if an invalid option's value
was requested.

This commit fixes the behavior of `opt_get()` so that it returns 0
if an option is valid and has a value (default or user-defined), 1
in case that the option name is invalid, and 2 in case that the
option name is valid but it does not have a value.

include/opt.sh

index 5ed8d94ee250a7530d525527f9c8e09501fed792..e50857543cd5bedefa626a175693ba937f8506a5 100644 (file)
@@ -109,10 +109,13 @@ opt_add_arg() {
        __opt_desc["$long"]="$desc"
        __opt_regex["$long"]="$regex"
        __opt_action["$long"]="$action"
-       __opt_default["$long"]="$default"
        __opt_map["-$short"]="$long"
        __opt_map["--$long"]="$long"
 
+       if [[ -n "$default" ]]; then
+               __opt_default["$long"]="$default"
+       fi
+
        ((__opt_num++))
 
        return 0
@@ -233,8 +236,12 @@ opt_get() {
 
        if array_contains "$long" "${!__opt_value[@]}"; then
                echo "${__opt_value[$long]}"
-       else
+       elif array_contains "$long" "${!__opt_default[@]}"; then
                echo "${__opt_default[$long]}"
+       elif [[ -n "${__opt_map[--$long]}" ]]; then
+               return 2
+       else
+               return 1
        fi
 
        return 0