From 6c81d37f27aea204173d23621b2dfff09dd1f0ad Mon Sep 17 00:00:00 2001 From: Peter Aronoff Date: Sun, 8 Dec 2024 12:38:58 -0500 Subject: [PATCH] feat: make small improvements to optionparser 1. Add a Coda field to OptionParser. The user can put text here that will appear at the bottom of a help message. (This is especially nice for links pointing to further information or where to file bug reports.) 2. Make a few small changes pointed out by staticcheck. (Do not use uppercase letters at the start of an error, and avoid a loop when using `append`.) 3. Change the help message to go better with my preferences. --- internal/optionparser/optionparser.go | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/internal/optionparser/optionparser.go b/internal/optionparser/optionparser.go index 16482c9..c6de79b 100644 --- a/internal/optionparser/optionparser.go +++ b/internal/optionparser/optionparser.go @@ -18,11 +18,12 @@ type command struct { } // OptionParser contains the methods to parse options and the settings to -// influence the output of --help. Set the Banner for usage info, set Start and -// Stop for output of the long description text. +// influence the output of --help. Set the Banner and Coda for usage info, set +// Start and Stop for output of the long description text. type OptionParser struct { Extra []string Banner string + Coda string Start int Stop int options []*allowedOptions @@ -203,9 +204,7 @@ func set(obj *allowedOptions, hasNoPrefix bool, param string) { } if obj.stringslice != nil { eachParam := strings.Split(param, ",") - for _, v := range eachParam { - *obj.stringslice = append(*obj.stringslice, v) - } + *obj.stringslice = append(*obj.stringslice, eachParam...) } if obj.functionNoArgs != nil { obj.functionNoArgs() @@ -327,7 +326,7 @@ func (op *OptionParser) ParseFrom(args []string) error { } if option == nil { - return fmt.Errorf("Unknown option %s", ret.argument) + return fmt.Errorf("unknown option %s", ret.argument) } // the parameter in ret.param is only set by `splitOn()` when used with @@ -359,7 +358,7 @@ func (op *OptionParser) ParseFrom(args []string) error { // parameter expected if !option.optional { // No parameter found but expected - return fmt.Errorf("Parameter expected but none given %s", ret.argument) + return fmt.Errorf("parameter expected but none given %s", ret.argument) } } set(option, ret.negate, "") @@ -428,6 +427,9 @@ func (op *OptionParser) Help() { formatAndOutput(op.Start, op.Stop, "", "", "", "", cmd.name, lines) } } + if op.Coda != "" { + fmt.Println(op.Coda) + } } // NewOptionParser initializes the OptionParser struct with sane settings for Banner, @@ -440,6 +442,6 @@ func NewOptionParser() *OptionParser { a.Stop = 79 a.short = map[string]*allowedOptions{} a.long = map[string]*allowedOptions{} - a.On("-h", "--help", "Show this help", func() { a.Help(); os.Exit(0) }) + a.On("-h", "--help", "Print this help and exit", func() { a.Help(); os.Exit(0) }) return a }