From 67c13cf821588bf6e754ff88737bc3d1fbd5059e Mon Sep 17 00:00:00 2001 From: Ulysses Souza Date: Mon, 30 May 2022 17:30:30 +0200 Subject: [PATCH] Import dotenv file to os environment Signed-off-by: Ulysses Souza --- cmd/compose/compose.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/cmd/compose/compose.go b/cmd/compose/compose.go index b5d87a571..f4c35e987 100644 --- a/cmd/compose/compose.go +++ b/cmd/compose/compose.go @@ -27,6 +27,7 @@ import ( "github.com/compose-spec/compose-go/cli" "github.com/compose-spec/compose-go/types" + composegoutils "github.com/compose-spec/compose-go/utils" dockercli "github.com/docker/cli/cli" "github.com/docker/cli/cli-plugins/manager" "github.com/docker/cli/cli/command" @@ -257,6 +258,10 @@ func RootCommand(dockerCli command.Cli, backend api.Service) *cobra.Command { } }, PersistentPreRunE: func(cmd *cobra.Command, args []string) error { + err := setEnvWithDotEnv(&opts) + if err != nil { + return err + } parent := cmd.Root() if parent != nil { parentPrerun := parent.PersistentPreRunE @@ -333,3 +338,27 @@ func RootCommand(dockerCli command.Cli, backend api.Service) *cobra.Command { command.Flags().MarkHidden("verbose") //nolint:errcheck return command } + +func setEnvWithDotEnv(prjOpts *projectOptions) error { + options, err := prjOpts.toProjectOptions() + if err != nil { + return compose.WrapComposeError(err) + } + workingDir, err := options.GetWorkingDir() + if err != nil { + return err + } + + envFromFile, err := cli.GetEnvFromFile(composegoutils.GetAsEqualsMap(os.Environ()), workingDir, options.EnvFile) + if err != nil { + return err + } + for k, v := range envFromFile { + if _, ok := os.LookupEnv(k); !ok { + if err = os.Setenv(k, v); err != nil { + return err + } + } + } + return nil +}