From 2c970eadb99bcf389af5a60c029cf8b74badf951 Mon Sep 17 00:00:00 2001 From: Jackjon Date: Tue, 10 Oct 2023 06:42:35 +0100 Subject: [PATCH] :recycle: (arg_parsing): Simplify option parsing fns (#14) --- modules/arg_parsing.sh | 121 +++++++++++++++++------------------------ 1 file changed, 49 insertions(+), 72 deletions(-) diff --git a/modules/arg_parsing.sh b/modules/arg_parsing.sh index ed2d214..81772ad 100755 --- a/modules/arg_parsing.sh +++ b/modules/arg_parsing.sh @@ -1,5 +1,5 @@ -TWO_VALUES_CONSUMED=1 -ONE_VALUE_CONSUMED=0 +ONE_VALUE_CONSUMED=1 +TWO_VALUES_CONSUMED=2 is_early_exit_option() { local args_and_options=("$@") @@ -77,92 +77,69 @@ validate_volume_type() { fi } -parse_arg() { - local current_value="$1" - local next_value="$2" - - case "$current_value" in - -d|--dir) - check_opt_missing_value "$current_value" "$next_value" - - VOLUME_DIR=$(strip_path "$next_value") - - return $TWO_VALUES_CONSUMED - ;; - -e|--exclude) - check_opt_missing_value "$current_value" "$next_value" - - IFS=',' read -ra EXCLUSIONS < <(echo "$next_value") - - return $TWO_VALUES_CONSUMED - ;; - -f|--force) - FORCE_ACTION=1 - - return $ONE_VALUE_CONSUMED - ;; - -h|--help) - display_help +parse_options() { + local values_remaining="$#" + local current_value="" + local next_value="" - # NOTE: display_help will exit, so we don't need to do anything else here. - ;; - -t|--type) - check_opt_missing_value "$current_value" "$next_value" + while (( "$values_remaining" )); do + current_value="$1" + next_value="$2" - validate_volume_type "$next_value" + case "$current_value" in + -d|--dir) + check_opt_missing_value "$current_value" "$next_value" - VOLUME_TYPE="$next_value" + VOLUME_DIR=$(strip_path "$next_value") - return $TWO_VALUES_CONSUMED - ;; - -V|--volume) - check_opt_missing_value "$current_value" "$next_value" + shift $TWO_VALUES_CONSUMED + ;; + -e|--exclude) + check_opt_missing_value "$current_value" "$next_value" - VOLUME_NAME=$(strip_path "$next_value") + IFS=',' read -ra EXCLUSIONS < <(echo "$next_value") - return $TWO_VALUES_CONSUMED - ;; - -y|--yes) - AUTO_CONFIRM=1 + shift $TWO_VALUES_CONSUMED + ;; + -f|--force) + FORCE_ACTION=1 - return $ONE_VALUE_CONSUMED - ;; - *) - print error "Unrecognised option: $current_value" + shift $ONE_VALUE_CONSUMED + ;; + -h|--help) + display_help - exit $EXIT_UNRECOGNIZED_OPTION - ;; - esac + # NOTE: display_help will exit, so we don't need to do anything else here. + ;; + -t|--type) + check_opt_missing_value "$current_value" "$next_value" - # NOTE: If we've gotten to this point, something very bad has happened. - print error "Unrecognised option: $current_value" + validate_volume_type "$next_value" - exit $EXIT_UNRECOGNIZED_OPTION -} - -parse_options() { - local options=("$@") - local total_options=${#options[@]} - local skip_current_value=0 + VOLUME_TYPE="$next_value" - for (( i=0; i