-
Notifications
You must be signed in to change notification settings - Fork 0
/
boolSetter.go
87 lines (78 loc) · 2.16 KB
/
boolSetter.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 psetter
import (
"errors"
"fmt"
"strconv"
)
// Bool is used to set boolean flags
//
// The Invert flag is used to invert the normal meaning of a boolean parameter.
// It is useful where you want to have a parameter of the form 'dont-xxx' but
// use it to set the value of a bool variable (default value: true) such as
// 'xxx' which you can then test by saying:
//
// if xxx { doXXX() }
//
// rather than having to set the value of a variable which you would have to
// call dontXXX and then test by saying:
//
// if !dontXXX { doXXX() }
//
// The benefit is that you can avoid the ugly (and error prone) double
// negative.
type Bool struct {
ValueReqOptional
// Value must be set, the program will panic if not. This is the boolean
// that the setter is setting.
Value *bool
// Invert reverses the normal meaning of the boolean parameter so that
// the Value will be set to false when no value is given or the negation
// of the given value when one is given.
Invert bool
}
// Set sets the parameter value to true
func (s Bool) Set(_ string) error {
if s.Invert {
*s.Value = false
} else {
*s.Value = true
}
return nil
}
// SetWithVal should be called when a value is given for the parameter
func (s Bool) SetWithVal(_, val string) error {
b, err := strconv.ParseBool(val)
if err != nil {
return errors.New(
"cannot interpret '" +
val +
"' as either true or false")
}
if s.Invert {
*s.Value = !b
} else {
*s.Value = b
}
return nil
}
// AllowedValues returns a description of the allowed values.
func (s Bool) AllowedValues() string {
return "none (which will be taken as 'true')" +
" or some value that can be interpreted as true or false." +
" The value must be given after an '='," +
" not as a following value, as this is optional"
}
// CurrentValue returns the current setting of the parameter value
func (s Bool) CurrentValue() string {
if s.Invert {
return fmt.Sprintf("%v", !*s.Value)
}
return fmt.Sprintf("%v", *s.Value)
}
// CheckSetter panics if the setter has not been properly created - if the
// Value is nil
func (s Bool) CheckSetter(name string) {
if s.Value == nil {
panic(NilValueMessage(name, "psetter.Bool"))
}
}