问题描述
为什么下面的使用cobra软件包的CLI程序在与go run /tmp/test.go branch leaf
一起运行时为什么会引发堆栈溢出错误,而当leaf子命令直接连接到root时却不会出错(如主函数中所述)? / p>
这表明我没有正确使用眼镜蛇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",args []string) {
cmd.Parent().PersistentPreRun(cmd,args)
fmt.Println("in branch pre run")
},}
var leafCmd = &cobra.Command{
Use: "leaf",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()
}
解决方法
我了解了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(),