-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathexample_explicit_test.go
84 lines (75 loc) · 2.67 KB
/
example_explicit_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
// Copyright 2016 Bob Ziuchkovski. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package writ_test
import (
"github.com/bobziuchkovski/writ"
"os"
"runtime"
)
type Config struct {
help bool
verbosity int
bootloader string
}
// This example demonstrates explicit Command and Option creation,
// along with explicit option grouping. It checks the host platform
// and dynamically adds a --bootloader option if the example is run on
// Linux. The same result could be achieved by using writ.New() to
// construct a Command, and then adding the platform-specific option
// to the resulting Command directly.
func Example_explicit() {
config := &Config{}
cmd := &writ.Command{Name: "explicit"}
cmd.Help.Usage = "Usage: explicit [OPTION]... [ARG]..."
cmd.Options = []*writ.Option{
{
Names: []string{"h", "help"},
Description: "Display this help text and exit",
Decoder: writ.NewFlagDecoder(&config.help),
Flag: true,
},
{
Names: []string{"v"},
Description: "Increase verbosity; may be specified more than once",
Decoder: writ.NewFlagAccumulator(&config.verbosity),
Flag: true,
Plural: true,
},
}
// Note the explicit option grouping. Using writ.New(), a single option group is
// created for all options/flags that have descriptions. Without writ.New(), we
// need to create the OptionGroup(s) ourselves.
general := cmd.GroupOptions("help", "v")
general.Header = "General Options:"
cmd.Help.OptionGroups = append(cmd.Help.OptionGroups, general)
// Dynamically add --bootloader on Linux
if runtime.GOOS == "linux" {
cmd.Options = append(cmd.Options, &writ.Option{
Names: []string{"bootloader"},
Description: "Use the specified bootloader (grub, grub2, or lilo)",
Decoder: writ.NewOptionDecoder(&config.bootloader),
Placeholder: "NAME",
})
platform := cmd.GroupOptions("bootloader")
platform.Header = "Platform Options:"
cmd.Help.OptionGroups = append(cmd.Help.OptionGroups, platform)
}
// Decode the options
_, _, err := cmd.Decode(os.Args[1:])
if err != nil || config.help {
cmd.ExitHelp(err)
}
// Help Output, Linux:
// General Options:
// -h, --help Display this help text and exit
// -v Increase verbosity; may be specified more than once
//
// Platform Options:
// --bootloader=NAME Use the specified bootloader (grub, grub2, or lilo)
//
// Help Output, other platforms:
// General Options:
// -h, --help Display this help text and exit
// -v Increase verbosity; may be specified more than once
}