From 42e6ce397f6b996220f8318526213968e78804f4 Mon Sep 17 00:00:00 2001 From: Anastasis Andronidis Date: Mon, 4 May 2015 03:36:05 +0200 Subject: [PATCH 1/2] Fixed Persistent-Run function propagation --- command.go | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/command.go b/command.go index 5d03aaff..978c4b09 100644 --- a/command.go +++ b/command.go @@ -463,8 +463,11 @@ func (c *Command) execute(a []string) (err error) { c.preRun() argWoFlags := c.Flags().Args() - if c.PersistentPreRun != nil { - c.PersistentPreRun(c, argWoFlags) + for p := c; p != nil; p = p.Parent() { + if p.PersistentPreRun != nil { + p.PersistentPreRun(c, argWoFlags) + break + } } if c.PreRun != nil { c.PreRun(c, argWoFlags) @@ -475,8 +478,11 @@ func (c *Command) execute(a []string) (err error) { if c.PostRun != nil { c.PostRun(c, argWoFlags) } - if c.PersistentPostRun != nil { - c.PersistentPostRun(c, argWoFlags) + for p := c; p != nil; p = p.Parent() { + if p.PersistentPostRun != nil { + p.PersistentPostRun(c, argWoFlags) + break + } } return nil @@ -601,14 +607,6 @@ func (c *Command) AddCommand(cmds ...*Command) { c.commandsMaxNameLen = nameLen } 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 - } } } From 799a8ef863e9770c8d0bda8270b34e8d490bf0bd Mon Sep 17 00:00:00 2001 From: Anastasis Andronidis Date: Mon, 4 May 2015 17:57:46 +0200 Subject: [PATCH 2/2] Test for Persistent-Run propagation --- cobra_test.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/cobra_test.go b/cobra_test.go index 080b8ddd..56746495 100644 --- a/cobra_test.go +++ b/cobra_test.go @@ -869,3 +869,20 @@ func TestPreRun(t *testing.T) { 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") + } +}