/
required.go
61 lines (55 loc) · 1.51 KB
/
required.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package cli
import (
"fmt"
"github.com/spf13/cobra"
)
// NoArgs checks that the command is not passed any parameters
func NoArgs(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return nil
}
return fmt.Errorf("unexpected argument: %s\nSee '%s --help'", args[0], cmd.CommandPath())
}
// ExactArgs returns an error if the exact number of args are not passed
func ExactArgs(num int) func(cmd *cobra.Command, args []string) error {
return func(cmd *cobra.Command, args []string) error {
if len(args) == num {
return nil
}
return fmt.Errorf(
"\"%s\" requires exactly %d argument(s).\nSee '%s --help'",
cmd.CommandPath(),
num,
cmd.CommandPath(),
)
}
}
// AtLeastArgs returns an error if the min number of args are not passed
func AtLeastArgs(min int) func(cmd *cobra.Command, args []string) error {
return func(cmd *cobra.Command, args []string) error {
if len(args) >= min {
return nil
}
return fmt.Errorf(
"\"%s\" requires at least %d argument(s).\nSee '%s --help'",
cmd.CommandPath(),
min,
cmd.CommandPath(),
)
}
}
// RangeArgs returns an error if the min and max number of args are not passed
func RangeArgs(min int, max int) func(cmd *cobra.Command, args []string) error {
return func(cmd *cobra.Command, args []string) error {
if len(args) >= min && len(args) <= max {
return nil
}
return fmt.Errorf(
"\"%s\" requires at least %d argument(s) and at most %d argument(s).\nSee '%s --help'",
cmd.CommandPath(),
min,
max,
cmd.CommandPath(),
)
}
}