From 4cf9a0c4440069ad787decceb08e9498b463feed Mon Sep 17 00:00:00 2001 From: Wayne Warren Date: Thu, 20 Dec 2018 10:21:06 -0600 Subject: [PATCH] issue#798 support initializers that return error --- cobra.go | 7 +++++++ command.go | 14 ++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/cobra.go b/cobra.go index 7010fd15..e3a3f732 100644 --- a/cobra.go +++ b/cobra.go @@ -37,6 +37,7 @@ var templateFuncs = template.FuncMap{ } var initializers []func() +var initializersWithError []func() error // EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing // to automatically enable in CLI tools. @@ -76,6 +77,12 @@ func OnInitialize(y ...func()) { initializers = append(initializers, y...) } +// OnInitializeE sets the passed functions to be run when each command's +// Execute method is called. +func OnInitializeE(y ...func() error) { + initializers = append(initializers, y...) +} + // FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra. // Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans, diff --git a/command.go b/command.go index 34d1bf36..7e1123c7 100644 --- a/command.go +++ b/command.go @@ -727,6 +727,11 @@ func (c *Command) execute(a []string) (err error) { c.preRun() + err = c.preRunE() + if err != nil { + return err + } + argWoFlags := c.Flags().Args() if c.DisableFlagParsing { argWoFlags = a @@ -793,6 +798,15 @@ func (c *Command) preRun() { } } +func (c *Command) preRunE() { + for _, x := range initializersWithError { + err := x() + if err != nil { + return err + } + } +} + // Execute uses the args (os.Args[1:] by default) // and run through the command tree finding appropriate matches // for commands and then corresponding flags.