forked from srl-labs/containerlab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenv.go
87 lines (80 loc) · 1.81 KB
/
env.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
83
84
85
86
87
// Copyright 2020 Nokia
// Licensed under the BSD 3-Clause License.
// SPDX-License-Identifier: BSD-3-Clause
package utils
import (
"fmt"
"reflect"
)
// convertEnvs convert env variables passed as a map to a list of them
func ConvertEnvs(m map[string]string) []string {
s := make([]string, 0, len(m))
for k, v := range m {
s = append(s, k+"="+v)
}
return s
}
func mapify(i interface{}) (map[string]interface{}, bool) {
value := reflect.ValueOf(i)
if value.Kind() == reflect.Map {
m := map[string]interface{}{}
for _, k := range value.MapKeys() {
m[fmt.Sprintf("%v", k)] = value.MapIndex(k).Interface()
}
return m, true
}
return map[string]interface{}{}, false
}
// merge all dictionaries and return a new dictionary
// recursively if matching keys are both dictionaries
func MergeMaps(dicts ...map[string]interface{}) map[string]interface{} {
res := make(map[string]interface{})
for _, m := range dicts {
if m == nil {
continue
}
for k, v := range m {
vMap, vMapOk := mapify(v)
if v0, ok := res[k]; ok {
// Recursive merging if res[k] exists (and both are dicts)
t0, ok0 := mapify(v0)
if ok0 && vMapOk {
res[k] = MergeMaps(t0, vMap)
continue
}
}
if vMapOk {
res[k] = vMap
} else {
res[k] = v
}
}
}
return res
}
// merge all string maps and return a new map
// maps that are passed for merging will not be changed
func MergeStringMaps(maps ...map[string]string) map[string]string {
res := make(map[string]string)
for _, m := range maps {
if m == nil {
continue
}
for k, v := range m {
res[k] = v
}
}
if len(res) == 0 {
return nil
}
return res
}
// does a slice contain a string
func StringInSlice(slice []string, val string) (int, bool) {
for i, item := range slice {
if item == val {
return i, true
}
}
return -1, false
}