-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathargs.go
69 lines (64 loc) · 1.67 KB
/
args.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
package subcmd
import (
"fmt"
"strconv"
)
// ArgsStr are string positional arguments. If it is created with cap > 0, it will be used to define
// the number of required arguments.
//
// Usage
//
// To get a list of arbitrary number of arguments:
//
// root := subcmd.Root()
//
// var subcmd.ArgsStr args
// root.ArgsVar(&args, "[arg...]", "list of arguments")
//
// To get a list of specific number of arguments:
//
// root := subcmd.Root()
//
// args := make(subcmd.ArgsStr, 3)
// root.ArgsVar(&args, "[arg1] [arg2] [arg3]", "list of 3 arguments")
type ArgsStr []string
func (a *ArgsStr) Set(args []string) error {
if cap(*a) > 0 && len(args) != cap(*a) {
return fmt.Errorf("required %d positional args, got %v", cap(*a), args)
}
*a = args
return nil
}
// ArgsInt are int positional arguments. If it is created with cap > 0, it will be used to define
// the number of required arguments.
//
// Usage
//
// To get a list of arbitrary number of integers:
//
// root := subcmd.Root()
//
// var subcmd.ArgsInt args
// root.ArgsVar(&args, "[int...]", "list of integer args")
//
// To get a list of specific number of integers:
//
// root := subcmd.Root()
//
// args := make(subcmd.ArgsInt, 3)
// root.ArgsVar(&args, "[int1] [int2] [int3]", "list of 3 integers")
type ArgsInt []int
func (a *ArgsInt) Set(args []string) error {
if cap(*a) > 0 && len(args) != cap(*a) {
return fmt.Errorf("required %d positional args, got %v", cap(*a), args)
}
*a = (*a)[:0] // Reset length to 0.
for i, arg := range args {
v, err := strconv.Atoi(arg)
if err != nil {
return fmt.Errorf("invalid int positional argument at position %d with value %v", i, arg)
}
*a = append(*a, v)
}
return nil
}