-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathvalidate.go
54 lines (46 loc) · 957 Bytes
/
validate.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
package stdcli
import (
"fmt"
)
type Validator func(c *Context) error
func Args(num int) Validator {
return func(c *Context) error {
if len(c.Args) != num {
return fmt.Errorf("%d %s required", num, plural("arg", num))
}
return nil
}
}
func ArgsBetween(min, max int) Validator {
return func(c *Context) error {
if err := ArgsMin(min)(c); err != nil {
return err
}
if err := ArgsMax(max)(c); err != nil {
return err
}
return nil
}
}
func ArgsMin(min int) Validator {
return func(c *Context) error {
if len(c.Args) < min {
return fmt.Errorf("at least %d %s required", min, plural("arg", min))
}
return nil
}
}
func ArgsMax(max int) Validator {
return func(c *Context) error {
if len(c.Args) > max {
return fmt.Errorf("no more than %d %s expected", max, plural("arg", max))
}
return nil
}
}
func plural(noun string, num int) string {
if num == 1 {
return noun
}
return fmt.Sprintf("%ss", noun)
}