Debian Codegraph @

config/optbool.go

raw
1 package config
2
3 import (
4 "strconv"
5 "strings"
6 )
7
8 // OptBool is a tri-state boolean: unset, explicitly false, or explicitly true.
9 // Its zero value (OptBoolUnset) means the setting was not specified, which
10 // allows merge logic based on reflect.Value.IsZero to skip unset fields while
11 // still letting an explicit "false" override a previously set "true".
12 type OptBool byte
13
14 const (
15 // OptBoolUnset indicates the setting was not specified.
16 OptBoolUnset OptBool = iota
17 // OptBoolFalse indicates the setting was explicitly set to false.
18 OptBoolFalse
19 // OptBoolTrue indicates the setting was explicitly set to true.
20 OptBoolTrue
21 )
22
23 // NewOptBool converts a plain bool into an OptBool.
24 func NewOptBool(v bool) OptBool {
25 if v {
26 return OptBoolTrue
27 }
28 return OptBoolFalse
29 }
30
31 // IsTrue returns whether the value is explicitly true.
32 func (o OptBool) IsTrue() bool { return o == OptBoolTrue }
33
34 // IsSet returns whether the value was explicitly specified (true or false).
35 func (o OptBool) IsSet() bool { return o != OptBoolUnset }
36
37 func (o OptBool) String() string {
38 switch o {
39 case OptBoolTrue:
40 return "true"
41 case OptBoolFalse:
42 return "false"
43 default:
44 return "unset"
45 }
46 }
47
48 // FormatBool returns the strconv-formatted value. Only meaningful when IsSet.
49 func (o OptBool) FormatBool() string {
50 return strconv.FormatBool(o.IsTrue())
51 }
52
53 // parseConfigBool mirrors upstream Git's git_parse_maybe_bool: it
54 // accepts true/yes/on (→ OptBoolTrue) and false/no/off (→
55 // OptBoolFalse) case-insensitively, plus any decimal integer (zero
56 // → OptBoolFalse, non-zero → OptBoolTrue). Empty or otherwise
57 // unrecognised values return OptBoolUnset, leaving the caller's
58 // platform default in place. The empty-string handling is the only
59 // intentional divergence from upstream, which returns false for
60 // empty: in our unmarshalCore caller, an empty value means the key
61 // is unset and the platform default should apply.
62 //
63 // Reference: upstream Git git_parse_maybe_bool_text at parse.c
64 // L157-L173 and git_parse_maybe_bool at parse.c L174-L182 in tag
65 // v2.54.0[1].
66 //
67 // [1]: https://github.com/git/git/blob/v2.54.0/parse.c#L157-L182
68 func parseConfigBool(v string) OptBool {
69 switch strings.ToLower(v) {
70 case "true", "yes", "on":
71 return OptBoolTrue
72 case "false", "no", "off":
73 return OptBoolFalse
74 }
75 if i, err := strconv.Atoi(v); err == nil {
76 if i != 0 {
77 return OptBoolTrue
78 }
79 return OptBoolFalse
80 }
81 return OptBoolUnset
82 }