github.com/nalum/terraform@v0.3.2-0.20141223102918-aa2c22ffeff6/flatmap/expand.go (about) 1 package flatmap 2 3 import ( 4 "fmt" 5 "strconv" 6 "strings" 7 ) 8 9 // Expand takes a map and a key (prefix) and expands that value into 10 // a more complex structure. This is the reverse of the Flatten operation. 11 func Expand(m map[string]string, key string) interface{} { 12 // If the key is exactly a key in the map, just return it 13 if v, ok := m[key]; ok { 14 if v == "true" { 15 return true 16 } else if v == "false" { 17 return false 18 } 19 20 return v 21 } 22 23 // Check if the key is an array, and if so, expand the array 24 if _, ok := m[key+".#"]; ok { 25 return expandArray(m, key) 26 } 27 28 // Check if this is a prefix in the map 29 prefix := key + "." 30 for k, _ := range m { 31 if strings.HasPrefix(k, prefix) { 32 return expandMap(m, prefix) 33 } 34 } 35 36 return nil 37 } 38 39 func expandArray(m map[string]string, prefix string) []interface{} { 40 num, err := strconv.ParseInt(m[prefix+".#"], 0, 0) 41 if err != nil { 42 panic(err) 43 } 44 45 result := make([]interface{}, num) 46 for i := 0; i < int(num); i++ { 47 result[i] = Expand(m, fmt.Sprintf("%s.%d", prefix, i)) 48 } 49 50 return result 51 } 52 53 func expandMap(m map[string]string, prefix string) map[string]interface{} { 54 result := make(map[string]interface{}) 55 for k, _ := range m { 56 if !strings.HasPrefix(k, prefix) { 57 continue 58 } 59 60 key := k[len(prefix):] 61 idx := strings.Index(key, ".") 62 if idx != -1 { 63 key = key[:idx] 64 } 65 if _, ok := result[key]; ok { 66 continue 67 } 68 69 // It contains a period, so it is a more complex structure 70 result[key] = Expand(m, k[:len(prefix)+len(key)]) 71 } 72 73 return result 74 }