Add better usage and error messages

pull/85/head v0.10.1
rwxrob 2 years ago
parent 6fff916b9c
commit 96fb962b51
No known key found for this signature in database
GPG Key ID: 2B9111F33082AE77

@ -57,6 +57,7 @@ type Cmd struct {
MinArgs int `json:"-"` // minimum number of args required (including parms)
MaxArgs int `json:"-"` // maximum number of args required (including parms)
NumArgs int `json:"-"` // exact number of args required (including parms)
NoArgs bool `json:"-"` // must not have any args
MinParm int `json:"-"` // minimum number of params required
MaxParm int `json:"-"` // maximum number of params required
UseConf bool `json:"-"` // requires Z.Conf be assigned
@ -316,6 +317,9 @@ func (x *Cmd) Run() {
}
switch {
case len(args) > 0 && cmd.NoArgs:
ExitError(TooManyArgs{cmd})
return
case len(args) < cmd.MinArgs:
ExitError(NotEnoughArgs{cmd})
return
@ -599,8 +603,15 @@ func (x *Cmd) GetAliases() []string { return x.Aliases }
// GetSummary fulfills the bonzai.Command interface. Uses Fill.
func (x *Cmd) GetSummary() string { return x.Fill(x.Summary) }
// GetUsage fulfills the bonzai.Command interface. Uses Fill.
func (x *Cmd) GetUsage() string { return x.Fill(x.Usage) }
// GetUsage fulfills the bonzai.Command interface. Uses x.Usage if not
// empty. Otherwise, calls UsageFunc to get usage, then uses Fill.
func (x *Cmd) GetUsage() string {
usage := x.Usage
if usage == "" {
usage = UsageFunc(x)
}
return x.Fill(usage)
}
// GetVersion fulfills the bonzai.Command interface. Uses Fill.
func (x *Cmd) GetVersion() string { return x.Fill(x.Version) }

@ -7,7 +7,10 @@ type NotEnoughArgs struct {
}
func (e NotEnoughArgs) Error() string {
return fmt.Sprintf("not enough args, %v required", e.Cmd.MinArgs)
return fmt.Sprintf(
"usage: %v %v (not enough args, %v required)",
e.Cmd.Name, e.Cmd.GetUsage(), e.Cmd.MinArgs,
)
}
type TooManyArgs struct {
@ -15,7 +18,10 @@ type TooManyArgs struct {
}
func (e TooManyArgs) Error() string {
return fmt.Sprintf("too many args, %v maximum", e.Cmd.MaxArgs)
return fmt.Sprintf(
"usage: %v %v (too many args, %v maximum)",
e.Cmd.Name, e.Cmd.GetUsage(), e.Cmd.MaxArgs,
)
}
type WrongNumArgs struct {
@ -23,7 +29,10 @@ type WrongNumArgs struct {
}
func (e WrongNumArgs) Error() string {
return fmt.Sprintf("wrong number of args, %v required", e.Cmd.NumArgs)
return fmt.Sprintf(
"usage: %v %v (wrong number of args, %v required)",
e.Cmd.Name, e.Cmd.GetUsage(), e.Cmd.NumArgs,
)
}
type MissingConf struct {
@ -71,7 +80,7 @@ type IncorrectUsage struct {
}
func (e IncorrectUsage) Error() string {
return fmt.Sprintf("usage: %v %v", e.Cmd.Name, UsageFunc(e.Cmd))
return fmt.Sprintf("usage: %v %v", e.Cmd.Name, e.Cmd.GetUsage())
}
type MultiCallCmdNotFound struct {

Loading…
Cancel
Save