cobra PersistentPreRun 堆栈溢出
cobra PersistentPreRun stack overflow
为什么以下使用 cobra 包的 CLI 程序在 运行 和 go run /tmp/test.go branch leaf
时抛出堆栈溢出错误,但当 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()
}
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")
},
为什么以下使用 cobra 包的 CLI 程序在 运行 和 go run /tmp/test.go branch leaf
时抛出堆栈溢出错误,但当 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()
}
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")
},