-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_maingroup_test.go
84 lines (67 loc) · 2.13 KB
/
example_maingroup_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
package cmdy_test
import (
"context"
"fmt"
"github.com/ArtProcessors/cmdy"
"github.com/ArtProcessors/cmdy/arg"
)
type mainGroupCommand struct{}
func newMainGroupCommand() cmdy.Command {
return &mainGroupCommand{}
}
func (cmd *mainGroupCommand) Help() cmdy.Help {
return cmdy.Synopsis("Example main group command")
}
func (cmd *mainGroupCommand) Configure(flags *cmdy.FlagSet, args *arg.ArgSet) {}
func (cmd *mainGroupCommand) Run(ctx cmdy.Context) error {
fmt.Fprintf(ctx.Stdout(), "subcommand!\n")
return nil
}
func Example_maingroup() {
// Ignore this, pretend it isn't here.
cmdy.Reset()
// builders allow multiple instances of the command to be created.
mainBuilder := func() cmdy.Command {
// flag values should be scoped to the builder:
var testFlag bool
return cmdy.NewGroup(
"myprog",
cmdy.Builders{
// Add your subcommand builders here. This has the same signature as
// mainBuilder - you can nest cmdy.Groups arbitrarily.
"mycmd": newMainGroupCommand,
},
// Optionally override the default usage:
cmdy.GroupUsage("Usage: yep!"),
// Optionally provide global flags. Flags are left-associative in cmdy, so
// any flag in here must come before the subcommand:
cmdy.GroupFlags(func() *cmdy.FlagSet {
set := cmdy.NewFlagSet()
set.BoolVar(&testFlag, "testflag", false, "test flag")
return set
}),
// Optionally provide global setup code to run before the Group's
// subcommand is created and run:
cmdy.GroupBefore(func(ctx cmdy.Context) error {
fmt.Fprintf(ctx.Stdout(), "before! flag: %v\n", testFlag)
return nil
}),
// Optionally provide global teardown code to run after the Group's
// subcommand is run:
cmdy.GroupAfter(func(ctx cmdy.Context, err error) error {
fmt.Fprintf(ctx.Stdout(), "after! flag: %v\n", testFlag)
// Careful: failing to return the passed in error here will
// swallow the error.
return err
}),
)
}
args := []string{"-testflag", "mycmd"}
if err := cmdy.Run(context.Background(), args, mainBuilder); err != nil {
cmdy.Fatal(err)
}
// Output:
// before! flag: true
// subcommand!
// after! flag: true
}