<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                Cobra既是用于創建強大的現代CLI應用程序的庫,也是用于生成應用程序和命令文件的程序。 許多最廣泛使用的Go項目都是使用Cobra構建的,包括: ~~~ Kubernetes Hugo rkt etcd Moby (former Docker) Docker (distribution) OpenShift Delve GopherJS CockroachDB Bleve ProjectAtomic (enterprise) GiantSwarm's swarm Nanobox/Nanopack rclone nehm Pouch ~~~ ## 概述 Cobra是一個庫,提供了一個簡單的[界面](https://www.baidu.com/s?wd=%E7%95%8C%E9%9D%A2&tn=24004469_oem_dg&rsv_dl=gh_pl_sl_csd)來創建類似于git&go工具的強大的現代CLI界面。 Cobra也是一個應用程序,它將生成您的應用程序支架,以快速開發基于Cobra的應用程序。 Cobra提供: ~~~ 簡單易用的基于CLI:app server,app fetch等。 完全符合POSIX標準(包括including short & long versions) 嵌套的子命令 全局,本地和級聯標志 易產生的應用程序和命令與cobra init appname&cobra add cmdname 智能建議 命令和標志的自動幫助生成 自動幫助標志識別-h,--help等等。 為您的應用程序自動生成bash自動完成 為您的應用程序自動生成的手冊頁 命令別名,以便您可以在不破壞它們的情況下進行更改 靈活定義您自己的幫助,用法等。 可選擇與viper緊密集成,適用于12-factor應用 ~~~ # 概念 Cobra建立在命令,參數和標志的結構上。 **Commands**代表動作,**Args**代表參數,**Flags**是這些動作的修飾符。 最好的應用程序在使用時會像句子一樣讀取。用戶將知道如何使用該應用程序,因為他們將原生地了解如何使用它。 要遵循的模式是?`APPNAME VERB NOUN --ADJECTIVE.`?或?`APPNAME COMMAND ARG --FLAG` 使用以下示例進行說明,在以下示例中,'server'是一個命令,'port'是一個標志: ~~~ hugo server --port=1313 ~~~ 在這個命令中,我們告訴Git克隆url ~~~ git clone URL --bare ~~~ ## Commands命令 命令是應用程序的中心點。應用程序支持的每個交互都將包含在命令中。命令可以具有子命令并可選地運行動作。 在上面的示例中,'server'是命令。[更多關于cobra.Command](https://godoc.org/github.com/spf13/cobra#Command) ## Flags標志 標志是一種修改命令行為的方法。Cobra支持完全符合POSIX標準的標志以及Go?[標志包](https://golang.org/pkg/flag/)。Cobra命令可以定義持久保存到子命令和標志的標志,這些命令和標志僅對該命令可用。 在上面的例子中,'port'是標志。 [標志功能](https://www.baidu.com/s?wd=%E6%A0%87%E5%BF%97%E5%8A%9F%E8%83%BD&tn=24004469_oem_dg&rsv_dl=gh_pl_sl_csd)由[pflag庫](https://github.com/spf13/pflag)提供,[pflag庫](https://github.com/spf13/pflag)是標準庫的一個分支,它在添加POSIX兼容性時保持相同的接口。 # Installing安裝 使用cobra很容易。首先,使用`go get`安裝最新版本的庫。此命令將安裝`cobra`生成器可執行文件以及庫及其依賴項: ~~~ go get -u github.com/spf13/cobra/cobra ~~~ 接下來,在您的應用程序中包含Cobra: ~~~ import "github.com/spf13/cobra" ~~~ # Getting Started入門 雖然歡迎您提供自己的組織,但通常基于Cobra的應用程序將遵循以下組織結構: ~~~ ? appName/ ? cmd/ add.go your.go commands.go here.go main.go ~~~ 在Cobra應用程序中,通常main.go是暴露的文件。它有一個目的:初始化Cobra ~~~ package main import ( "{pathToYourApp}/cmd" ) func main() { cmd.Execute() } ~~~ ## 使用Cobra生成器 Cobra提供了自己的程序,可以創建您的應用程序并添加您想要的任何命令。這是將Cobra整合到您的應用程序中的最簡單方法。 [在這里](https://github.com/spf13/cobra/blob/master/cobra/README.md)您可以找到有關它的更多信息。 ## 使用Cobra Library 要手動實現Cobra,您需要創建一個暴露的main.go文件和一個rootCmd文件。您可以選擇根據需要提供其他命令。 ### 創建rootCmd cobra不需要任何特殊的構造函數。只需創建命令即可。 理想情況下,您將其放在app / cmd / root.go中: ~~~ var rootCmd = &cobra.Command{ Use: "hugo", Short: "Hugo is a very fast static site generator", Long: `A Fast and Flexible Static Site Generator built with love by spf13 and friends in Go. Complete documentation is available at http://hugo.spf13.com`, Run: func(cmd *cobra.Command, args []string) { // Do Stuff Here }, } func Execute() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } } ~~~ 您還將在init()函數中定義標志和句柄配置。 例如cmd / root.go: ~~~ import ( "fmt" "os" homedir "github.com/mitchellh/go-homedir" "github.com/spf13/cobra" "github.com/spf13/viper" ) func init() { cobra.OnInitialize(initConfig) rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") rootCmd.PersistentFlags().StringVarP(&projectBase, "projectbase", "b", "", "base project directory eg. github.com/spf13/") rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "Author name for copyright attribution") rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "Name of license for the project (can provide `licensetext` in config)") rootCmd.PersistentFlags().Bool("viper", true, "Use Viper for configuration") viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) viper.BindPFlag("projectbase", rootCmd.PersistentFlags().Lookup("projectbase")) viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")) viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>") viper.SetDefault("license", "apache") } func initConfig() { // Don't forget to read config either from cfgFile or from home directory! if cfgFile != "" { // Use config file from the flag. viper.SetConfigFile(cfgFile) } else { // Find home directory. home, err := homedir.Dir() if err != nil { fmt.Println(err) os.Exit(1) } // Search config in home directory with name ".cobra" (without extension). viper.AddConfigPath(home) viper.SetConfigName(".cobra") } if err := viper.ReadInConfig(); err != nil { fmt.Println("Can't read config:", err) os.Exit(1) } } ~~~ ### 創建你的main.go 使用root命令,您需要讓main函數執行它。為了清楚起見,應該在root上運行Execute,盡管可以在任何命令上調用它。 在Cobra應用程序中,通常在main.go暴露。它有一個目的,就是初始化Cobra。 ~~~ package main import ( "fmt" "os" "{pathToYourApp}/cmd" ) func main() { cmd.Execute() } ~~~ ### 創建其他命令 可以定義其他命令,并且通常在cmd /目錄中為每個命令提供自己的文件。 如果要創建版本命令,可以創建cmd / version.go并使用以下內容填充它: ~~~ package cmd import ( "fmt" "github.com/spf13/cobra" ) func init() { rootCmd.AddCommand(versionCmd) } var versionCmd = &cobra.Command{ Use: "version", Short: "Print the version number of Hugo", Long: `All software has versions. This is Hugo's`, Run: func(cmd *cobra.Command, args []string) { fmt.Println("Hugo Static Site Generator v0.9 -- HEAD") }, } ~~~ ### 使用Flags Flags提供修飾符來控制動作命令的操作方式。 ### 為命令分配Flags 由于flag是在不同的位置定義和使用的,因此我們需要在外部定義一個具有正確范圍的變量來分配要使用的標志。 ~~~ var Verbose bool var Source string ~~~ 分配標志有兩種不同的方法。 ### 持久的Flags Flags可以是“持久的”,這意味著該標志可用于它所分配的命令以及該命令下的每個命令。對于全局標志,在根上分配Flag作為持久Flag。 ~~~ rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output") ~~~ ### 本地Flags 還可以在本地分配一個Flag,該Flag僅適用于該特定命令。 ~~~ rootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from") ~~~ ### 父命令上的本地Flags 默認情況下,Cobra僅解析目標命令上的本地Flag,忽略父命令上的任何本地Flag。通過啟用`Command.TraverseChildren`Cobra將在執行目標命令之前解析每個命令上的本地Flag。 ~~~ command := cobra.Command{ Use: "print [OPTIONS] [COMMANDS]", TraverseChildren: true,} ~~~ ### 使用配置綁定Flags 你也可以用[viper](https://blog.csdn.net/cs380637384/article/details/81217767)綁定你的Flags ~~~ var author string func init() { rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution") viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) } ~~~ 在此示例中,持久Flags?`author`與之綁定`viper`。?**請注意**,`author`當`--author`用戶未提供該標志時,該變量將不會設置為config中的值。 更多[viper文檔](https://blog.csdn.net/cs380637384/article/details/81217767)。 ### 必需的Flags Flags默認是可選的。如果您希望命令在未設置Flags時報告錯誤,請將其標記為必需: ~~~ rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)") rootCmd.MarkFlagRequired("region") ~~~ ### 位置和自定義參數 可以使用`Args`字段來指定位置參數的驗證`Command`。 以下驗證器內置: * `NoArgs`?- 如果存在任何位置參數,該命令將報告錯誤。 * `ArbitraryArgs`?- 該命令將接受任何args。 * `OnlyValidArgs`\- 如果存在任何不在`ValidArgs`字段中的位置參數,該命令將報告錯誤`Command`。 * `MinimumNArgs(int)`?- 如果沒有至少N個位置參數,該命令將報告錯誤。 * `MaximumNArgs(int)`?- 如果有多于N個位置參數,該命令將報告錯誤。 * `ExactArgs(int)`?- 如果沒有確切的N位置參數,該命令將報告錯誤。 * `RangeArgs(min, max)`?- 如果args的數量不在預期args的最小和最大數量之間,則該命令將報告錯誤。 設置自定義驗證器的示例: ~~~ var cmd = &cobra.Command{ Short: "hello", Args: func(cmd *cobra.Command, args []string) error { if len(args) < 1 { return errors.New("requires at least one arg") } if myapp.IsValidColor(args[0]) { return nil } return fmt.Errorf("invalid color specified: %s", args[0]) }, Run: func(cmd *cobra.Command, args []string) { fmt.Println("Hello, World!") }, } ~~~ ### 示例: 在下面的示例中,我們定義了三個命令。兩個位于頂層,一個(cmdTimes)是頂級命令之一的子級。在這種情況下,root不可執行,這意味著需要子命令。這是通過不為'rootCmd'提供'Run'來實現的。 我們只為一個命令定義了一個標志。 有關標志的更多文檔,請訪問[https://github.com/spf13/pflag](https://github.com/spf13/pflag) ~~~ package main import ( "fmt" "strings" "github.com/spf13/cobra" ) 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.`, Args: cobra.MinimumNArgs(1), 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.`, Args: cobra.MinimumNArgs(1), 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.`, Args: cobra.MinimumNArgs(1), 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() } ~~~ 有關更大應用程序的更完整示例,請查看[Hugo](http://gohugo.io/) ## 幫助命令 當您有子命令時,Cobra會自動為您的應用程序添加一個幫助命令。當用戶運行“app help”時會調用此方法。此外,幫助還將支持所有其他命令作為輸入。比如說,你有一個名為'create'的命令,沒有任何額外的配置;?當'app help create'被調用時,Cobra會工作。每個命令都會自動添加' - help'標志。 ### 例 以下輸出由Cobra自動生成。除了命令和標志定義之外,不需要任何其他內容。 ~~~ $ cobra help Cobra is a CLI library for Go that empowers applications. This application is a tool to generate the needed files to quickly create a Cobra application. Usage: cobra [command] Available Commands: add Add a command to a Cobra Application help Help about any command init Initialize a Cobra Application Flags: -a, --author string author name for copyright attribution (default "YOUR NAME") --config string config file (default is $HOME/.cobra.yaml) -h, --help help for cobra -l, --license string name of license for the project --viper use Viper for configuration (default true) Use "cobra [command] --help" for more information about a command. ~~~ 幫助就像任何其他命令一樣。它周圍沒有特殊的邏輯或行為。事實上,如果你愿意,你可以提供自己的。 ### 定義自己的help 您可以提供自己的help命令或自己的模板,以使用以下函數使用的默認命令: ~~~ cmd.SetHelpCommand(cmd *Command) cmd.SetHelpFunc(f func(*Command, []string)) cmd.SetHelpTemplate(s string) ~~~ 后兩者也適用于任何子命令。 ## 用法 當用戶提供無效標志或無效命令時,Cobra會通過向用戶顯示“使用情況”來做出響應。 ### 示例 您可以從上面的幫助中認識到這一點。那是因為默認幫助將用法嵌入其輸出中。 ~~~ $ cobra --invalid Error: unknown flag: --invalid Usage: cobra [command] Available Commands: add Add a command to a Cobra Application help Help about any command init Initialize a Cobra Application Flags: -a, --author string author name for copyright attribution (default "YOUR NAME") --config string config file (default is $HOME/.cobra.yaml) -h, --help help for cobra -l, --license string name of license for the project --viper use Viper for configuration (default true) Use "cobra [command] --help" for more information about a command. ~~~ ### 定義自己的用法 您可以提供自己的使用功能或模板供Cobra使用。與help一樣,函數和模板可以通過公共方法覆蓋: ~~~ cmd.SetUsageFunc(f func(*Command) error) cmd.SetUsageTemplate(s string) ~~~ ## 版本flags 如果在root命令上設置了Version字段,Cobra會添加頂級'--version'標志。使用'--version'標志運行應用程序將使用版本模板將版本打印到stdout。可以使用該`cmd.SetVersionTemplate(s string)`功能自定義模板?。 ## PreRun和PostRun Hooks `Run`命令在主函數之前或之后運行函數。`PersistentPreRun`和`PreRun`功能執行之前`Run`。`PersistentPostRun`和`PostRun`將在后執行`Run`。`Persistent*Run`如果子程序沒有聲明他們自己的功能,他們將繼承這些功能。這些功能按以下順序運行: ~~~ PersistentPreRun PreRun Run PostRun PersistentPostRun ~~~ 下面是使用所有這些功能的兩個命令的示例。執行子命令時,它將運行root命令,`PersistentPreRun`但不運行root命令`PersistentPostRun`:? ~~~ package main import ( "fmt" "github.com/spf13/cobra" ) func main() { var rootCmd = &cobra.Command{ Use: "root [sub]", Short: "My root command", PersistentPreRun: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args) }, PreRun: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside rootCmd PreRun with args: %v\n", args) }, Run: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside rootCmd Run with args: %v\n", args) }, PostRun: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside rootCmd PostRun with args: %v\n", args) }, PersistentPostRun: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args) }, } var subCmd = &cobra.Command{ Use: "sub [no options!]", Short: "My subcommand", PreRun: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside subCmd PreRun with args: %v\n", args) }, Run: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside subCmd Run with args: %v\n", args) }, PostRun: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside subCmd PostRun with args: %v\n", args) }, PersistentPostRun: func(cmd *cobra.Command, args []string) { fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args) }, } rootCmd.AddCommand(subCmd) rootCmd.SetArgs([]string{""}) rootCmd.Execute() fmt.Println() rootCmd.SetArgs([]string{"sub", "arg1", "arg2"}) rootCmd.Execute() } ~~~ 打印 ~~~ Inside rootCmd PersistentPreRun with args: [] Inside rootCmd PreRun with args: [] Inside rootCmd Run with args: [] Inside rootCmd PostRun with args: [] Inside rootCmd PersistentPostRun with args: [] Inside rootCmd PersistentPreRun with args: [arg1 arg2] Inside subCmd PreRun with args: [arg1 arg2] Inside subCmd Run with args: [arg1 arg2] Inside subCmd PostRun with args: [arg1 arg2] Inside subCmd PersistentPostRun with args: [arg1 arg2] ~~~ ### “未知命令”發生時的建議 當“未知命令”錯誤發生時,Cobra將打印自動建議。這使得Cobra?`git`在發生拼寫錯誤時的行為與命令類似。例如: ~~~ $ hugo srever Error: unknown command "srever" for "hugo" Did you mean this? server Run 'hugo --help' for usage. ~~~ 根據注冊的每個子命令自動提出建議,并使用[Levenshtein距離](http://en.wikipedia.org/wiki/Levenshtein_distance)的實現。每個匹配最小距離為2(忽略大小寫)的注冊命令將顯示為建議。 如果您需要在命令中禁用建議或調整字符串距離,請使用: ~~~ command.DisableSuggestions = true #或者 command.SuggestionsMinimumDistance = 1 ~~~ 您還可以使用該`SuggestFor`屬性顯式設置要為其指定命令的名稱。這允許建議字符串距離不接近的字符串,但在您的命令集和一些您不想要別名的字符串中有意義。例如: ~~~ $ kubectl remove Error: unknown command "remove" for "kubectl" Did you mean this? delete Run 'kubectl help' for usage. ~~~
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看