env.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package container
  2. import (
  3. "strings"
  4. )
  5. // ReplaceOrAppendEnvValues returns the defaults with the overrides either
  6. // replaced by env key or appended to the list
  7. func ReplaceOrAppendEnvValues(defaults, overrides []string) []string {
  8. cache := make(map[string]int, len(defaults))
  9. for i, e := range defaults {
  10. parts := strings.SplitN(e, "=", 2)
  11. cache[parts[0]] = i
  12. }
  13. for _, value := range overrides {
  14. // Values w/o = means they want this env to be removed/unset.
  15. if !strings.Contains(value, "=") {
  16. if i, exists := cache[value]; exists {
  17. defaults[i] = "" // Used to indicate it should be removed
  18. }
  19. continue
  20. }
  21. // Just do a normal set/update
  22. parts := strings.SplitN(value, "=", 2)
  23. if i, exists := cache[parts[0]]; exists {
  24. defaults[i] = value
  25. } else {
  26. defaults = append(defaults, value)
  27. }
  28. }
  29. // Now remove all entries that we want to "unset"
  30. for i := 0; i < len(defaults); i++ {
  31. if defaults[i] == "" {
  32. defaults = append(defaults[:i], defaults[i+1:]...)
  33. i--
  34. }
  35. }
  36. return defaults
  37. }