github.com/wallyworld/juju@v0.0.0-20161013125918-6cf1bc9d917a/core/description/serialization.go (about) 1 // Copyright 2015 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package description 5 6 import ( 7 "github.com/juju/errors" 8 "github.com/juju/schema" 9 ) 10 11 func versionedChecker(name string) schema.Checker { 12 fields := schema.Fields{ 13 "version": schema.Int(), 14 } 15 if name != "" { 16 fields[name] = schema.List(schema.StringMap(schema.Any())) 17 } 18 return schema.FieldMap(fields, nil) // no defaults 19 } 20 21 func versionedEmbeddedChecker(name string) schema.Checker { 22 fields := schema.Fields{ 23 "version": schema.Int(), 24 } 25 fields[name] = schema.StringMap(schema.Any()) 26 return schema.FieldMap(fields, nil) // no defaults 27 } 28 29 func getVersion(source map[string]interface{}) (int, error) { 30 checker := versionedChecker("") 31 coerced, err := checker.Coerce(source, nil) 32 if err != nil { 33 return 0, errors.Trace(err) 34 } 35 valid := coerced.(map[string]interface{}) 36 return int(valid["version"].(int64)), nil 37 } 38 39 func convertToStringSlice(field interface{}) []string { 40 if field == nil { 41 return nil 42 } 43 fieldSlice := field.([]interface{}) 44 result := make([]string, len(fieldSlice)) 45 for i, value := range fieldSlice { 46 result[i] = value.(string) 47 } 48 return result 49 } 50 51 // convertToStringMap is expected to be used on a field with the schema 52 // checker `schema.StringMap(schema.String())`. The schema will return a 53 // string map as map[string]interface{}. It will make sure that the interface 54 // values are strings, but doesn't return them as strings. So we need to do 55 // that here. 56 func convertToStringMap(field interface{}) map[string]string { 57 if field == nil { 58 return nil 59 } 60 fieldMap := field.(map[string]interface{}) 61 result := make(map[string]string) 62 for key, value := range fieldMap { 63 result[key] = value.(string) 64 } 65 return result 66 } 67 68 // convertToMapOfMaps is expected to be used on a field with the schema 69 // checker `schema.StringMap(schema.StringMap(schema.Any())`. 70 func convertToMapOfMaps(field interface{}) map[string]map[string]interface{} { 71 if field == nil { 72 return nil 73 } 74 fieldMap := field.(map[string]interface{}) 75 result := make(map[string]map[string]interface{}) 76 for key, value := range fieldMap { 77 result[key] = value.(map[string]interface{}) 78 } 79 return result 80 }