assignFieldMapping verifies that field mapping has been set once, but only once (either in cfg or comp). Then if that is the case, assignFieldMapping sets both fieldByName and fieldName in cfg.
(cfg *Config, comp Components)
| 425 | // once (either in cfg or comp). Then if that is the case, assignFieldMapping |
| 426 | // sets both fieldByName and fieldName in cfg. |
| 427 | func assignFieldMapping(cfg *Config, comp Components) error { |
| 428 | cfgOk := len(cfg.Fields.Names) != 0 |
| 429 | compOk := comp.FieldByName != nil && comp.FieldNames != nil |
| 430 | |
| 431 | if (comp.FieldByName == nil) != (comp.FieldNames == nil) { |
| 432 | return fmt.Errorf("FieldByName and FieldName must be either both set or both unset") |
| 433 | } |
| 434 | |
| 435 | // First, get inconsistent cases out of the way. |
| 436 | if !cfgOk && !compOk { |
| 437 | return fmt.Errorf("field indexes/names have not been set") |
| 438 | } |
| 439 | |
| 440 | if cfgOk && compOk { |
| 441 | return fmt.Errorf("field indexes/names can't both be set in TOML and in Components") |
| 442 | } |
| 443 | |
| 444 | if compOk { |
| 445 | // Ok, mapping has been set from Components. |
| 446 | cfg.fieldByName = comp.FieldByName |
| 447 | cfg.fieldNames = comp.FieldNames |
| 448 | return nil |
| 449 | } |
| 450 | |
| 451 | // Mapping has been set from Config, create both closures and assign them. |
| 452 | m := make(map[string]FieldIndex, len(cfg.Fields.Names)) |
| 453 | for f, s := range cfg.Fields.Names { |
| 454 | _, ok := m[s] |
| 455 | if ok { |
| 456 | return fmt.Errorf("duplicated field name %q", s) |
| 457 | } |
| 458 | m[s] = FieldIndex(f) |
| 459 | } |
| 460 | |
| 461 | cfg.fieldNames = cfg.Fields.Names |
| 462 | cfg.fieldByName = func(name string) (FieldIndex, bool) { |
| 463 | f, ok := m[name] |
| 464 | return f, ok |
| 465 | } |
| 466 | |
| 467 | return nil |
| 468 | } |
| 469 | |
| 470 | // assignValidationMapping verifies that validation has been set once either in comp or in cfg. |
| 471 | // If validation has not been set assignValidationMapping generates a dummy function. |