-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
example_dispatch_test.go
43 lines (36 loc) · 966 Bytes
/
example_dispatch_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
package getoptions_test
import (
"context"
"errors"
"fmt"
"os"
"github.com/DavidGamba/go-getoptions"
)
func ExampleGetOpt_Dispatch() {
runFn := func(ctx context.Context, opt *getoptions.GetOpt, args []string) error {
fmt.Println("a, b, c, d")
return nil
}
opt := getoptions.New()
opt.NewCommand("list", "list stuff").SetCommandFn(runFn)
opt.HelpCommand("help", opt.Alias("?"))
remaining, err := opt.Parse([]string{"list"}) // <- argv set to call command
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: %s\n", err)
os.Exit(1)
}
getoptions.Writer = os.Stdout // Print help to stdout instead of stderr for test purpose
err = opt.Dispatch(context.Background(), remaining)
if err != nil {
if errors.Is(err, getoptions.ErrorHelpCalled) {
os.Exit(1)
}
fmt.Fprintf(os.Stderr, "ERROR: %s\n", err)
if errors.Is(err, getoptions.ErrorParsing) {
fmt.Fprintf(os.Stderr, "\n"+opt.Help())
}
os.Exit(1)
}
// Output:
// a, b, c, d
}