Debian Codegraph @

flag_bool_with_inverse.go

raw symbols SCIP
1 package cli
2
3 import (
4 "context"
5 "fmt"
6 "slices"
7 "strings"
8 )
9
10 var DefaultInverseBoolPrefix = "no-"
11
12 type BoolWithInverseFlag struct {
13 Name string `json:"name"` // name of the flag
14 Category string `json:"category"` // category of the flag, if any
15 DefaultText string `json:"defaultText"` // default text of the flag for usage purposes
16 HideDefault bool `json:"hideDefault"` // whether to hide the default value in output
17 Usage string `json:"usage"` // usage string for help output
18 Sources ValueSourceChain `json:"-"` // sources to load flag value from
19 Required bool `json:"required"` // whether the flag is required or not
20 Hidden bool `json:"hidden"` // whether to hide the flag in help output
21 Local bool `json:"local"` // whether the flag needs to be applied to subcommands as well
22 Value bool `json:"defaultValue"` // default value for this flag if not set by from any source
23 Destination *bool `json:"-"` // destination pointer for value when set
24 Aliases []string `json:"aliases"` // Aliases that are allowed for this flag
25 TakesFile bool `json:"takesFileArg"` // whether this flag takes a file argument, mainly for shell completion purposes
26 Action func(context.Context, *Command, bool) error `json:"-"` // Action callback to be called when flag is set
27 OnlyOnce bool `json:"onlyOnce"` // whether this flag can be duplicated on the command line
28 Validator func(bool) error `json:"-"` // custom function to validate this flag value
29 ValidateDefaults bool `json:"validateDefaults"` // whether to validate defaults or not
30 Config BoolConfig `json:"config"` // Additional/Custom configuration associated with this flag type
31 InversePrefix string `json:"invPrefix"` // The prefix used to indicate a negative value. Default: `env` becomes `no-env`
32
33 // unexported fields for internal use
34 count int // number of times the flag has been set
35 hasBeenSet bool // whether the flag has been set from env or file
36 applied bool // whether the flag has been applied to a flag set already
37 value Value // value representing this flag's value
38 pset bool
39 nset bool
40 }
41
42 func (bif *BoolWithInverseFlag) IsSet() bool {
43 return bif.hasBeenSet
44 }
45
46 func (bif *BoolWithInverseFlag) Get() any {
47 return bif.value.Get()
48 }
49
50 func (bif *BoolWithInverseFlag) RunAction(ctx context.Context, cmd *Command) error {
51 if bif.Action != nil {
52 return bif.Action(ctx, cmd, bif.Get().(bool))
53 }
54
55 return nil
56 }
57
58 func (bif *BoolWithInverseFlag) IsLocal() bool {
59 return bif.Local
60 }
61
62 func (bif *BoolWithInverseFlag) inversePrefix() string {
63 if bif.InversePrefix == "" {
64 bif.InversePrefix = DefaultInverseBoolPrefix
65 }
66
67 return bif.InversePrefix
68 }
69
70 func (bif *BoolWithInverseFlag) PreParse() error {
71 count := bif.Config.Count
72 if count == nil {
73 count = &bif.count
74 }
75 dest := bif.Destination
76 if dest == nil {
77 dest = new(bool)
78 }
79 *dest = bif.Value
80 bif.value = &boolValue{
81 destination: dest,
82 count: count,
83 }
84
85 // Validate the given default or values set from external sources as well
86 if bif.Validator != nil && bif.ValidateDefaults {
87 if err := bif.Validator(bif.value.Get().(bool)); err != nil {
88 return err
89 }
90 }
91 bif.applied = true
92 return nil
93 }
94
95 func (bif *BoolWithInverseFlag) PostParse() error {
96 tracef("postparse (flag=%[1]q)", bif.Name)
97
98 if !bif.hasBeenSet {
99 if val, source, found := bif.Sources.LookupWithSource(); found {
100 if val == "" {
101 val = "false"
102 }
103 if err := bif.Set(bif.Name, val); err != nil {
104 return fmt.Errorf(
105 "could not parse %[1]q as %[2]T value from %[3]s for flag %[4]s: %[5]s",
106 val, bif.Value, source, bif.Name, err,
107 )
108 }
109
110 bif.hasBeenSet = true
111 }
112 }
113
114 return nil
115 }
116
117 func (bif *BoolWithInverseFlag) Set(name, val string) error {
118 if bif.count > 0 && bif.OnlyOnce {
119 return fmt.Errorf("can't duplicate this flag")
120 }
121
122 bif.hasBeenSet = true
123
124 if slices.Contains(append([]string{bif.Name}, bif.Aliases...), name) {
125 if bif.nset {
126 return fmt.Errorf("cannot set both flags `--%s` and `--%s`", bif.Name, bif.inversePrefix()+bif.Name)
127 }
128 if err := bif.value.Set(val); err != nil {
129 return err
130 }
131 bif.pset = true
132 } else {
133 if bif.pset {
134 return fmt.Errorf("cannot set both flags `--%s` and `--%s`", bif.Name, bif.inversePrefix()+bif.Name)
135 }
136 if err := bif.value.Set("false"); err != nil {
137 return err
138 }
139 bif.nset = true
140 }
141
142 if bif.Validator != nil {
143 return bif.Validator(bif.value.Get().(bool))
144 }
145 return nil
146 }
147
148 func (bif *BoolWithInverseFlag) Names() []string {
149 names := append([]string{bif.Name}, bif.Aliases...)
150
151 for _, name := range names {
152 names = append(names, bif.inversePrefix()+name)
153 }
154
155 return names
156 }
157
158 func (bif *BoolWithInverseFlag) IsRequired() bool {
159 return bif.Required
160 }
161
162 func (bif *BoolWithInverseFlag) IsVisible() bool {
163 return !bif.Hidden
164 }
165
166 // String implements the standard Stringer interface.
167 //
168 // Example for BoolFlag{Name: "env"}
169 // --[no-]env (default: false)
170 //
171 // Example for BoolFlag{Name: "env", Aliases: []string{"e"}}
172 // --[no-]env, -e (default: false)
173 func (bif *BoolWithInverseFlag) String() string {
174 out := FlagStringer(bif)
175
176 i := strings.Index(out, "\t")
177
178 prefix := "--"
179
180 // single character flags are prefixed with `-` instead of `--`
181 if len(bif.Name) == 1 {
182 prefix = "-"
183 }
184
185 // Guard against a FlagStringer that returns a string without a tab (e.g.
186 // a custom stringer or the default stringer when the flag does not
187 // implement DocGenerationFlag). In that case treat the entire output as
188 // the tab-delimited suffix so the slice never goes out of bounds.
189 if i < 0 {
190 i = 0
191 }
192
193 var aliasParts []string
194 for _, alias := range bif.Aliases {
195 aPrefix := "--"
196 if len(alias) == 1 {
197 aPrefix = "-"
198 }
199 aliasParts = append(aliasParts, aPrefix+alias)
200 }
201
202 names := fmt.Sprintf("%s[%s]%s", prefix, bif.inversePrefix(), bif.Name)
203 if len(aliasParts) > 0 {
204 names = names + ", " + strings.Join(aliasParts, ", ")
205 }
206
207 return fmt.Sprintf("%s%s", names, out[i:])
208 }
209
210 // IsBoolFlag returns whether the flag doesn't need to accept args
211 func (bif *BoolWithInverseFlag) IsBoolFlag() bool {
212 return true
213 }
214
215 // Count returns the number of times this flag has been invoked
216 func (bif *BoolWithInverseFlag) Count() int {
217 return bif.count
218 }
219
220 // GetDefaultText returns the default text for this flag
221 func (bif *BoolWithInverseFlag) GetDefaultText() string {
222 if bif.Required {
223 return bif.DefaultText
224 }
225 return boolValue{}.ToString(bif.Value)
226 }
227
228 // GetCategory returns the category of the flag
229 func (bif *BoolWithInverseFlag) GetCategory() string {
230 return bif.Category
231 }
232
233 func (bif *BoolWithInverseFlag) SetCategory(c string) {
234 bif.Category = c
235 }
236
237 // GetUsage returns the usage string for the flag
238 func (bif *BoolWithInverseFlag) GetUsage() string {
239 return bif.Usage
240 }
241
242 // GetEnvVars returns the env vars for this flag
243 func (bif *BoolWithInverseFlag) GetEnvVars() []string {
244 return bif.Sources.EnvKeys()
245 }
246
247 // GetValue returns the flags value as string representation and an empty
248 // string if the flag takes no value at all.
249 func (bif *BoolWithInverseFlag) GetValue() string {
250 return ""
251 }
252
253 func (bif *BoolWithInverseFlag) TakesValue() bool {
254 return false
255 }
256
257 // IsDefaultVisible returns true if the flag is not hidden, otherwise false
258 func (bif *BoolWithInverseFlag) IsDefaultVisible() bool {
259 return !bif.HideDefault
260 }
261
262 // TypeName is used for stringify/docs. For bool its a no-op
263 func (bif *BoolWithInverseFlag) TypeName() string {
264 return "bool"
265 }
266
267 func (bif *BoolWithInverseFlag) SchemaType() string {
268 return "boolean"
269 }
270
271 func (bif *BoolWithInverseFlag) SchemaItemsType() string {
272 return ""
273 }