From b69e8f62ef771746b60977523d1b99ec43aed1e9 Mon Sep 17 00:00:00 2001 From: Milas Bowman Date: Mon, 21 Aug 2023 15:29:52 -0400 Subject: [PATCH] load: move env var profile detection to option Instead of reading `COMPOSE_PROFILES` environment variable directly during `load()`, rely exclusively on `opts.Profiles`. A new loader option, `WithDefaultProfiles`, allows passing profile name(s) via varargs. If none are provided, it will fallback to using any profiles set via `COMPOSE_PROFILES`. This improves purity of the loader and fixes issues with profiles being ignored for `include` (docker/compose#10906). Signed-off-by: Milas Bowman --- cli/options.go | 16 +++++++++++++--- loader/loader.go | 3 --- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/cli/options.go b/cli/options.go index f20803b0..abd4e5af 100644 --- a/cli/options.go +++ b/cli/options.go @@ -194,7 +194,7 @@ func WithEnv(env []string) ProjectOptionsFn { } } -// WithDiscardEnvFiles sets discards the `env_file` section after resolving to +// WithDiscardEnvFile sets discards the `env_file` section after resolving to // the `environment` section func WithDiscardEnvFile(o *ProjectOptions) error { o.loadOptions = append(o.loadOptions, loader.WithDiscardEnvFiles) @@ -209,6 +209,15 @@ func WithLoadOptions(loadOptions ...func(*loader.Options)) ProjectOptionsFn { } } +// WithDefaultProfiles uses the provided profiles (if any), and falls back to +// profiles specified via the COMPOSE_PROFILES environment variable otherwise. +func WithDefaultProfiles(profile ...string) ProjectOptionsFn { + if len(profile) == 0 { + profile = strings.Split(os.Getenv(consts.ComposeProfiles), ",") + } + return WithProfiles(profile) +} + // WithProfiles sets profiles to be activated func WithProfiles(profiles []string) ProjectOptionsFn { return func(o *ProjectOptions) error { @@ -228,8 +237,9 @@ func WithOsEnv(o *ProjectOptions) error { return nil } -// WithEnvFile set an alternate env file -// deprecated - use WithEnvFiles +// WithEnvFile sets an alternate env file. +// +// Deprecated: use WithEnvFiles instead. func WithEnvFile(file string) ProjectOptionsFn { var files []string if file != "" { diff --git a/loader/loader.go b/loader/loader.go index 6b80ab23..74dc5c86 100644 --- a/loader/loader.go +++ b/loader/loader.go @@ -360,9 +360,6 @@ func load(ctx context.Context, configDetails types.ConfigDetails, opts *Options, } } - if profiles, ok := project.Environment[consts.ComposeProfiles]; ok && len(opts.Profiles) == 0 { - opts.Profiles = strings.Split(profiles, ",") - } project.ApplyProfiles(opts.Profiles) err := project.ResolveServicesEnvironment(opts.discardEnvFiles)