/
flag_bool.go
80 lines (66 loc) · 1.5 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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package flag
import (
"os"
"strconv"
"github.com/posener/complete"
)
// -- BoolVar and boolValue.
type BoolVar struct {
Name string
Aliases []string
Usage string
Default bool
Hidden bool
EnvVar string
Target *bool
Completion complete.Predictor
SetHook func(val bool)
}
func (f *Set) BoolVar(i *BoolVar) {
def := i.Default
if v, exist := os.LookupEnv(i.EnvVar); exist {
if b, err := strconv.ParseBool(v); err == nil {
def = b
}
}
f.VarFlag(&VarFlag{
Name: i.Name,
Aliases: i.Aliases,
Usage: i.Usage,
Default: strconv.FormatBool(i.Default),
EnvVar: i.EnvVar,
Value: newBoolValue(i, def, i.Target, i.Hidden),
Completion: i.Completion,
})
}
type boolValue struct {
v *BoolVar
hidden bool
target *bool
}
func newBoolValue(v *BoolVar, def bool, target *bool, hidden bool) *boolValue {
*target = def
return &boolValue{
v: v,
hidden: hidden,
target: target,
}
}
func (b *boolValue) Set(s string) error {
v, err := strconv.ParseBool(s)
if err != nil {
return err
}
*b.target = v
if b.v.SetHook != nil {
b.v.SetHook(v)
}
return nil
}
func (b *boolValue) Get() interface{} { return *b.target }
func (b *boolValue) String() string { return strconv.FormatBool(*b.target) }
func (b *boolValue) Example() string { return "" }
func (b *boolValue) Hidden() bool { return b.hidden }
func (b *boolValue) IsBoolFlag() bool { return true }