Skip to content

Allow requiring that options precede parameters #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 28 additions & 1 deletion argsparse.sh
Original file line number Diff line number Diff line change
Expand Up @@ -1341,6 +1341,33 @@ argsparse_allow_no_argument() {
}


# Default behaviour is to continue parsing options after a non-option parameter
# is encountered.
__argsparse_scanning_mode=""


## @fn argsparse_options_first()
## @brief Stop parsing options once a non-option parameter is encountered.
## @details Change argsparse behaviour to require that options
## precede non-options. Default is to ignore order.
## @param string if (case-insensitive) "yes", "true" or "1", the value
## is considered as affirmative. Anything else is a negative value.
## @retval 0 unless there's more than one parameter (or none).
## @ingroup ArgsparseParameter
argsparse_options_first() {
[[ $# -eq 1 ]] || return 1
local param=$1
case "${param,,}" in
yes|true|1)
__argsparse_scanning_mode="+"
;;
*)
__argsparse_scanning_mode=""
;;
esac
}


## @brief Internal use only.
## @details The default minimum parameters requirement for command line.
## @ingroup ArgsparseParameter
Expand Down Expand Up @@ -1760,7 +1787,7 @@ __argsparse_parse_options_no_usage() {

# 4. Invoke getopt and replace arguments.
if ! getopt_temp=$(getopt -s bash -n "$argsparse_pgm" \
--longoptions="$longs" "$shorts" "$@")
--longoptions="$longs" "$__argsparse_scanning_mode$shorts" "$@")
then
# Syntax error on the command implies returning with error.
return 1
Expand Down
10 changes: 10 additions & 0 deletions unittest
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,16 @@ parse_option_wrapper() {
parse_option_wrapper "short property" -S
)

(
argsparse_use_option option1 ""

argsparse_options_first yes
parse_option_wrapper "stop at nonoption" --option1 nonoption --invalid

argsparse_options_first no
TEST=failure parse_option_wrapper "don't stop at nonoption" --option1 nonoption --invalid
)

(
argsparse_use_option =shortcut ""
parse_option_wrapper "= in optstring" -s
Expand Down