From 7cebca376187b9d853fbe0feb1f2d7799ae7c785 Mon Sep 17 00:00:00 2001 From: spf13 Date: Fri, 27 Jun 2014 12:27:46 -0400 Subject: [PATCH] Add support for an InitializeConfig method as defined on Cobra by the user --- cobra.go | 7 +++++++ command.go | 15 +++++++++++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/cobra.go b/cobra.go index b653326..cb6501d 100644 --- a/cobra.go +++ b/cobra.go @@ -25,6 +25,13 @@ import ( "text/template" ) +// Called after flags are parsed immediately before executing any Command +var InitializeConfig func() + +func init() { + InitializeConfig = func() {} +} + func Gt(a interface{}, b interface{}) bool { var left, right int64 av := reflect.ValueOf(a) diff --git a/command.go b/command.go index c82e8eb..4a03a03 100644 --- a/command.go +++ b/command.go @@ -350,12 +350,17 @@ func (c *Command) execute(a []string) (err error) { return nil } + c.preRun() argWoFlags := c.Flags().Args() c.Run(c, argWoFlags) return nil } } +func (c *Command) preRun() { + InitializeConfig() +} + func (c *Command) errorMsgFromParse() string { s := c.flagErrorBuf.String() @@ -403,15 +408,16 @@ func (c *Command) Execute() (err error) { // Now handle the case where the root is runnable and only flags are provided if err != nil && c.Runnable() { + // This is pretty much a custom version of the *Command.execute method + // with a few differences because it's the final command (no fall back) e := c.ParseFlags(args) if e != nil { // Flags parsing had an error. - //fmt.Println(e) + // If an error happens here, we have to report it to the user c.Println(c.errorMsgFromParse()) c.Usage() return e } else { - // If help is called, regardless of other flags, we print that if c.helpFlagVal { c.Help() @@ -420,8 +426,13 @@ func (c *Command) Execute() (err error) { argWoFlags := c.Flags().Args() if len(argWoFlags) > 0 { + // If there are arguments (not flags) one of the earlier + // cases should have caught it.. It means invalid usage + // print the usage c.Usage() } else { + // Only flags left... Call root.Run + c.preRun() c.Run(c, argWoFlags) err = nil }