github.com/kunnos/engine@v1.13.1/cli/required.go (about) 1 package cli 2 3 import ( 4 "fmt" 5 "strings" 6 7 "github.com/spf13/cobra" 8 ) 9 10 // NoArgs validates args and returns an error if there are any args 11 func NoArgs(cmd *cobra.Command, args []string) error { 12 if len(args) == 0 { 13 return nil 14 } 15 16 if cmd.HasSubCommands() { 17 return fmt.Errorf("\n" + strings.TrimRight(cmd.UsageString(), "\n")) 18 } 19 20 return fmt.Errorf( 21 "\"%s\" accepts no argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s", 22 cmd.CommandPath(), 23 cmd.CommandPath(), 24 cmd.UseLine(), 25 cmd.Short, 26 ) 27 } 28 29 // RequiresMinArgs returns an error if there is not at least min args 30 func RequiresMinArgs(min int) cobra.PositionalArgs { 31 return func(cmd *cobra.Command, args []string) error { 32 if len(args) >= min { 33 return nil 34 } 35 return fmt.Errorf( 36 "\"%s\" requires at least %d argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s", 37 cmd.CommandPath(), 38 min, 39 cmd.CommandPath(), 40 cmd.UseLine(), 41 cmd.Short, 42 ) 43 } 44 } 45 46 // RequiresMaxArgs returns an error if there is not at most max args 47 func RequiresMaxArgs(max int) cobra.PositionalArgs { 48 return func(cmd *cobra.Command, args []string) error { 49 if len(args) <= max { 50 return nil 51 } 52 return fmt.Errorf( 53 "\"%s\" requires at most %d argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s", 54 cmd.CommandPath(), 55 max, 56 cmd.CommandPath(), 57 cmd.UseLine(), 58 cmd.Short, 59 ) 60 } 61 } 62 63 // RequiresRangeArgs returns an error if there is not at least min args and at most max args 64 func RequiresRangeArgs(min int, max int) cobra.PositionalArgs { 65 return func(cmd *cobra.Command, args []string) error { 66 if len(args) >= min && len(args) <= max { 67 return nil 68 } 69 return fmt.Errorf( 70 "\"%s\" requires at least %d and at most %d argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s", 71 cmd.CommandPath(), 72 min, 73 max, 74 cmd.CommandPath(), 75 cmd.UseLine(), 76 cmd.Short, 77 ) 78 } 79 } 80 81 // ExactArgs returns an error if there is not the exact number of args 82 func ExactArgs(number int) cobra.PositionalArgs { 83 return func(cmd *cobra.Command, args []string) error { 84 if len(args) == number { 85 return nil 86 } 87 return fmt.Errorf( 88 "\"%s\" requires exactly %d argument(s).\nSee '%s --help'.\n\nUsage: %s\n\n%s", 89 cmd.CommandPath(), 90 number, 91 cmd.CommandPath(), 92 cmd.UseLine(), 93 cmd.Short, 94 ) 95 } 96 }