forked from urfave/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flag_bool.go
87 lines (72 loc) · 1.75 KB
/
flag_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
85
86
87
package cli
import (
"errors"
"strconv"
)
type BoolFlag = FlagBase[bool, BoolConfig, boolValue]
// BoolConfig defines the configuration for bool flags
type BoolConfig struct {
Count *int
}
// boolValue needs to implement the boolFlag internal interface in flag
// to be able to capture bool fields and values
//
// type boolFlag interface {
// Value
// IsBoolFlag() bool
// }
type boolValue struct {
destination *bool
count *int
}
func (cmd *Command) Bool(name string) bool {
if v, ok := cmd.Value(name).(bool); ok {
tracef("bool available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name)
return v
}
tracef("bool NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name)
return false
}
// Below functions are to satisfy the ValueCreator interface
// Create creates the bool value
func (b boolValue) Create(val bool, p *bool, c BoolConfig) Value {
*p = val
if c.Count == nil {
c.Count = new(int)
}
return &boolValue{
destination: p,
count: c.Count,
}
}
// ToString formats the bool value
func (b boolValue) ToString(value bool) string {
return strconv.FormatBool(value)
}
// Below functions are to satisfy the flag.Value interface
func (b *boolValue) Set(s string) error {
v, err := strconv.ParseBool(s)
if err != nil {
err = errors.New("parse error")
return err
}
*b.destination = v
if b.count != nil {
*b.count = *b.count + 1
}
return err
}
func (b *boolValue) Get() interface{} { return *b.destination }
func (b *boolValue) String() string {
if b.destination != nil {
return strconv.FormatBool(*b.destination)
}
return strconv.FormatBool(false)
}
func (b *boolValue) IsBoolFlag() bool { return true }
func (b *boolValue) Count() int {
if b.count != nil {
return *b.count
}
return 0
}