/
validate.go
81 lines (70 loc) · 1.66 KB
/
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package command
import (
"fmt"
)
type ValidateFunc func(ctx *Context, args []string) error
type Validates []ValidateFunc
func NewValidats() Validates {
return nil
}
func (v Validates) Finish() ValidateFunc {
return func(ctx *Context, args []string) error {
for _, c := range v {
if err := c(ctx, args); err != nil {
return err
}
}
return nil
}
}
func (v Validates) Append(f ValidateFunc) Validates {
v = append(v, f)
return v
}
func (v Validates) NumArgs(n int) Validates {
return v.Append(func(ctx *Context, args []string) error {
if len(args) != n {
return fmt.Errorf("expect %d arguments, got %d", n, len(args))
}
return nil
})
}
func (v Validates) MaxArgs(n int) Validates {
return v.Append(func(ctx *Context, args []string) error {
if len(args) > n {
return fmt.Errorf("expect max %d arguments, got %d", n, len(args))
}
return nil
})
}
func (v Validates) MinArgs(n int) Validates {
return v.Append(func(ctx *Context, args []string) error {
if len(args) < n {
return fmt.Errorf("expect minimum %d arguments, got %d", n, len(args))
}
return nil
})
}
func (v Validates) NumArgsChoice(n ...int) Validates {
return v.Append(func(ctx *Context, args []string) error {
for _, v := range n {
if v == len(args) {
return nil
}
}
return fmt.Errorf("expect %+v arguments, got %d", n, len(args))
})
}
func (v Validates) Choices(pos int, choices []string) Validates {
return v.Append(func(ctx *Context, args []string) error {
if len(args) <= pos {
return nil
}
for _, c := range choices {
if c == args[pos] {
return nil
}
}
return fmt.Errorf("%d-th arguments should be one of %+v", pos+1, choices)
})
}