diff --git a/pkg/container/docker_run.go b/pkg/container/docker_run.go index 8dde858..f2402cb 100644 --- a/pkg/container/docker_run.go +++ b/pkg/container/docker_run.go @@ -294,8 +294,15 @@ func (cr *containerReference) create(capAdd []string, capDrop []string) common.E } logger := common.Logger(ctx) isTerminal := term.IsTerminal(int(os.Stdout.Fd())) - input := cr.input + + insp, _, err := cr.cli.ImageInspectWithRaw(ctx, input.Image) + if err != nil { + logger.Error(err) + } + + input.Env = mergeEnvFromImage(input.Env, insp.Config.Env) + config := &container.Config{ Image: input.Image, Cmd: input.Cmd, @@ -348,6 +355,39 @@ func (cr *containerReference) create(capAdd []string, capDrop []string) common.E } } +func mergeEnvFromImage(inputEnv, imageEnv []string) []string { + envMap := make(map[string]string) + for _, v := range inputEnv { + e := strings.Split(v, `=`) + if e[1] == "" { + envMap[e[0]] = "" + } else { + envMap[e[0]] = e[1] + } + } + + for _, v := range imageEnv { + e := strings.SplitN(v, `=`, 2) + if env, ok := envMap[e[0]]; !ok { + if e[1] != "" { + envMap[e[0]] = e[1] + } + } else { + if e[0] == "PATH" { + if e[1] != "" { + envMap[e[0]] = strings.Join([]string{env, e[1]}, `:`) + } + } + } + } + + out := make([]string, 0) + for k, v := range envMap { + out = append(out, strings.Join([]string{k, v}, `=`)) + } + return out +} + var singleLineEnvPattern, mulitiLineEnvPattern *regexp.Regexp func (cr *containerReference) extractEnv(srcPath string, env *map[string]string) common.Executor { diff --git a/pkg/container/docker_run_test.go b/pkg/container/docker_run_test.go new file mode 100644 index 0000000..b5bdb66 --- /dev/null +++ b/pkg/container/docker_run_test.go @@ -0,0 +1,34 @@ +package container + +import ( + "sort" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestMergeEnvFromImage(t *testing.T) { + inputEnv := []string{ + "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/sbin", + "GOPATH=/root/go", + "GOOS=linux", + } + imageEnv := []string{ + "PATH=/root/go/bin", + "GOPATH=/tmp", + "GOARCH=amd64", + } + + merged := mergeEnvFromImage(inputEnv, imageEnv) + sort.Strings(merged) + + expected := []string{ + "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/sbin:/root/go/bin", + "GOPATH=/root/go", + "GOOS=linux", + "GOARCH=amd64", + } + sort.Strings(expected) + + assert.Equal(t, expected, merged) +}