forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.go
82 lines (69 loc) · 1.7 KB
/
map.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package flatmap
import (
"strings"
)
// Map is a wrapper around map[string]string that provides some helpers
// above it that assume the map is in the format that flatmap expects
// (the result of Flatten).
//
// All modifying functions such as Delete are done in-place unless
// otherwise noted.
type Map map[string]string
// Contains returns true if the map contains the given key.
func (m Map) Contains(key string) bool {
for _, k := range m.Keys() {
if k == key {
return true
}
}
return false
}
// Delete deletes a key out of the map with the given prefix.
func (m Map) Delete(prefix string) {
for k, _ := range m {
match := k == prefix
if !match {
if !strings.HasPrefix(k, prefix) {
continue
}
if k[len(prefix):len(prefix)+1] != "." {
continue
}
}
delete(m, k)
}
}
// Keys returns all of the top-level keys in this map
func (m Map) Keys() []string {
ks := make(map[string]struct{})
for k, _ := range m {
idx := strings.Index(k, ".")
if idx == -1 {
idx = len(k)
}
ks[k[:idx]] = struct{}{}
}
result := make([]string, 0, len(ks))
for k, _ := range ks {
result = append(result, k)
}
return result
}
// Merge merges the contents of the other Map into this one.
//
// This merge is smarter than a simple map iteration because it
// will fully replace arrays and other complex structures that
// are present in this map with the other map's. For example, if
// this map has a 3 element "foo" list, and m2 has a 2 element "foo"
// list, then the result will be that m has a 2 element "foo"
// list.
func (m Map) Merge(m2 Map) {
for _, prefix := range m2.Keys() {
m.Delete(prefix)
for k, v := range m2 {
if strings.HasPrefix(k, prefix) {
m[k] = v
}
}
}
}