setFieldValue sets the value of the given configuration field to the given string argument value.
(f *field, value string)
| 350 | // setFieldValue sets the value of the given configuration field |
| 351 | // to the given string argument value. |
| 352 | func setFieldValue(f *field, value string) error { |
| 353 | nptyp := reflectx.NonPointerType(f.Value.Type()) |
| 354 | vk := nptyp.Kind() |
| 355 | switch { |
| 356 | // TODO: more robust parsing of maps and slices |
| 357 | case vk == reflect.Map: |
| 358 | strs := strings.Split(value, ",") |
| 359 | mval := map[string]string{} |
| 360 | for _, str := range strs { |
| 361 | k, v, found := strings.Cut(str, "=") |
| 362 | if !found { |
| 363 | return fmt.Errorf("missing key-value pair for setting map flag %q from flag value %q (element %q has no %q)", f.Names[0], value, str, "=") |
| 364 | } |
| 365 | mval[k] = v |
| 366 | } |
| 367 | err := reflectx.CopyMapRobust(f.Value.Interface(), mval) |
| 368 | if err != nil { |
| 369 | return fmt.Errorf("unable to set map flag %q from flag value %q: %w", f.Names[0], value, err) |
| 370 | } |
| 371 | case vk == reflect.Slice: |
| 372 | err := reflectx.CopySliceRobust(f.Value.Interface(), strings.Split(value, ",")) |
| 373 | if err != nil { |
| 374 | return fmt.Errorf("unable to set slice flag %q from flag value %q: %w", f.Names[0], value, err) |
| 375 | } |
| 376 | default: |
| 377 | // initialize nil fields to prevent panics |
| 378 | // (don't do for maps and slices, as new doesn't work for them) |
| 379 | if f.Value.IsNil() { |
| 380 | f.Value.Set(reflect.New(nptyp)) |
| 381 | } |
| 382 | err := reflectx.SetRobust(f.Value.Interface(), value) // overkill but whatever |
| 383 | if err != nil { |
| 384 | return fmt.Errorf("error setting set flag %q from flag value %q: %w", f.Names[0], value, err) |
| 385 | } |
| 386 | } |
| 387 | return nil |
| 388 | } |
| 389 | |
| 390 | // addAllCases adds all string cases (kebab-case, snake_case, etc) |
| 391 | // of the given field with the given name to the given set of flags. |
no test coverage detected