-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
69 lines (54 loc) · 1.36 KB
/
example_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
// Copyright 2020 Manlio Perillo. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cmd_test
import (
"fmt"
"os"
"github.com/perillo/cmd"
)
var (
main = &cmd.Command{
Name: "example",
UsageLine: "<command> [arguments]",
Long: "example is an example command",
}
child = &cmd.Command{
Name: "child",
UsageLine: "[-v]",
Short: "sub command example",
}
)
func init() {
child.Run = runChild // break initialization loop
}
var verbose = child.Flag.Bool("v", false, "verbose")
func Example() {
// We are going to modify os.Args; make sure to restore it.
defer restore()
// Setup main commands.
main.Commands = []*cmd.Command{child}
// Call Run with a custom os.Args.
os.Args = []string{"example", "child", "-v", "a", "b"}
status := cmd.Run(main)
fmt.Println("exit status:", status)
// Output:
// full command name: "example child"
// -v flag: true
// args: [a b]
// exit status: 0
}
func runChild(c *cmd.Command, args []string) int {
fmt.Printf("full command name: %q\n", c)
fmt.Println("-v flag:", *verbose)
fmt.Println("args:", args)
return cmd.ExitSuccess
}
// restore returns a function that, when called, will restore the global state
// modified during a test.
func restore() func() {
args := os.Args
return func() {
os.Args = args
}
}