From d1821a06667ce31c7b1b7ab387b3421b3382d484 Mon Sep 17 00:00:00 2001 From: hasheddan Date: Fri, 11 Sep 2020 15:48:39 -0500 Subject: [PATCH] Add UsageOnMissing option to Kong Adds an UsageOnMissing option which configures Kong to omit errors and display usage when a command is invalid due to a missing argument. This can be useful if a user wishes for the top-level command to print usage when no args are supplied, or if they would prefer child commands which have their own subcommands to print usage specific to that command. Signed-off-by: hasheddan --- context.go | 6 ++++++ kong.go | 15 ++++++++------- options.go | 8 ++++++++ 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/context.go b/context.go index 56efd92..b4d1ee2 100644 --- a/context.go +++ b/context.go @@ -187,6 +187,9 @@ func (c *Context) Validate() error { // nolint: gocyclo } if err := checkMissingChildren(node); err != nil { + if c.Kong.usageOnMissing { + return c.PrintUsage(false) + } return err } if err := checkMissingPositionals(positionals, node.Positional); err != nil { @@ -624,6 +627,9 @@ func (c *Context) Run(binds ...interface{}) (err error) { defer catch(&err) node := c.Selected() if node == nil { + if c.Kong.usageOnMissing { + return nil + } return fmt.Errorf("no command selected") } return c.RunNode(node, binds...) diff --git a/kong.go b/kong.go index 3e09f47..21085b2 100644 --- a/kong.go +++ b/kong.go @@ -47,13 +47,14 @@ type Kong struct { resolvers []Resolver registry *Registry - noDefaultHelp bool - usageOnError bool - help HelpPrinter - helpFormatter HelpValueFormatter - helpOptions HelpOptions - helpFlag *Flag - vars Vars + noDefaultHelp bool + usageOnError bool + usageOnMissing bool + help HelpPrinter + helpFormatter HelpValueFormatter + helpOptions HelpOptions + helpFlag *Flag + vars Vars // Set temporarily by Options. These are applied after build(). postBuildOptions []Option diff --git a/options.go b/options.go index 5bd36c3..1369b6b 100644 --- a/options.go +++ b/options.go @@ -216,6 +216,14 @@ func UsageOnError() Option { }) } +// UsageOnMissing configures Kong to display usage and exit successfully if command is missing a child argument. +func UsageOnMissing() Option { + return OptionFunc(func(k *Kong) error { + k.usageOnMissing = true + return nil + }) +} + // ClearResolvers clears all existing resolvers. func ClearResolvers() Option { return OptionFunc(func(k *Kong) error {