-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathcmd_validator.go
More file actions
63 lines (53 loc) · 1.41 KB
/
Copy pathcmd_validator.go
File metadata and controls
63 lines (53 loc) · 1.41 KB
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
62
63
package utils
import (
"errors"
"fmt"
"github.com/spf13/cobra"
)
// Validates if the number of args passed to a command is exactly same as that required
func ExactArgs(count int) cobra.PositionalArgs {
return func(cmd *cobra.Command, args []string) error {
arg := "argument"
if count > 1 {
arg = "arguments"
}
errorMsg := fmt.Sprintf("`%s` requires exactly %d %s. Got %d. Please see `%s --help` for the supported flags and their usage.",
cmd.CommandPath(),
count,
arg,
len(args),
cmd.CommandPath())
if len(args) != count {
return errors.New(errorMsg)
}
return nil
}
}
func MaxNArgs(count int) cobra.PositionalArgs {
return func(cmd *cobra.Command, args []string) error {
arg := "argument"
if count > 1 {
arg = "arguments"
}
errorMsg := fmt.Sprintf("`%s` requires maximum %d %s. Got %d. Please see `%s --help` for the supported flags and their usage.",
cmd.CommandPath(),
count,
arg,
len(args),
cmd.CommandPath())
if len(args) > count {
return errors.New(errorMsg)
}
return nil
}
}
// Validates if there is any arg passed to a command which doesn't require any
func NoArgs(cmd *cobra.Command, args []string) error {
errorMsg := fmt.Sprintf("`%s` does not require any argument. Please see `%s --help` for the supported flags and their usage.",
cmd.CommandPath(),
cmd.CommandPath())
if len(args) > 0 {
return errors.New(errorMsg)
}
return nil
}