From b84bf415bf057cab669b5828e050cc291314f2a2 Mon Sep 17 00:00:00 2001 From: Florent Viel Date: Fri, 19 Feb 2021 18:59:19 +0100 Subject: [PATCH] Add a flag to control printing help before exiting --- cli.go | 11 ++++++----- commands.go | 7 ++++++- internal/fsm/fsm.go | 9 ++++++--- 3 files changed, 18 insertions(+), 9 deletions(-) diff --git a/cli.go b/cli.go index 6bce342..38646f0 100644 --- a/cli.go +++ b/cli.go @@ -36,11 +36,12 @@ name and description will be used to construct the help message for the app: func App(name, desc string) *Cli { return &Cli{ Cmd: &Cmd{ - name: name, - desc: desc, - optionsIdx: map[string]*container.Container{}, - argsIdx: map[string]*container.Container{}, - ErrorHandling: flag.ExitOnError, + name: name, + desc: desc, + optionsIdx: map[string]*container.Container{}, + argsIdx: map[string]*container.Container{}, + ErrorHandling: flag.ExitOnError, + PrintHelpOnExit: true, }, } } diff --git a/commands.go b/commands.go index 99b43ba..1ce272e 100644 --- a/commands.go +++ b/commands.go @@ -1,6 +1,7 @@ package cli import ( + "errors" "flag" "fmt" "io" @@ -35,6 +36,8 @@ type Cmd struct { // The command error handling strategy ErrorHandling flag.ErrorHandling + PrintHelpOnExit bool + init CmdInitializer name string aliases []string @@ -677,7 +680,9 @@ func (c *Cmd) parse(args []string, entry, inFlow, outFlow *flow.Step) error { if err := c.fsm.Parse(args[:nargsLen]); err != nil { fmt.Fprintf(stdErr, "Error: %s\n", err.Error()) - c.PrintHelp() + if c.PrintHelpOnExit || errors.Is(err, fsm.ErrIncorrectUsage) { + c.PrintHelp() + } c.onError(err) return err } diff --git a/internal/fsm/fsm.go b/internal/fsm/fsm.go index e16208e..fff51f3 100644 --- a/internal/fsm/fsm.go +++ b/internal/fsm/fsm.go @@ -1,15 +1,18 @@ package fsm import ( + "errors" "sort" - "fmt" - "github.com/jawher/mow.cli/internal/container" "github.com/jawher/mow.cli/internal/matcher" "github.com/jawher/mow.cli/internal/values" ) +var ( + ErrIncorrectUsage = errors.New("incorrect usage") +) + /* State is the basic building block in the FSM. A State can be final or not, and has transitions to other states @@ -121,7 +124,7 @@ func (s *State) Parse(args []string) error { pc := matcher.NewParseContext() ok := s.apply(args, pc) if !ok { - return fmt.Errorf("incorrect usage") + return ErrIncorrectUsage } if err := fillContainers(pc.Opts); err != nil {