@@ -70,7 +70,7 @@ func Execute() {
7070}
7171
7272func init () {
73- cobra .OnInitialize ( func () { fixPersistentPreRuns ( rootCmd ) })
73+ cobra .EnableTraverseRunHooks = true
7474 cobra .OnInitialize (initConfig )
7575
7676 rootCmd .PersistentFlags ().StringVarP (& cfgFile , "config" , "c" , "" , "config file (default is $HOME/.config/fioctl.yaml)" )
@@ -213,59 +213,3 @@ $ fioctl completion fish > ~/.config/fish/completions/fioctl.fish
213213 }
214214 },
215215}
216-
217- func fixPersistentPreRuns (cmd * cobra.Command ) {
218- // See https://github.com/spf13/cobra/issues/216
219- parentPreRunE := cmd .PersistentPreRunE
220- parentPreRun := cmd .PersistentPreRun
221- // First, traverse up to find a parent defining the PersistentPreRun function.
222- for p := cmd .Parent (); p != nil && parentPreRunE == nil && parentPreRun == nil ; p = p .Parent () {
223- // Cobra prefers PersistentPreRunE over PersistentPreRun if both are defined, so do we.
224- // Actually, no our code defines both functions (expected), so that assumption is safe.
225- if p .PersistentPreRunE != nil {
226- parentPreRunE = p .PersistentPreRunE
227- } else if p .PersistentPreRun != nil {
228- parentPreRun = p .PersistentPreRun
229- }
230- }
231-
232- // Traverse children tree top-down, gradually fixing their PersistentPreRun functions to call into parents.
233- for _ , child := range cmd .Commands () {
234- preRun := child .PersistentPreRun
235- preRunE := child .PersistentPreRunE
236- if preRunE != nil {
237- if parentPreRunE != nil {
238- child .PersistentPreRunE = func (cmd * cobra.Command , args []string ) error {
239- if err := parentPreRunE (cmd , args ); err != nil {
240- return err
241- }
242- return preRunE (cmd , args )
243- }
244- } else if parentPreRun != nil {
245- child .PersistentPreRunE = func (cmd * cobra.Command , args []string ) error {
246- parentPreRun (cmd , args )
247- return preRunE (cmd , args )
248- }
249- }
250- } else if preRun != nil {
251- if parentPreRunE != nil {
252- // Set the PersistentPreRunE, not PersistentPreRun, so that we can return the parent error into cmd.execute.
253- child .PersistentPreRun = nil
254- child .PersistentPreRunE = func (cmd * cobra.Command , args []string ) error {
255- if err := parentPreRunE (cmd , args ); err != nil {
256- return err
257- }
258- preRun (cmd , args )
259- return nil
260- }
261- } else if parentPreRun != nil {
262- child .PersistentPreRun = func (cmd * cobra.Command , args []string ) {
263- parentPreRun (cmd , args )
264- preRun (cmd , args )
265- }
266- }
267- }
268- // Now that this child command was fixed, we can run the magic recursion.
269- fixPersistentPreRuns (child )
270- }
271- }
0 commit comments