[Proposal] Return matched parser
myOmikron opened this issue · 3 comments
I'd propose to return the matched parser in Parse
. For the changes in code refer to the linked PR.
This would allow to identify which subcommand has matched to split the command execution afterwards.
This would be an example usage of argparse after the changes:
func main() {
// I have disabled defaultShowHelp, so I don't have to add additional arguments to invoke my switch below
parser := argparse.NewParser("Example", "This is an example parser", &argparse.ParserConfig{DisableDefaultShowHelp: true})
testParser := parser.AddCommand("test", "This is the test sub-command", &argparse.ParserConfig{DisableDefaultShowHelp: true})
exitParser := parser.AddCommand("exit", "This is the exit sub-command", &argparse.ParserConfig{DisableDefaultShowHelp: true})
matchedParser, err := parser.Parse(nil)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
switch {
case matchedParser == parser:
fmt.Println("The root parser was invoked")
doMain()
case matchedParser == testParser:
fmt.Println("The test parser was invoked")
doTest()
case matchedParser == exitParser:
fmt.Println("The exit parser was invoked")
doExit()
}
}
It's quite handy to know which parser is invoked, but the change could be more friendly if we don't change the interface of parser.Parse
.
actually, every parser
(including subParser created by AddCommand
) will have InvokeAction(func() {})
and Invoked
to indicate if it's invoked.
Ah, I missed that one.
Is there any reason to set Invoked
true on the root parser, if the subparser was used In my opinion it would be better to only set
Invoked` true on the parser that was used and ignore the chain.
Invoked
will be set more reasonably now, in the latest version v1.7.3
thanks again :)