Repository navigation
Expand file tree
/
Copy pathexample_type_test.go
More file actions
73 lines (65 loc) · 2.31 KB
/
Copy pathexample_type_test.go
File metadata and controls
73 lines (65 loc) · 2.31 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
// This example demonstrates how a custom struct type may be used to encapsulate
// the behavior of a single command.
package climux
import (
"context"
"fmt"
)
// exampleCommand encapsulates the configuration and handler for a CLI
// command as a custom type.
// It collects the value of each flag as a struct field.
// Command types should be very fast to initialize, ideally initialized with their zero-value.
type exampleCommand struct {
Species string
GopherType string
}
// Command returns the CLI configuration of the example command as a
// *Command.
func (c *exampleCommand) Command() *Command {
return NewCommand("example", "An example CLI program").
HelpFlag().
Flags(
String("species", "the species we are studying").Default("Gopher").Bind(&c.Species),
String("gopher_type", "the variety of gopher").Default("Pocket").Bind(&c.GopherType),
).
HandleFunc(c.Run)
}
// Run handles calls to this command from the command line.
func (c *exampleCommand) Run(ctx context.Context, inv *Invocation) error {
fmt.Fprintf(inv.Stdout, "%s is a variety of species %s\n", c.GopherType, c.Species)
return nil
}
// ExampleCommand is a *Command built from a global instance of the
// exampleCommand type so that its parsed flag values can be accessed from
// other commands. This is an optional alternative to defining flag variables
// individually in the global scope.
var ExampleCommand = (&exampleCommand{}).Command()
func Example_customTypes() {
ctx := context.Background()
fmt.Println("+ example --help")
Run(ctx, ExampleCommand, WithArgs("--help"))
// Most programs will call the following from main:
//
// func main() {
// ctx, stop := climux.NotifyContext(context.Background())
// defer stop()
// os.Exit(climux.Run(ctx, ExampleCommand))
// }
//
fmt.Println()
fmt.Println("+ example --gopher_type 'Goldman's pocket gopher'")
Run(ctx, ExampleCommand, WithArgs("--gopher_type", "Goldman's pocket gopher"))
// Output:
// + example --help
// Usage: example [OPTIONS]
//
// An example CLI program
//
// Options:
// -h, --help Show this help message and exit
// --species the species we are studying
// --gopher_type the variety of gopher
//
// + example --gopher_type 'Goldman's pocket gopher'
// Goldman's pocket gopher is a variety of species Gopher
}