matejak / argbash

Bash argument parsing code generator
Other
1.39k stars 63 forks source link

Allow checking whether optionals provided explicitly #187

Open kstrafe opened 6 months ago

kstrafe commented 6 months ago

Since boolean optionals default to "off" we have no way to check if a boolean optional was actually specified on the command line.

The ability to check if a boolean optional has been given is useful in cases where we source values from a configuration file where we want any explicitly given arguments to override the configuration.

An example that mostly works is (for plain optionals with an empty default):

    test -f ~/.standard-values-for-this-script && source "$_"
    MYOPT="${MYOPT:-$_arg_myopt}"
    ... # Code using MYOPT

This works since optionals can default to an empty string. We still are not entirely sure if the optional was actually passed here, but it tends to be "good enough" in most cases.

In the case where myopt is boolean, the above case would always use "off" if the argument was not specified, thus overriding the sourced configuration file.

This patch introduces _optionals, an array where each optional inserts itself if they were actually given.

This allows us to do the following:

    test -f ~/.standard-values-for-this-script && source "$_"
    if [[ ${_optionals[@]} =~ _arg_myopt ]]; then
            MYOPT="$_arg_myopt" # We override
    fi
    ... # Code using MYOPT
kstrafe commented 6 months ago

Posting this PR to get some feedback, it's why I haven't written any tests. Let me know if this is a better way to implement this. I think this feature is really useful.