title: cobra PersistentPreRun stack overflow
body: <p>why does the following CLI program using the cobra package throw a stack overflow error when ran with <code>go run /tmp/test.go branch leaf</code>, but does not error when when leaf subcommand is directly connected to root(as commented in the main function)?</p>
  <p>This suggests that I'm not using the cobra PersistenRun* functions properly. My understanding of the PersistenRun* functions is that they only apply to command's children. The issue seems that a command's parent has been somehow set to the command itself.</p>
  <pre class="lang-golang prettyprint-override"><code>package main
  
  import (
          &quot;fmt&quot;
          &quot;os&quot;
          &quot;path&quot;
  
          &quot;github.com/spf13/cobra&quot;
  )
  
  var programName = path.Base(os.Args[0])
  
  var rootCmd = &amp;cobra.Command{
          Use: programName,
          PersistentPreRun: func(cmd *cobra.Command, args []string) {
                  fmt.Println(&quot;in root pre run&quot;)
          },
  }
  
  var branchCmd = &amp;cobra.Command{
          Use: &quot;branch&quot;,
          PersistentPreRun: func(cmd *cobra.Command, args []string) {
                  cmd.Parent().PersistentPreRun(cmd, args)
                  fmt.Println(&quot;in branch pre run&quot;)
          },
  }
  
  var leafCmd = &amp;cobra.Command{
          Use: &quot;leaf&quot;,
          PersistentPreRun: func(cmd *cobra.Command, args []string) {
                  cmd.Parent().PersistentPreRun(cmd, args)
                  fmt.Println(&quot;in leaf pre run&quot;)
          },
          Run: func(cmd *cobra.Command, args []string) {
                  fmt.Println(&quot;in leaf run&quot;)
          },
  }
  
  func main() {
          branchCmd.AddCommand(leafCmd)
          rootCmd.AddCommand(branchCmd)
          rootCmd.Execute()
  
          // If I connect the root to the leaf directly, like the following, then
          // the program no longer stack overflow
          // rootCmd.AddCommand(leafCmd)
          // rootCmd.Execute()
  }
  </code></pre>