]> git.corax.cc Git - toolbox/commitdiff
include/opt: Add a default regex and action
authorMatthias Kruk <m@m10k.eu>
Thu, 11 Aug 2022 18:21:40 +0000 (03:21 +0900)
committerMatthias Kruk <m@m10k.eu>
Thu, 11 Aug 2022 18:21:40 +0000 (03:21 +0900)
The regex and action of an option may be unset, making it necessary
to check their value before using them.

This commit modifies the opt module to define a default regex and
action in case the user didn't provide one, allowing the parser to
omit checks if the two are unset.

include/opt.sh

index 80abb52cff110b47b3271ff2181bce7d75a78f4d..9129933ed59570d96f3723c1860b7057b6a47423 100644 (file)
@@ -99,8 +99,8 @@ opt_add_arg() {
        local flags="$3"
        local default="$4"
        local desc="$5"
-       local regex="$6"
-       local action="$7"
+       local regex="${6-.*}"
+       local action="${7-true}"
 
        local -i parsed_flags
 
@@ -212,7 +212,7 @@ opt_parse() {
                        value="${argv[$i]}"
                        regex="${__opt_regex[$long]}"
 
-                       if [[ -n "$regex" ]] && ! [[ "$value" =~ $regex ]]; then
+                       if ! [[ "$value" =~ $regex ]]; then
                                log_error "Value \"$value\" doesn't match \"$regex\""
                                return 1
                        fi
@@ -222,13 +222,11 @@ opt_parse() {
 
                __opt_value["$long"]="$value"
 
-               if [[ -n "$action" ]]; then
-                       "$action" "$long" "$value"
-                       err="$?"
+               "$action" "$long" "$value"
+               err="$?"
 
-                       if (( err != 0 )); then
-                               return "$err"
-                       fi
+               if (( err != 0 )); then
+                       return "$err"
                fi
        done