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