Positional and Custom Arguments
Validation of positional arguments can be specified using the Args
field
of Command
.
The following validators are built in:
NoArgs
- the command will report an error if there are any positional args.ArbitraryArgs
- the command will accept any args.OnlyValidArgs
- the command will report an error if there are any positional args that are not in theValidArgs
field ofCommand
.MinimumNArgs(int)
- the command will report an error if there are not at least N positional args.MaximumNArgs(int)
- the command will report an error if there are more than N positional args.ExactArgs(int)
- the command will report an error if there are not exactly N positional args.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 theValidArgs
field ofCommand
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.
An example of setting the custom validator:
var cmd = &cobra.Command{
Short: "hello",
Args: func(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return errors.New("requires a color argument")
}
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!")
},
}