diff options
author | Fabricio Voznika <fvoznika@google.com> | 2021-01-11 16:23:44 -0800 |
---|---|---|
committer | gVisor bot <gvisor-bot@google.com> | 2021-01-11 16:25:50 -0800 |
commit | 7e462a1c7f56b9b8439ad1ac92906bd8dd376ab7 (patch) | |
tree | e1975a4970f1a173344bb211debede3ac91a8787 /runsc/specutils | |
parent | 4c4de66443174f2ed7f4fa533a1d09c709be9427 (diff) |
OCI spec may contain duplicate environment variables
Closes #5226
PiperOrigin-RevId: 351259576
Diffstat (limited to 'runsc/specutils')
-rw-r--r-- | runsc/specutils/specutils.go | 25 |
1 files changed, 25 insertions, 0 deletions
diff --git a/runsc/specutils/specutils.go b/runsc/specutils/specutils.go index fdbba1832..ea55bbc7d 100644 --- a/runsc/specutils/specutils.go +++ b/runsc/specutils/specutils.go @@ -493,6 +493,31 @@ func EnvVar(env []string, name string) (string, bool) { return "", false } +// ResolveEnvs transforms lists of environment variables into a single list of +// environment variables. If a variable is defined multiple times, the last +// value is used. +func ResolveEnvs(envs ...[]string) ([]string, error) { + // First create a map of variable names to values. This removes any + // duplicates. + envMap := make(map[string]string) + for _, env := range envs { + for _, str := range env { + parts := strings.SplitN(str, "=", 2) + if len(parts) != 2 { + return nil, fmt.Errorf("invalid variable: %s", str) + } + envMap[parts[0]] = parts[1] + } + } + // Reassemble envMap into a list of environment variables of the form + // NAME=VALUE. + env := make([]string, 0, len(envMap)) + for k, v := range envMap { + env = append(env, fmt.Sprintf("%s=%s", k, v)) + } + return env, nil +} + // FaqErrorMsg returns an error message pointing to the FAQ. func FaqErrorMsg(anchor, msg string) string { return fmt.Sprintf("%s; see https://gvisor.dev/faq#%s for more details", msg, anchor) |