為什么以下使用 cobra 包的 CLI 程序在運(yùn)行時(shí)會(huì)拋出堆棧溢出錯(cuò)誤go run /tmp/test.go branch leaf,但當(dāng)葉子命令直接連接到 root 時(shí)不會(huì)出錯(cuò)(如主函數(shù)中所述)?這表明我沒(méi)有正確使用 cobra PersistenRun* 功能。我對(duì) PersistenRun* 函數(shù)的理解是它們僅適用于命令的子級(jí)。問(wèn)題似乎是命令的父級(jí)已以某種方式設(shè)置為命令本身。package mainimport ( "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()}
1 回答

鳳凰求蠱
TA貢獻(xiàn)1825條經(jīng)驗(yàn) 獲得超4個(gè)贊
NVM,我想通了。
而不是
PersistentPreRun: func(cmd *cobra.Command, args []string) {
cmd.Parent().PersistentPreRun(cmd, args)
fmt.Println("in * pre run")
},
它應(yīng)該是:
PersistentPreRun: func(cmd *cobra.Command, args []string) {
cmd.Parent().PersistentPreRun(cmd.Parent(), args)
fmt.Println("in * pre run")
},
- 1 回答
- 0 關(guān)注
- 164 瀏覽
添加回答
舉報(bào)
0/150
提交
取消