env.go 1.1 KB

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