command: filter parse errors
Signed-off-by: Ophestra <cat@gensokyo.uk>
This commit is contained in:
parent
eda4d612c2
commit
ba1498cd18
@ -29,6 +29,11 @@ type (
|
||||
|
||||
Command interface {
|
||||
Parse(arguments []string) error
|
||||
|
||||
// MustParse determines exit outcomes for Parse errors
|
||||
// and calls handleError if [HandlerFunc] returns a non-nil error.
|
||||
MustParse(arguments []string, handleError func(error))
|
||||
|
||||
baseNode[Command]
|
||||
}
|
||||
Node baseNode[Node]
|
||||
|
@ -3,6 +3,7 @@ package command
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"os"
|
||||
)
|
||||
|
||||
var (
|
||||
@ -78,3 +79,27 @@ func (n *node) printf(format string, a ...any) {
|
||||
n.logf(format, a...)
|
||||
}
|
||||
}
|
||||
|
||||
func (n *node) MustParse(arguments []string, handleError func(error)) {
|
||||
switch err := n.Parse(arguments); err {
|
||||
case nil:
|
||||
return
|
||||
case ErrHelp:
|
||||
os.Exit(0)
|
||||
case ErrNoMatch:
|
||||
os.Exit(1)
|
||||
case ErrEmptyTree:
|
||||
os.Exit(1)
|
||||
default:
|
||||
var flagError FlagError
|
||||
if !errors.As(err, &flagError) { // returned by HandlerFunc
|
||||
handleError(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if flagError.Success() {
|
||||
os.Exit(0)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user