Skip to content

Commit

Permalink
Always set COMPOSE_PROJECT_NAME
Browse files Browse the repository at this point in the history
Signed-off-by: Nicolas De Loof <[email protected]>
  • Loading branch information
ndeloof committed May 15, 2024
1 parent 94bd735 commit f01b674
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 13 deletions.
22 changes: 9 additions & 13 deletions loader/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -328,19 +328,11 @@ func loadModelWithContext(ctx context.Context, configDetails *types.ConfigDetail
return nil, errors.New("No files specified")
}

err := projectName(*configDetails, opts)
err := projectName(configDetails, opts)
if err != nil {
return nil, err
}

// TODO(milas): this should probably ALWAYS set (overriding any existing)
if _, ok := configDetails.Environment[consts.ComposeProjectName]; !ok && opts.projectName != "" {
if configDetails.Environment == nil {
configDetails.Environment = map[string]string{}
}
configDetails.Environment[consts.ComposeProjectName] = opts.projectName
}

return load(ctx, *configDetails, opts, nil)
}

Expand Down Expand Up @@ -595,10 +587,14 @@ func InvalidProjectNameErr(v string) error {
// projectName determines the canonical name to use for the project considering
// the loader Options as well as `name` fields in Compose YAML fields (which
// also support interpolation).
//
// TODO(milas): restructure loading so that we don't need to re-parse the YAML
// here, as it's both wasteful and makes this code error-prone.
func projectName(details types.ConfigDetails, opts *Options) error {
func projectName(details *types.ConfigDetails, opts *Options) error {
defer func() {
if details.Environment == nil {
details.Environment = map[string]string{}
}
details.Environment[consts.ComposeProjectName] = opts.projectName
}()

if opts.projectNameImperativelySet {
if NormalizeProjectName(opts.projectName) != opts.projectName {
return InvalidProjectNameErr(opts.projectName)
Expand Down
17 changes: 17 additions & 0 deletions loader/loader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2391,6 +2391,23 @@ services:
assert.NilError(t, err)
assert.Equal(t, "env-var-web", svc.ContainerName)
})

t.Run("project name override", func(t *testing.T) {
yaml := `
name: another_name
services:
web:
image: web
container_name: ${COMPOSE_PROJECT_NAME}-web
`
configDetails := buildConfigDetails(yaml, map[string]string{})

actual, err := Load(configDetails, withProjectName("interpolated", true))
assert.NilError(t, err)
svc, err := actual.GetService("web")
assert.NilError(t, err)
assert.Equal(t, "interpolated-web", svc.ContainerName)
})
}

func TestLoadWithBindMountVolume(t *testing.T) {
Expand Down

0 comments on commit f01b674

Please sign in to comment.