Skip to content

Commit

Permalink
Fix required env vars ignored except the last one
Browse files Browse the repository at this point in the history
During the variable substitution, if a missing variable was followed
by an existing one, the empty "outerErr" variable overwrote the previous
non-empty variable.

Unlike with Docker Compose v1, the first found error did not guarantee
that an actual error would be thrown.

Example which would have run before the fix even though var1 is not defined:

```yaml
services:
  bash:
    image: bash:5.0.18-alpine3.15
    environment:
      var12: "_ ${var1:?Error1} _ ${var2:?Error2} _ "
    command:
      - env
```

```bash
```

This change also means that, if multiple variables are missing in one string, the first one will be reported by Docker Compose

Signed-off-by: Ákos Takács <takacs.akos@it-sziget.hu>
  • Loading branch information
rimelek committed Aug 31, 2022
1 parent 7aed131 commit 8ce8973
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
1 change: 1 addition & 0 deletions interpolation/interpolation_test.go
Expand Up @@ -114,6 +114,7 @@ func TestValidUnexistentInterpolation(t *testing.T) {
{test: "{{{ ${FOO:?foo_} }}}", errMsg: "foo_"},
{test: "{{{ ${FOO:?foo-bar-value} }}}", errMsg: "foo-bar-value"},
{test: "{{{ ${FOO:?foo} ${BAR:-DEFAULT_VALUE} }}}", errMsg: "foo"},
{test: "${FOO:?foo} ${BAR:?bar}", errMsg: "foo"},
{test: "{{{ ${BAR} }}}", expected: "{{{ }}}"},
{test: "${FOO:?baz} }}}", errMsg: "baz"},
{test: "${FOO?baz} }}}", errMsg: "baz"},
Expand Down
9 changes: 8 additions & 1 deletion template/template.go
Expand Up @@ -62,6 +62,7 @@ type SubstituteFunc func(string, Mapping) (string, bool, error)
// It accepts additional substitute function.
func SubstituteWith(template string, mapping Mapping, pattern *regexp.Regexp, subsFuncs ...SubstituteFunc) (string, error) {
var outerErr error
var returnErr error

result := pattern.ReplaceAllStringFunc(template, func(substring string) string {
_, subsFunc := getSubstitutionFunctionForTemplate(substring)
Expand Down Expand Up @@ -91,6 +92,9 @@ func SubstituteWith(template string, mapping Mapping, pattern *regexp.Regexp, su

if substitution == "" {
outerErr = &InvalidTemplateError{Template: template}
if returnErr == nil {
returnErr = outerErr
}
return ""
}

Expand All @@ -101,6 +105,9 @@ func SubstituteWith(template string, mapping Mapping, pattern *regexp.Regexp, su
)
value, applied, outerErr = subsFunc(substitution, mapping)
if outerErr != nil {
if returnErr == nil {
returnErr = outerErr
}
return ""
}
if applied {
Expand All @@ -119,7 +126,7 @@ func SubstituteWith(template string, mapping Mapping, pattern *regexp.Regexp, su
return value
})

return result, outerErr
return result, returnErr
}

func getSubstitutionFunctionForTemplate(template string) (string, SubstituteFunc) {
Expand Down

0 comments on commit 8ce8973

Please sign in to comment.