vendor/github.com/spf13/cobra/user_guide.md
changeset 260 445e01aede7e
parent 256 6d9efbef00a9
child 265 05c40b36d3b2
equal deleted inserted replaced
259:db4911b0c721 260:445e01aede7e
    27 }
    27 }
    28 ```
    28 ```
    29 
    29 
    30 ## Using the Cobra Generator
    30 ## Using the Cobra Generator
    31 
    31 
    32 Cobra provides its own program that will create your application and add any
    32 Cobra-CLI is its own program that will create your application and add any
    33 commands you want. It's the easiest way to incorporate Cobra into your application.
    33 commands you want. It's the easiest way to incorporate Cobra into your application.
    34 
    34 
    35 [Here](https://github.com/spf13/cobra/blob/master/cobra/README.md) you can find more information about it.
    35 For complete details on using the Cobra generator, please refer to [The Cobra-CLI Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md)
    36 
    36 
    37 ## Using the Cobra Library
    37 ## Using the Cobra Library
    38 
    38 
    39 To manually implement Cobra you need to create a bare main.go file and a rootCmd file.
    39 To manually implement Cobra you need to create a bare main.go file and a rootCmd file.
    40 You will optionally provide additional commands as you see fit.
    40 You will optionally provide additional commands as you see fit.
    49 var rootCmd = &cobra.Command{
    49 var rootCmd = &cobra.Command{
    50   Use:   "hugo",
    50   Use:   "hugo",
    51   Short: "Hugo is a very fast static site generator",
    51   Short: "Hugo is a very fast static site generator",
    52   Long: `A Fast and Flexible Static Site Generator built with
    52   Long: `A Fast and Flexible Static Site Generator built with
    53                 love by spf13 and friends in Go.
    53                 love by spf13 and friends in Go.
    54                 Complete documentation is available at http://hugo.spf13.com`,
    54                 Complete documentation is available at https://gohugo.io/documentation/`,
    55   Run: func(cmd *cobra.Command, args []string) {
    55   Run: func(cmd *cobra.Command, args []string) {
    56     // Do Stuff Here
    56     // Do Stuff Here
    57   },
    57   },
    58 }
    58 }
    59 
    59 
    84 	// Used for flags.
    84 	// Used for flags.
    85 	cfgFile     string
    85 	cfgFile     string
    86 	userLicense string
    86 	userLicense string
    87 
    87 
    88 	rootCmd = &cobra.Command{
    88 	rootCmd = &cobra.Command{
    89 		Use:   "cobra",
    89 		Use:   "cobra-cli",
    90 		Short: "A generator for Cobra based Applications",
    90 		Short: "A generator for Cobra based Applications",
    91 		Long: `Cobra is a CLI library for Go that empowers applications.
    91 		Long: `Cobra is a CLI library for Go that empowers applications.
    92 This application is a tool to generate the needed files
    92 This application is a tool to generate the needed files
    93 to quickly create a Cobra application.`,
    93 to quickly create a Cobra application.`,
    94 	}
    94 	}
   279 }
   279 }
   280 ```
   280 ```
   281 
   281 
   282 In this example, the persistent flag `author` is bound with `viper`.
   282 In this example, the persistent flag `author` is bound with `viper`.
   283 **Note**: the variable `author` will not be set to the value from config,
   283 **Note**: the variable `author` will not be set to the value from config,
   284 when the `--author` flag is not provided by user.
   284 when the `--author` flag is provided by user.
   285 
   285 
   286 More in [viper documentation](https://github.com/spf13/viper#working-with-flags).
   286 More in [viper documentation](https://github.com/spf13/viper#working-with-flags).
   287 
   287 
   288 ### Required flags
   288 ### Required flags
   289 
   289 
   298 ```go
   298 ```go
   299 rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
   299 rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
   300 rootCmd.MarkPersistentFlagRequired("region")
   300 rootCmd.MarkPersistentFlagRequired("region")
   301 ```
   301 ```
   302 
   302 
       
   303 ### Flag Groups
       
   304 
       
   305 If you have different flags that must be provided together (e.g. if they provide the `--username` flag they MUST provide the `--password` flag as well) then 
       
   306 Cobra can enforce that requirement:
       
   307 ```go
       
   308 rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)")
       
   309 rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)")
       
   310 rootCmd.MarkFlagsRequiredTogether("username", "password")
       
   311 ``` 
       
   312 
       
   313 You can also prevent different flags from being provided together if they represent mutually 
       
   314 exclusive options such as specifying an output format as either `--json` or `--yaml` but never both:
       
   315 ```go
       
   316 rootCmd.Flags().BoolVar(&u, "json", false, "Output in JSON")
       
   317 rootCmd.Flags().BoolVar(&pw, "yaml", false, "Output in YAML")
       
   318 rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")
       
   319 ```
       
   320 
       
   321 In both of these cases:
       
   322   - both local and persistent flags can be used
       
   323     - **NOTE:** the group is only enforced on commands where every flag is defined
       
   324   - a flag may appear in multiple groups
       
   325   - a group may contain any number of flags
       
   326 
   303 ## Positional and Custom Arguments
   327 ## Positional and Custom Arguments
   304 
   328 
   305 Validation of positional arguments can be specified using the `Args` field
   329 Validation of positional arguments can be specified using the `Args` field of `Command`.
   306 of `Command`.
   330 If `Args` is undefined or `nil`, it defaults to `ArbitraryArgs`.
   307 
   331 
   308 The following validators are built in:
   332 The following validators are built in:
   309 
   333 
   310 - `NoArgs` - the command will report an error if there are any positional args.
   334 - `NoArgs` - the command will report an error if there are any positional args.
   311 - `ArbitraryArgs` - the command will accept any args.
   335 - `ArbitraryArgs` - the command will accept any args.
   313 - `MinimumNArgs(int)` - the command will report an error if there are not at least N positional args.
   337 - `MinimumNArgs(int)` - the command will report an error if there are not at least N positional args.
   314 - `MaximumNArgs(int)` - the command will report an error if there are more than N positional args.
   338 - `MaximumNArgs(int)` - the command will report an error if there are more than N positional args.
   315 - `ExactArgs(int)` - the command will report an error if there are not exactly N positional args.
   339 - `ExactArgs(int)` - the command will report an error if there are not exactly N positional args.
   316 - `ExactValidArgs(int)` - the command will report an error if there are not exactly N positional args OR if there are any positional args that are not in the `ValidArgs` field of `Command`
   340 - `ExactValidArgs(int)` - the command will report an error if there are not exactly N positional args OR if there are any positional args that are not in the `ValidArgs` field of `Command`
   317 - `RangeArgs(min, max)` - the command will report an error if the number of args is not between the minimum and maximum number of expected args.
   341 - `RangeArgs(min, max)` - the command will report an error if the number of args is not between the minimum and maximum number of expected args.
       
   342 - `MatchAll(pargs ...PositionalArgs)` - enables combining existing checks with arbitrary other checks (e.g. you want to check the ExactArgs length along with other qualities).
   318 
   343 
   319 An example of setting the custom validator:
   344 An example of setting the custom validator:
   320 
   345 
   321 ```go
   346 ```go
   322 var cmd = &cobra.Command{
   347 var cmd = &cobra.Command{
   402   cmdEcho.AddCommand(cmdTimes)
   427   cmdEcho.AddCommand(cmdTimes)
   403   rootCmd.Execute()
   428   rootCmd.Execute()
   404 }
   429 }
   405 ```
   430 ```
   406 
   431 
   407 For a more complete example of a larger application, please checkout [Hugo](http://gohugo.io/).
   432 For a more complete example of a larger application, please checkout [Hugo](https://gohugo.io/).
   408 
   433 
   409 ## Help Command
   434 ## Help Command
   410 
   435 
   411 Cobra automatically adds a help command to your application when you have subcommands.
   436 Cobra automatically adds a help command to your application when you have subcommands.
   412 This will be called when a user runs 'app help'. Additionally, help will also
   437 This will be called when a user runs 'app help'. Additionally, help will also
   600         server
   625         server
   601 
   626 
   602 Run 'hugo --help' for usage.
   627 Run 'hugo --help' for usage.
   603 ```
   628 ```
   604 
   629 
   605 Suggestions are automatic based on every subcommand registered and use an implementation of [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.
   630 Suggestions are automatic based on every subcommand registered and use an implementation of [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.
   606 
   631 
   607 If you need to disable suggestions or tweak the string distance in your command, use:
   632 If you need to disable suggestions or tweak the string distance in your command, use:
   608 
   633 
   609 ```go
   634 ```go
   610 command.DisableSuggestions = true
   635 command.DisableSuggestions = true
   633 Cobra can generate documentation based on subcommands, flags, etc. Read more about it in the [docs generation documentation](doc/README.md).
   658 Cobra can generate documentation based on subcommands, flags, etc. Read more about it in the [docs generation documentation](doc/README.md).
   634 
   659 
   635 ## Generating shell completions
   660 ## Generating shell completions
   636 
   661 
   637 Cobra can generate a shell-completion file for the following shells: bash, zsh, fish, PowerShell. If you add more information to your commands, these completions can be amazingly powerful and flexible.  Read more about it in [Shell Completions](shell_completions.md).
   662 Cobra can generate a shell-completion file for the following shells: bash, zsh, fish, PowerShell. If you add more information to your commands, these completions can be amazingly powerful and flexible.  Read more about it in [Shell Completions](shell_completions.md).
       
   663 
       
   664 ## Providing Active Help
       
   665 
       
   666 Cobra makes use of the shell-completion system to define a framework allowing you to provide Active Help to your users.  Active Help are messages (hints, warnings, etc) printed as the program is being used.  Read more about it in [Active Help](active_help.md).