Skip to content

Commit

Permalink
keep empty environment variables as those must be UNSET in container
Browse files Browse the repository at this point in the history
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
  • Loading branch information
ndeloof committed Jul 8, 2024
1 parent 65600ce commit 6adefd5
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 4 deletions.
13 changes: 9 additions & 4 deletions loader/normalize.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,14 @@ func Normalize(dict map[string]any, env types.Mapping) (map[string]any, error) {
}

if a, ok := build["args"]; ok {
build["args"], _ = resolve(a, fn)
build["args"], _ = resolve(a, fn, false)
}

service["build"] = build
}

if e, ok := service["environment"]; ok {
service["environment"], _ = resolve(e, fn)
service["environment"], _ = resolve(e, fn, true)
}

var dependsOn map[string]any
Expand Down Expand Up @@ -178,12 +178,12 @@ func normalizeNetworks(dict map[string]any) {
}
}

func resolve(a any, fn func(s string) (string, bool)) (any, bool) {
func resolve(a any, fn func(s string) (string, bool), keepEmpty bool) (any, bool) {
switch v := a.(type) {
case []any:
var resolved []any
for _, val := range v {
if r, ok := resolve(val, fn); ok {
if r, ok := resolve(val, fn, keepEmpty); ok {
resolved = append(resolved, r)
}
}
Expand All @@ -197,6 +197,8 @@ func resolve(a any, fn func(s string) (string, bool)) (any, bool) {
}
if s, ok := fn(key); ok {
resolved[key] = s
} else if keepEmpty {
resolved[key] = nil
}
}
return resolved, true
Expand All @@ -205,6 +207,9 @@ func resolve(a any, fn func(s string) (string, bool)) (any, bool) {
if val, ok := fn(v); ok {
return fmt.Sprintf("%s=%s", v, val), true
}
if keepEmpty {
return v, true
}
return "", false
}
return v, true
Expand Down
40 changes: 40 additions & 0 deletions loader/normalize_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -336,3 +336,43 @@ services:
assert.NilError(t, err)
assert.DeepEqual(t, expect, model)
}

func TestNormalizeEnvironment(t *testing.T) {
project := `
name: myProject
services:
test:
environment:
- FOO
- BAR
- ZOT=QIX
`

expected := `
name: myProject
networks:
default:
name: myProject_default
services:
test:
environment:
- FOO
- BAR=bar
- ZOT=QIX
networks:
default: null
`
var model map[string]any
err := yaml.Unmarshal([]byte(project), &model)
assert.NilError(t, err)
model, err = Normalize(model, map[string]string{
"BAR": "bar",
"ZOT": "zot",
})
assert.NilError(t, err)

var expect map[string]any
err = yaml.Unmarshal([]byte(expected), &expect)
assert.NilError(t, err)
assert.DeepEqual(t, expect, model)
}

0 comments on commit 6adefd5

Please sign in to comment.