mirror of
https://github.com/spf13/cobra
synced 2024-11-24 22:57:12 +00:00
Merge pull request #102 from andronat/master
Fixed Persistent-Run function propagation
This commit is contained in:
commit
7fc9f148dd
2 changed files with 27 additions and 12 deletions
|
@ -869,3 +869,20 @@ func TestPreRun(t *testing.T) {
|
||||||
t.Error("Wrong *Pre functions called!")
|
t.Error("Wrong *Pre functions called!")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check if cmdEchoSub gets PersistentPreRun from rootCmd even if is added last
|
||||||
|
func TestPeristentPreRunPropagation(t *testing.T) {
|
||||||
|
rootCmd := initialize()
|
||||||
|
|
||||||
|
// First add the cmdEchoSub to cmdPrint
|
||||||
|
cmdPrint.AddCommand(cmdEchoSub)
|
||||||
|
// Now add cmdPrint to rootCmd
|
||||||
|
rootCmd.AddCommand(cmdPrint)
|
||||||
|
|
||||||
|
rootCmd.SetArgs(strings.Split("print echosub lala", " "))
|
||||||
|
rootCmd.Execute()
|
||||||
|
|
||||||
|
if rootPersPre == nil || len(rootPersPre) == 0 || rootPersPre[0] != "lala" {
|
||||||
|
t.Error("RootCmd PersistentPreRun not called but should have been")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
22
command.go
22
command.go
|
@ -463,8 +463,11 @@ func (c *Command) execute(a []string) (err error) {
|
||||||
c.preRun()
|
c.preRun()
|
||||||
argWoFlags := c.Flags().Args()
|
argWoFlags := c.Flags().Args()
|
||||||
|
|
||||||
if c.PersistentPreRun != nil {
|
for p := c; p != nil; p = p.Parent() {
|
||||||
c.PersistentPreRun(c, argWoFlags)
|
if p.PersistentPreRun != nil {
|
||||||
|
p.PersistentPreRun(c, argWoFlags)
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if c.PreRun != nil {
|
if c.PreRun != nil {
|
||||||
c.PreRun(c, argWoFlags)
|
c.PreRun(c, argWoFlags)
|
||||||
|
@ -475,8 +478,11 @@ func (c *Command) execute(a []string) (err error) {
|
||||||
if c.PostRun != nil {
|
if c.PostRun != nil {
|
||||||
c.PostRun(c, argWoFlags)
|
c.PostRun(c, argWoFlags)
|
||||||
}
|
}
|
||||||
if c.PersistentPostRun != nil {
|
for p := c; p != nil; p = p.Parent() {
|
||||||
c.PersistentPostRun(c, argWoFlags)
|
if p.PersistentPostRun != nil {
|
||||||
|
p.PersistentPostRun(c, argWoFlags)
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
|
@ -601,14 +607,6 @@ func (c *Command) AddCommand(cmds ...*Command) {
|
||||||
c.commandsMaxNameLen = nameLen
|
c.commandsMaxNameLen = nameLen
|
||||||
}
|
}
|
||||||
c.commands = append(c.commands, x)
|
c.commands = append(c.commands, x)
|
||||||
|
|
||||||
// Pass on peristent pre/post functions to children
|
|
||||||
if x.PersistentPreRun == nil {
|
|
||||||
x.PersistentPreRun = c.PersistentPreRun
|
|
||||||
}
|
|
||||||
if x.PersistentPostRun == nil {
|
|
||||||
x.PersistentPostRun = c.PersistentPostRun
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue