parseFlag parses the flag with the given name and the given value using the given map of all of the available flags, setting the value in that map corresponding to the flag name accordingly. Setting errNotFound = true causes passing a flag name that is not in allFlags to trigger an error; otherwise,
(name string, value string, allFlags *fields, errNotFound bool)
| 298 | // It is recommended that the [ErrNotFound] and [NoErrNotFound] |
| 299 | // constants be used for the value of errNotFound for clearer code. |
| 300 | func parseFlag(name string, value string, allFlags *fields, errNotFound bool) error { |
| 301 | f, exists := allFlags.ValueByKeyTry(name) |
| 302 | if !exists { |
| 303 | if errNotFound { |
| 304 | return fmt.Errorf("flag name %q not recognized", name) |
| 305 | } |
| 306 | return nil |
| 307 | } |
| 308 | |
| 309 | isBool := reflectx.NonPointerValue(f.Value).Kind() == reflect.Bool |
| 310 | |
| 311 | if isBool { |
| 312 | // check if we have a "no" prefix and set negate based on that |
| 313 | lcnm := strings.ToLower(name) |
| 314 | negate := false |
| 315 | if len(lcnm) > 3 { |
| 316 | if lcnm[:3] == "no_" || lcnm[:3] == "no-" { |
| 317 | negate = true |
| 318 | } else if lcnm[:2] == "no" { |
| 319 | if _, has := allFlags.ValueByKeyTry(lcnm[2:]); has { // e.g., nogui and gui is on list |
| 320 | negate = true |
| 321 | } |
| 322 | } |
| 323 | } |
| 324 | // the value could be explicitly set to a bool value, |
| 325 | // so we check that; if it is not set, it is true |
| 326 | b := true |
| 327 | if value != "" { |
| 328 | var err error |
| 329 | b, err = strconv.ParseBool(value) |
| 330 | if err != nil { |
| 331 | return fmt.Errorf("error parsing bool flag %q: %w", name, err) |
| 332 | } |
| 333 | } |
| 334 | // if we are negating and true (ex: -no-something), or not negating |
| 335 | // and false (ex: -something=false), we are false |
| 336 | if negate && b || !negate && !b { |
| 337 | value = "false" |
| 338 | } else { // otherwise, we are true |
| 339 | value = "true" |
| 340 | } |
| 341 | } |
| 342 | if value == "" { |
| 343 | // got '--flag' but arg was required |
| 344 | return fmt.Errorf("flag %q needs an argument", name) |
| 345 | } |
| 346 | |
| 347 | return setFieldValue(f, value) |
| 348 | } |
| 349 | |
| 350 | // setFieldValue sets the value of the given configuration field |
| 351 | // to the given string argument value. |
no test coverage detected