github.com/benchkram/bob@v0.0.0-20240314204020-b7a57f2f9be9/pkg/envutil/envutil.go (about) 1 package envutil 2 3 import "strings" 4 5 // Merge two lists of environment variables in the "key=value" format. 6 // If variables are duplicated, the one from `b` is kept. 7 // See tests for details. 8 func Merge(a []string, b []string) []string { 9 envKeys := make(map[string]string) 10 11 if len(a) == 0 { 12 r := make([]string, len(b)) 13 copy(r, b) 14 return r 15 } 16 if len(b) == 0 { 17 r := make([]string, len(a)) 18 copy(r, a) 19 return r 20 } 21 22 for _, v := range b { 23 pair := strings.SplitN(v, "=", 2) 24 envKeys[pair[0]] = v 25 } 26 27 // Add from `a` the keys which are not in `b` 28 for _, v := range a { 29 pair := strings.SplitN(v, "=", 2) 30 if _, exists := envKeys[pair[0]]; exists { 31 continue 32 } 33 envKeys[pair[0]] = v 34 } 35 36 // Populate the result slice with the keys from the map 37 result := make([]string, 0, len(envKeys)) 38 for _, v := range envKeys { 39 result = append(result, v) 40 } 41 42 return result 43 }