-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparseflags_test.go
122 lines (102 loc) · 2.51 KB
/
parseflags_test.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package parseflags
import (
"fmt"
"strconv"
)
func ExampleCreateFlagset() {
testConfig := struct {
A int64 `flag:"alpha" description:"an int value"`
B []string `flag:"beta" description:"some strings"`
C bool `flag:"gamma" hidden:"true"`
}{
B: []string{"defaultvalue"},
}
args := []string{"--alpha", "10", "--beta", "b", "--beta", "b2", "--gamma"}
flags := CreateFlagset(&testConfig)
flags.Parse(args)
fmt.Println(testConfig.A)
fmt.Println(testConfig.B)
fmt.Println(testConfig.C)
//Output:
//10
//[b b2]
//true
}
type Convertible int
func (c *Convertible) Set(val string) error {
ival, err := strconv.Atoi(val)
if err == nil {
*c = Convertible(ival)
}
return err
}
func ExampleConvertible() {
testConfig := struct {
A Convertible `flag:"alpha" description:"an int value with custom converter"`
B []Convertible `flag:"beta" description:"a slice of an int value with custom converter"`
}{
A: Convertible(1),
}
args := []string{"--alpha", "10", "--beta", "5"}
flags := CreateFlagset(&testConfig)
flags.Parse(args)
fmt.Println(testConfig.A)
fmt.Println(testConfig.B)
//Output:
//10
//[5]
}
type CustomConvertible int
func ExampleConverter() {
testConfig := struct {
A CustomConvertible `flag:"alpha" description:"an int value with custom converter"`
B []CustomConvertible `flag:"beta" description:"a slice of an int value with custom converter"`
}{
A: CustomConvertible(1),
}
RegisterConverter(CustomConvertible(0), func(val string) (interface{}, error) {
ival, err := strconv.Atoi(val)
if err == nil {
return CustomConvertible(ival), nil
}
return nil, err
})
args := []string{"--alpha", "10", "--beta", "5"}
flags := CreateFlagset(&testConfig)
flags.Parse(args)
fmt.Println(testConfig.A)
fmt.Println(testConfig.B)
//Output:
//10
//[5]
}
func ExampleRecurseFlagset() {
testConfig := struct {
A int64 `flag:"alpha" description:"an int value"`
SubComponentConfig struct {
B []string `flag:"beta" description:"some strings"`
} `recurse:"true"`
}{}
args := []string{"--alpha", "10", "--beta", "b"}
flags := CreateFlagset(&testConfig)
flags.Parse(args)
fmt.Println(testConfig.A)
fmt.Println(testConfig.SubComponentConfig.B)
//Output:
//10
//[b]
}
func ExampleNoOptDef() {
testConfig := struct {
A int64 `flag:"alpha" nooptdef:"1024"`
B int64 `flag:"beta"`
}{}
args := []string{"--alpha", "--beta"}
flags := CreateFlagset(&testConfig)
flags.Parse(args)
fmt.Println(testConfig.A)
fmt.Println(testConfig.B)
//Output:
//10
//1024
}