-
Notifications
You must be signed in to change notification settings - Fork 0
/
option_bool.go
84 lines (72 loc) · 2.3 KB
/
option_bool.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 cliz
import (
"slices"
"strings"
"github.com/hakadoriya/z.go/errorz"
)
type (
// BoolOption is the option for bool value.
BoolOption struct {
// Name is the name of the option.
Name string
// Aliases is the alias names of the option.
Aliases []string
// Env is the environment variable name of the option.
Env string
// Default is the default value of the option.
Default bool
// Required is the required flag of the option.
Required bool
// Description is the description of the option.
Description string
// Hidden is the hidden flag of the option.
Hidden bool
// value is the value of the option.
value *bool
}
)
var _ Option = (*BoolOption)(nil)
func (o *BoolOption) GetName() string { return o.Name }
func (o *BoolOption) GetAliases() []string { return o.Aliases }
func (o *BoolOption) GetEnv() string { return o.Env }
func (o *BoolOption) GetDefault() interface{} { return o.Default }
func (o *BoolOption) IsRequired() bool { return o.Required }
func (o *BoolOption) IsZero() bool { return o.value == nil || !*o.value }
func (o *BoolOption) IsHidden() bool { return o.Hidden }
func (o *BoolOption) GetDescription() string {
if o.Description != "" {
return o.Description
}
return "bool value of " + o.Name
}
func (c *Command) GetOptionBool(name string) (bool, error) {
v, err := c.getOptionBool(name)
if err != nil {
return false, errorz.Errorf("cmd = %s: %w", strings.Join(c.allExecutedCommandNames, " "), err)
}
return v, nil
}
//nolint:cyclop
func (c *Command) getOptionBool(name string) (bool, error) {
if len(c.allExecutedCommandNames) == 0 {
return false, errorz.Errorf("%s: %w", c.Name, ErrNotCalled)
}
// Search the contents of the subcommand in reverse order and prioritize the options of the descendant commands.
for i := range c.SubCommands {
subcmd := c.SubCommands[len(c.SubCommands)-1-i]
v, err := subcmd.getOptionBool(name)
if err == nil {
return v, nil
}
}
for _, opt := range c.Options {
if o, ok := opt.(*BoolOption); ok {
if (o.Name != "" && o.Name == name) || (len(o.Aliases) > 0 && slices.Contains(o.Aliases, name)) || (o.Env != "" && o.Env == name) {
if o.value != nil {
return *o.value, nil
}
}
}
}
return false, errorz.Errorf("option = %s: %w", name, ErrUnknownOption)
}