2

I'm working with the Cobra library for Go. The README shows an example that handles configuration setup via the cobra.OnInitialize function. The documentation for OnInitialize says:

OnInitialize sets the passed functions to be run when each command's Execute method is called.

But isn't that pretty much exactly the same thing as registering a PersistentPreRun function on the root command? That will also run just before the Execute method on any command.

larsks
  • 277,717
  • 41
  • 399
  • 399
  • 1
    There seem to be several oddities like this in spf13/cobra. I suspect Hysterical Raisins myself. – torek Aug 14 '21 at 08:29
  • Actually, I suspect that the difference is that while you can only have one active `PersistentPreRun` (that is, setting it on a child will override one set on a parent), you can call `cobra.OnInitialize` multiple times and all the registered functions will be called. I have yet to verify this. – larsks Aug 14 '21 at 12:48
  • 2
    Interesting, but that could be the historical reason (someone needed one behavior when only the other was available). I do wish the documentation were clearer. – torek Aug 15 '21 at 01:08

0 Answers0