0
0
mirror of https://github.com/bpg/terraform-provider-proxmox.git synced 2025-06-30 02:31:10 +00:00
terraform-provider-proxmox/utils/maps.go
Pavel Boldyrev 3180f81b4a
fix(vm): yet another fix for disk reordering (#1297)
Signed-off-by: Pavel Boldyrev <627562+bpg@users.noreply.github.com>
2024-05-15 02:31:41 +00:00

74 lines
2.0 KiB
Go

package utils
import "sort"
// OrderedListFromMap generates a list from a map's values. The values are sorted based on the map's keys.
func OrderedListFromMap(inputMap map[string]interface{}) []interface{} {
itemCount := len(inputMap)
keyList := make([]string, itemCount)
i := 0
for key := range inputMap {
keyList[i] = key
i++
}
sort.Strings(keyList)
return OrderedListFromMapByKeyValues(inputMap, keyList)
}
// ListResourcesAttributeValue generates a list of strings from a Terraform resource list (which is list of maps).
// The list is generated by extracting a specific key attribute from each resource. If the attribute is not found in a
// resource, it is skipped.
func ListResourcesAttributeValue(resourceList []interface{}, keyAttr string) []string {
var l []string
for _, resource := range resourceList {
if resource == nil {
continue
}
r := resource.(map[string]interface{})
if value, ok := r[keyAttr].(string); ok {
l = append(l, value)
}
}
return l
}
// MapResourcesByAttribute generates a map of resources from a resource list, using a specified attribute as the key
// and the resource as the value. If the attribute is not found in a resource, it is skipped.
func MapResourcesByAttribute(resourceList []interface{}, keyAttr string) map[string]interface{} {
m := make(map[string]interface{}, len(resourceList))
for _, resource := range resourceList {
if resource == nil {
continue
}
r := resource.(map[string]interface{})
if key, ok := r[keyAttr].(string); ok {
m[key] = r
}
}
return m
}
// OrderedListFromMapByKeyValues generates a list from a map's values.
// The values are sorted based on the provided key list. If a key is not found in the map, it is skipped.
func OrderedListFromMapByKeyValues(inputMap map[string]interface{}, keyList []string) []interface{} {
orderedList := make([]interface{}, len(keyList))
for i, k := range keyList {
val, ok := inputMap[k]
if ok {
orderedList[i] = val
}
}
return orderedList
}