2

为什么以下使用 cobra 包的 CLI 程序在运行时会抛出堆栈溢出错误go run /tmp/test.go branch leaf,但当叶子命令直接连接到 root 时不会出错(如主函数中所述)?

这表明我没有正确使用 cobra PersistenRun* 功能。我对 PersistenRun* 函数的理解是它们仅适用于命令的子级。问题似乎是命令的父级已以某种方式设置为命令本身。

package main

import (
        "fmt"
        "os"
        "path"

        "github.com/spf13/cobra"
)

var programName = path.Base(os.Args[0])

var rootCmd = &cobra.Command{
        Use: programName,
        PersistentPreRun: func(cmd *cobra.Command, args []string) {
                fmt.Println("in root pre run")
        },
}

var branchCmd = &cobra.Command{
        Use: "branch",
        PersistentPreRun: func(cmd *cobra.Command, args []string) {
                cmd.Parent().PersistentPreRun(cmd, args)
                fmt.Println("in branch pre run")
        },
}

var leafCmd = &cobra.Command{
        Use: "leaf",
        PersistentPreRun: func(cmd *cobra.Command, args []string) {
                cmd.Parent().PersistentPreRun(cmd, args)
                fmt.Println("in leaf pre run")
        },
        Run: func(cmd *cobra.Command, args []string) {
                fmt.Println("in leaf run")
        },
}

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()
}
4

1 回答 1

3

NVM,我想通了。

而不是

       PersistentPreRun: func(cmd *cobra.Command, args []string) {
                cmd.Parent().PersistentPreRun(cmd, args)
                fmt.Println("in * pre run")
       },

它应该是:

       PersistentPreRun: func(cmd *cobra.Command, args []string) {
                cmd.Parent().PersistentPreRun(cmd.Parent(), args)
                fmt.Println("in * pre run")
       },

于 2020-09-24T22:35:49.957 回答