I have a question about the functionality of argparse
. I use argparse
for custom functions and it's great, but sometimes I'd like to move the use of argparse
and supplemental code into a separate function and use it there to reduce boilerplate / visual noise.
This is a partial example of what I'd like to do:
function A
set --local options ... # some definition.
argparse_wrapper --name A $options -- $argv; or return 1
end
instead of
function A
set --local options ... # some definition.
argparse --name A $options -- $argv; or return 1
# Code validating flags set by argparse in some way that argparse is unable to do,
# i.e. validation that requires values from two flags (so f/flag!script would not
# work).
#
# Or, changing flag names to names more appropriate inside the function.
#
# Other boilerplate related to options, but
# unrelated to the purpose of the function.
#
end
But, I'm unable to set values inside of a function and transfer those values seamlessly to the caller. As in, argparse
sets values in the outer scope (the function calling argparse
), but I'm unable to do the same with a custom argparse
wrapper of my own. At least, I'm unsure of how to do so if there is a clean way. In particular, argparse
can set local variables in its outer scope, and I want to keep that functionality in the supposed argparse
wrapper. Is that possible?
I'm the person who designed and implemented argparse
. The approach I recommend is the one you'll find in the share/functions/fish_opt.fish module. Execute the argparse
in the function that implements the command. Define a helper function with the --no-scope-shadowing
flag to give it direct access to the vars in the parent function. Then call that function to validate the args (or do whatever is needed) after argparse
returns.