-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
127 lines (98 loc) · 2.35 KB
/
example_test.go
File metadata and controls
127 lines (98 loc) · 2.35 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
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
123
124
125
126
127
package clip_test
import (
"fmt"
"os"
"github.com/codemodus/clip"
)
func Example() {
var (
globalCnf = newGlobalConf()
printCnf = newPrintConf("print")
otherCnf = newOtherConf("other")
)
cs := clip.NewCommandSet(
clip.NewCommand(printCnf.flagSet, runPrintFunc(printCnf, globalCnf), nil),
clip.NewCommand(otherCnf.flagSet, runOtherFunc(otherCnf), nil),
)
app := clip.New("myapp", globalCnf.flagSet, cs)
// emulate cli command 'myapp -v print -msg="hello, world"'
os.Args = []string{"myapp", "-v", "print", "-msg=hello, world"}
if err := app.Parse(os.Args); err != nil {
handleError(app.UsageLongHelp(err)) // return? print? exit?
}
if err := app.Run(); err != nil {
handleError(err) // return? print? exit?
}
// Output:
// hello, world (global verbosity is enabled)
}
func ExampleHandlerFunc() {
var runPrint clip.HandlerFunc
var runAdvPrint clip.HandlerFunc
runPrint = func() error {
_, err := fmt.Println("hello, example")
return err
}
runAdvPrintFunc := func(msg string, verbosity bool) func() error {
return func() error {
_, err := fmt.Printf("%s (verbosity = %t)\n", msg, verbosity)
return err
}
}
runAdvPrint = runAdvPrintFunc("hello, again", true)
runPrint()
runAdvPrint()
// Output:
// hello, example
// hello, again (verbosity = true)
}
type globalConf struct {
flagSet *clip.FlagSet
verbose bool
}
func newGlobalConf() *globalConf {
c := globalConf{
flagSet: clip.NewFlagSet("global"),
}
c.flagSet.BoolVar(&c.verbose, "v", c.verbose, "enable verbosity")
return &c
}
type printConf struct {
flagSet *clip.FlagSet
msg string
}
func newPrintConf(name string) *printConf {
c := printConf{
flagSet: clip.NewFlagSet(name),
msg: "default message",
}
c.flagSet.StringVar(&c.msg, "msg", c.msg, "message to print")
return &c
}
type otherConf struct {
flagSet *clip.FlagSet
file string
}
func newOtherConf(name string) *otherConf {
c := otherConf{
flagSet: clip.NewFlagSet(name),
file: "test_data",
}
return &c
}
func runPrintFunc(cnf *printConf, gCnf *globalConf) func() error {
return func() error {
stts := "disabled"
if gCnf.verbose {
stts = "enabled"
}
_, err := fmt.Printf("%s (global verbosity is %s)\n", cnf.msg, stts)
return err
}
}
func runOtherFunc(cnf *otherConf) func() error {
return func() error {
return nil
}
}
func handleError(err error) {}