Add reading environment from Docker image (#771)

* fix: read envvars from image definition

* fix: add test

* fix: sort slices

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
This commit is contained in:
Ryan 2021-09-26 16:37:53 +00:00 committed by GitHub
parent 4d552e65ce
commit c2c8b525f8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 75 additions and 1 deletions

View file

@ -294,8 +294,15 @@ func (cr *containerReference) create(capAdd []string, capDrop []string) common.E
} }
logger := common.Logger(ctx) logger := common.Logger(ctx)
isTerminal := term.IsTerminal(int(os.Stdout.Fd())) isTerminal := term.IsTerminal(int(os.Stdout.Fd()))
input := cr.input 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{ config := &container.Config{
Image: input.Image, Image: input.Image,
Cmd: input.Cmd, 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 var singleLineEnvPattern, mulitiLineEnvPattern *regexp.Regexp
func (cr *containerReference) extractEnv(srcPath string, env *map[string]string) common.Executor { func (cr *containerReference) extractEnv(srcPath string, env *map[string]string) common.Executor {

View file

@ -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)
}