Skip to content

Commit

Permalink
Add support for an InitializeConfig method as defined on Cobra by the…
Browse files Browse the repository at this point in the history
… user
  • Loading branch information
spf13 committed Jun 27, 2014
1 parent 10a8494 commit 7cebca3
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
7 changes: 7 additions & 0 deletions cobra.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
15 changes: 13 additions & 2 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down Expand Up @@ -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()
Expand All @@ -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
}
Expand Down

0 comments on commit 7cebca3

Please sign in to comment.