diff --git a/local/compose/exec.go b/local/compose/exec.go index 068b5b3c6..cce085f10 100644 --- a/local/compose/exec.go +++ b/local/compose/exec.go @@ -50,11 +50,12 @@ func (s *composeService) Exec(ctx context.Context, project *types.Project, opts container := containers[0] var env []string - projectEnv := types.NewMappingWithEquals(opts.Environment).Resolve(func(s string) (string, bool) { - v, ok := project.Environment[s] - return v, ok - }) - for k, v := range service.Environment.OverrideBy(projectEnv) { + for k, v := range service.Environment.OverrideBy(types.NewMappingWithEquals(opts.Environment)). + Resolve(func(s string) (string, bool) { + v, ok := project.Environment[s] + return v, ok + }). + RemoveEmpty() { env = append(env, fmt.Sprintf("%s=%s", k, *v)) } diff --git a/local/e2e/compose/compose_exec_test.go b/local/e2e/compose/compose_exec_test.go index e25810bf3..4ef4bf877 100644 --- a/local/e2e/compose/compose_exec_test.go +++ b/local/e2e/compose/compose_exec_test.go @@ -17,8 +17,10 @@ package e2e import ( + "strings" "testing" + "gotest.tools/v3/assert" "gotest.tools/v3/icmd" . "github.com/docker/compose-cli/utils/e2e" @@ -40,4 +42,18 @@ func TestLocalComposeExec(t *testing.T) { res := c.RunDockerOrExitError("exec", "compose-e2e-exec_simple_1", "/bin/false") res.Assert(t, icmd.Expected{ExitCode: 1}) }) + + t.Run("exec with env set", func(t *testing.T) { + res := icmd.RunCmd(c.NewDockerCmd("exec", "-e", "FOO", "compose-e2e-exec_simple_1", "/usr/bin/env"), + func(cmd *icmd.Cmd) { + cmd.Env = append(cmd.Env, "FOO=BAR") + }) + res.Assert(t, icmd.Expected{Out: "FOO=BAR"}) + }) + + t.Run("exec without env set", func(t *testing.T) { + res := c.RunDockerOrExitError("exec", "-e", "FOO", "compose-e2e-exec_simple_1", "/usr/bin/env") + res.Assert(t, icmd.Expected{ExitCode: 0}) + assert.Check(t, !strings.Contains(res.Stdout(), "FOO=")) + }) }