github.com/drud/ddev@v1.21.5-alpha1.0.20230226034409-94fcc4b94453/pkg/util/yamltools.go (about) 1 package util 2 3 import ( 4 "fmt" 5 "gopkg.in/yaml.v3" 6 "os" 7 ) 8 9 // YamlFileToMap() reads the named file into a map[string]interface{} 10 func YamlFileToMap(fname string) (map[string]interface{}, error) { 11 file, err2 := os.ReadFile(fname) 12 contents, err := file, err2 13 if err != nil { 14 return nil, fmt.Errorf("unable to read file %s (%v)", fname, err) 15 } 16 17 itemMap := make(map[string]interface{}) 18 err = yaml.Unmarshal(contents, &itemMap) 19 if err != nil { 20 return nil, fmt.Errorf("unable to unmarshal %s: %v", contents, err) 21 } 22 return itemMap, nil 23 } 24 25 // YamlToDict turns random yaml-based interface into a map[string]interface{} 26 func YamlToDict(topm interface{}) (map[string]interface{}, error) { 27 res := make(map[string]interface{}) 28 var err error 29 30 switch topm.(type) { 31 case map[string]interface{}: 32 for yk, v := range topm.(map[string]interface{}) { 33 switch v.(type) { 34 case string: 35 res[yk] = v 36 case map[string]interface{}: 37 res[yk], err = YamlToDict(v) 38 case interface{}: 39 res[yk] = v 40 default: 41 return nil, fmt.Errorf("YamlToDict: type %T not handled (%v)", yk, yk) 42 } 43 if err != nil { 44 return nil, err 45 } 46 } 47 default: 48 return nil, fmt.Errorf("YamlToDict: type %T not handled (%v)", topm, topm) 49 } 50 return res, nil 51 }