MCPcopy Create free account
hub / github.com/cogentcore/core / setFieldValue

Function setFieldValue

cli/args.go:352–388  ·  view source on GitHub ↗

setFieldValue sets the value of the given configuration field to the given string argument value.

(f *field, value string)

Source from the content-addressed store, hash-verified

350// setFieldValue sets the value of the given configuration field
351// to the given string argument value.
352func 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.

Callers 2

parseFlagFunction · 0.85
addFlagsFunction · 0.85

Calls 12

NonPointerTypeFunction · 0.92
CopyMapRobustFunction · 0.92
CopySliceRobustFunction · 0.92
SetRobustFunction · 0.92
KindMethod · 0.80
SplitMethod · 0.80
TypeMethod · 0.65
CutMethod · 0.65
ErrorfMethod · 0.65
SetMethod · 0.65
NewMethod · 0.65
IsNilMethod · 0.45

Tested by

no test coverage detected