| 1 | package cli |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "strconv" |
| 6 | ) |
| 7 | |
| 8 | type BoolFlag = FlagBase[bool, BoolConfig, boolValue] |
| 9 | |
| 10 | // BoolConfig defines the configuration for bool flags |
| 11 | type BoolConfig struct { |
| 12 | Count *int |
| 13 | } |
| 14 | |
| 15 | // boolValue needs to implement the boolFlag internal interface in flag |
| 16 | // to be able to capture bool fields and values |
| 17 | // |
| 18 | // type boolFlag interface { |
| 19 | // Value |
| 20 | // IsBoolFlag() bool |
| 21 | // } |
| 22 | type boolValue struct { |
| 23 | destination *bool |
| 24 | count *int |
| 25 | } |
| 26 | |
| 27 | func (cmd *Command) Bool(name string) bool { |
| 28 | if v, ok := cmd.Value(name).(bool); ok { |
| 29 | tracef("bool available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name) |
| 30 | return v |
| 31 | } |
| 32 | |
| 33 | tracef("bool NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name) |
| 34 | return false |
| 35 | } |
| 36 | |
| 37 | // Below functions are to satisfy the ValueCreator interface |
| 38 | |
| 39 | // Create creates the bool value |
| 40 | func (b boolValue) Create(val bool, p *bool, c BoolConfig) Value { |
| 41 | *p = val |
| 42 | if c.Count == nil { |
| 43 | c.Count = new(int) |
| 44 | } |
| 45 | return &boolValue{ |
| 46 | destination: p, |
| 47 | count: c.Count, |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | // ToString formats the bool value |
| 52 | func (b boolValue) ToString(value bool) string { |
| 53 | b.destination = &value |
| 54 | return b.String() |
| 55 | } |
| 56 | |
| 57 | // Below functions are to satisfy the flag.Value interface |
| 58 | |
| 59 | func (b *boolValue) Set(s string) error { |
| 60 | v, err := strconv.ParseBool(s) |
| 61 | if err != nil { |
| 62 | err = errors.New("parse error") |
| 63 | return err |
| 64 | } |
| 65 | *b.destination = v |
| 66 | if b.count != nil { |
| 67 | *b.count = *b.count + 1 |
| 68 | } |
| 69 | return err |
| 70 | } |
| 71 | |
| 72 | func (b *boolValue) Get() any { return *b.destination } |
| 73 | |
| 74 | func (b *boolValue) String() string { |
| 75 | return strconv.FormatBool(*b.destination) |
| 76 | } |
| 77 | |
| 78 | func (b *boolValue) IsBoolFlag() bool { return true } |