env.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package opts
  2. import (
  3. "fmt"
  4. "os"
  5. "runtime"
  6. "strings"
  7. )
  8. // ValidateEnv validates an environment variable and returns it.
  9. // If no value is specified, it returns the current value using os.Getenv.
  10. //
  11. // As on ParseEnvFile and related to #16585, environment variable names
  12. // are not validate what so ever, it's up to application inside docker
  13. // to validate them or not.
  14. //
  15. // The only validation here is to check if name is empty, per #25099
  16. func ValidateEnv(val string) (string, error) {
  17. arr := strings.Split(val, "=")
  18. if arr[0] == "" {
  19. return "", fmt.Errorf("invalid environment variable: %s", val)
  20. }
  21. if len(arr) > 1 {
  22. return val, nil
  23. }
  24. if !doesEnvExist(val) {
  25. return val, nil
  26. }
  27. return fmt.Sprintf("%s=%s", val, os.Getenv(val)), nil
  28. }
  29. func doesEnvExist(name string) bool {
  30. for _, entry := range os.Environ() {
  31. parts := strings.SplitN(entry, "=", 2)
  32. if runtime.GOOS == "windows" {
  33. // Environment variable are case-insensitive on Windows. PaTh, path and PATH are equivalent.
  34. if strings.EqualFold(parts[0], name) {
  35. return true
  36. }
  37. }
  38. if parts[0] == name {
  39. return true
  40. }
  41. }
  42. return false
  43. }