github.com/Jeffail/benthos/v3@v3.65.0/internal/docs/field_interop.go (about) 1 package docs 2 3 import ( 4 "gopkg.in/yaml.v3" 5 ) 6 7 // ComponentFieldsFromConf walks the children of a YAML node and returns a list 8 // of fields extracted from it. This can be used in order to infer a field spec 9 // for a parsed component. 10 // 11 // TODO: V5 Remove this eventually. 12 func ComponentFieldsFromConf(conf interface{}) (inferred map[string]FieldSpecs) { 13 inferred = map[string]FieldSpecs{} 14 15 componentNodes := map[string]yaml.Node{} 16 17 var node yaml.Node 18 if err := node.Encode(conf); err != nil { 19 return 20 } 21 22 if err := node.Decode(componentNodes); err != nil { 23 return 24 } 25 26 for k, v := range componentNodes { 27 inferred[k] = FieldsFromYAML(&v) 28 } 29 return 30 } 31 32 // FieldsFromConf attempts to infer field documents from a config struct. 33 func FieldsFromConf(conf interface{}) FieldSpecs { 34 var node yaml.Node 35 if err := node.Encode(conf); err != nil { 36 return FieldSpecs{} 37 } 38 return FieldsFromYAML(&node) 39 } 40 41 // ChildDefaultAndTypesFromStruct enriches a field specs children with a type 42 // string and default value from another field spec inferred from a config 43 // struct. 44 // 45 // TODO: V5 Remove this eventually. 46 func (f FieldSpec) ChildDefaultAndTypesFromStruct(conf interface{}) FieldSpec { 47 var node yaml.Node 48 if err := node.Encode(conf); err != nil { 49 return f 50 } 51 f.Children = f.Children.DefaultAndTypeFrom(FieldsFromYAML(&node)) 52 return f 53 } 54 55 // DefaultAndTypeFrom enriches a field spec with a type string and default value 56 // from another field spec. 57 func (f FieldSpec) DefaultAndTypeFrom(from FieldSpec) FieldSpec { 58 if f.Default == nil && from.Default != nil { 59 f.Default = from.Default 60 } 61 if f.Type == "" && from.Type != "" { 62 f.Type = from.Type 63 } 64 f.Children = f.Children.DefaultAndTypeFrom(from.Children) 65 return f 66 } 67 68 // DefaultAndTypeFrom enriches a field spec with a type string and default value 69 // from another field spec. 70 func (f FieldSpecs) DefaultAndTypeFrom(from FieldSpecs) FieldSpecs { 71 newSpecs := make(FieldSpecs, len(f)) 72 fromMap := map[string]FieldSpec{} 73 for _, v := range from { 74 fromMap[v.Name] = v 75 } 76 for i, v := range f { 77 ref, exists := fromMap[v.Name] 78 if !exists { 79 newSpecs[i] = v 80 continue 81 } 82 newSpecs[i] = v.DefaultAndTypeFrom(ref) 83 } 84 return newSpecs 85 }