我想了解如何创建服装命令为旅途中使用的眼镜蛇(和蝮蛇)库,并能够使用它们.
具体而言,我试图理解并提供他们提供工作的例子.示例如下:
import( "github.com/spf13/cobra" "fmt" "strings" ) func main() { var echoTimes int var cmdPrint = &cobra.Command{ Use: "print [string to print]", Short: "Print anything to the screen", Long: `print is for printing anything back to the screen. For many years people have printed back to the screen. `, Run: func(cmd *cobra.Command, args []string) { fmt.Println("Print: " + strings.Join(args, " ")) }, } var cmdEcho = &cobra.Command{ Use: "echo [string to echo]", Short: "Echo anything to the screen", Long: `echo is for echoing anything back. Echo works a lot like print, except it has a child command. `, Run: func(cmd *cobra.Command, args []string) { fmt.Println("Print: " + strings.Join(args, " ")) }, } var cmdTimes = &cobra.Command{ Use: "times [# times] [string to echo]", Short: "Echo anything to the screen more times", Long: `echo things multiple times back to the user by providing a count and a string.`, Run: func(cmd *cobra.Command, args []string) { for i:=0; i < echoTimes; i++ { fmt.Println("Echo: " + strings.Join(args, " ")) } }, } cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input") var rootCmd = &cobra.Command{Use: "app"} rootCmd.AddCommand(cmdPrint, cmdEcho) cmdEcho.AddCommand(cmdTimes) rootCmd.Execute() }
但是,我已经为它制作了文件package main
,我似乎无法使其正常工作.我知道rootCmd不是可执行的.但是,在我看来,Use字段表现不一致(据我所知).我试图了解命令如何在命令行中实际运行,并以不同的方式编译文件来试验它.
比如我编译这个文件,我命名为cobra.go
用go build cobra.go
,现在我有一个可执行文件cobra
.
如果我这样做的./name
行为./name help
和打印方式相同:
Usage: app [command] Available Commands: print [string to print] Print anything to the screen echo [string to echo] Echo anything to the screen help [command] Help about any command Available Flags: --help=false: help for app Use "app help [command]" for more information about that command.
但是,描述错误地说要使用它,你必须做"app help [command]".
如果我这样做./app help print
(当然只有cobra可执行文件)它打印:
zsh: no such file or directory: ./app
如果我这样做app help print
也不起作用(因为它没有在PATH中找到):
zsh: command not found: app
所以我的理解是,除非我使用与root相同的名称构建它,否则cobra会表现得很有趣.
因此,这意味着use字段必须匹配帮助输出的文件名才有意义,并且我们能够正确运行其子命令,对吧?
此外,如何是一个能够有(编译)多个不同的"根"在同一个项目的命令,如果只有一个主包允许?如果在main下有多个"root"命令,它应该不起作用,对吧?我很快就会尝试其中的一些想法.