Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 64 additions & 25 deletions bake/compose.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/compose-spec/compose-go/v2/consts"
"github.com/compose-spec/compose-go/v2/dotenv"
"github.com/compose-spec/compose-go/v2/loader"
composeschema "github.com/compose-spec/compose-go/v2/schema"
composetypes "github.com/compose-spec/compose-go/v2/types"
"github.com/docker/buildx/util/buildflags"
dockeropts "github.com/docker/cli/opts"
Expand All @@ -35,21 +36,7 @@ func ParseComposeFiles(fs []File) (*Config, error) {
}

func ParseCompose(cfgs []composetypes.ConfigFile, envs map[string]string) (*Config, error) {
if envs == nil {
envs = make(map[string]string)
}
cfg, err := loader.LoadWithContext(context.Background(), composetypes.ConfigDetails{
ConfigFiles: cfgs,
Environment: envs,
}, func(options *loader.Options) {
projectName := "bake"
if v, ok := envs[consts.ComposeProjectName]; ok && v != "" {
projectName = v
}
options.SetProjectName(projectName, false)
options.SkipNormalization = true
options.Profiles = []string{"*"}
})
cfg, err := loadComposeFiles(cfgs, envs)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -208,6 +195,67 @@ func ParseCompose(cfgs []composetypes.ConfigFile, envs map[string]string) (*Conf
return &c, nil
}

func loadComposeFiles(cfgs []composetypes.ConfigFile, envs map[string]string, options ...func(*loader.Options)) (*composetypes.Project, error) {
if envs == nil {
envs = make(map[string]string)
}

cfgDetails := composetypes.ConfigDetails{
ConfigFiles: cfgs,
Environment: envs,
}

raw, err := loader.LoadModelWithContext(context.Background(), cfgDetails, append([]func(*loader.Options){func(opts *loader.Options) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can do this as follow-up as not directly related but seems fine to pass in the right context from the command.

projectName := "bake"
if v, ok := envs[consts.ComposeProjectName]; ok && v != "" {
projectName = v
}
opts.SetProjectName(projectName, false)
opts.SkipNormalization = true
opts.SkipValidation = true
}}, options...)...)
if err != nil {
return nil, err
}

filtered := make(map[string]any)
for _, key := range []string{"services", "secrets"} {
if key == "services" {
if services, ok := raw["services"].(map[string]any); ok {
filteredServices := make(map[string]any)
for svcName, svc := range services {
if svc == nil {
filteredServices[svcName] = map[string]any{}
} else if svcMap, ok := svc.(map[string]any); ok {
filteredService := make(map[string]any)
for _, svcField := range []string{"image", "build", "environment", "env_file"} {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AFAICT you don't need environment or env_file as those won't have any impact on the build context (they only apply on runtime environment)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need them to evaluate build arguments:

buildx/bake/compose_test.go

Lines 396 to 424 in a007368

func TestEnv(t *testing.T) {
envf, err := os.CreateTemp("", "env")
require.NoError(t, err)
defer os.Remove(envf.Name())
_, err = envf.WriteString("FOO=bsdf -csdf\n")
require.NoError(t, err)
dt := []byte(`
services:
scratch:
build:
context: .
args:
CT_ECR: foo
FOO:
NODE_ENV:
environment:
- NODE_ENV=test
- AWS_ACCESS_KEY_ID=dummy
- AWS_SECRET_ACCESS_KEY=dummy
env_file:
- ` + envf.Name() + `
`)
c, err := ParseCompose([]composetypes.ConfigFile{{Content: dt}}, nil)
require.NoError(t, err)
require.Equal(t, map[string]*string{"CT_ECR": ptrstr("foo"), "FOO": ptrstr("bsdf -csdf"), "NODE_ENV": ptrstr("test")}, c.Targets[0].Args)
}

If not set then this test fails:

        	Error:      	Not equal: 
        	            	expected: map[string]*string{"CT_ECR":(*string)(0xc00060a510), "FOO":(*string)(0xc00060a520), "NODE_ENV":(*string)(0xc00060a530)}
        	            	actual  : map[string]*string{"CT_ECR":(*string)(0xc00060a4a0)}
        	            	
        	            	Diff:
        	            	--- Expected
        	            	+++ Actual
        	            	@@ -1,5 +1,3 @@
        	            	-(map[string]*string) (len=3) {
        	            	- (string) (len=6) "CT_ECR": (*string)((len=3) "foo"),
        	            	- (string) (len=3) "FOO": (*string)((len=10) "bsdf -csdf"),
        	            	- (string) (len=8) "NODE_ENV": (*string)((len=4) "test")
        	            	+(map[string]*string) (len=1) {
        	            	+ (string) (len=6) "CT_ECR": (*string)((len=3) "foo")
        	            	 }
        	Test:       	TestEnv
--- FAIL: TestEnv (0.00s)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a bug then. Runtime environment MUST not impact build environment; Sounds there's a confusion here with client environment (which is defined by .env file and --env-file flag in Compose) ... which is unfortunately a pretty common source of confusion 😭

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Argh yes seems it was a mistake, this was introduced in #905. What about .env then?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For parity with Compose, .env should be loaded (from compose file's parent folder), and interpolated using os.Env

if val, ok := svcMap[svcField]; ok {
filteredService[svcField] = val
}
}
filteredServices[svcName] = filteredService
}
}
filtered["services"] = filteredServices
}
} else if v, ok := raw[key]; ok {
filtered[key] = v
}
}

if err := composeschema.Validate(filtered); err != nil {
return nil, err
}

return loader.ModelToProject(filtered, loader.ToOptions(&cfgDetails, append([]func(*loader.Options){func(options *loader.Options) {
options.SkipNormalization = true
options.Profiles = []string{"*"}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

building with all profiles enabled is not consistent with Compose. Is this expected ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We allow all profiles because Bake doesn't support them: #1903. If we add something similar in our spec I think we could reconsider that. cc @colinhemmings

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In follow-up we could consider mapping compose profiles to bake groups and maybe defining a default profile that would be used if one is defined.

}}, options...)), composetypes.ConfigDetails{
ConfigFiles: cfgs,
Environment: envs,
})
}

func validateComposeFile(dt []byte, fn string) (bool, error) {
envs, err := composeEnv()
if err != nil {
Expand All @@ -225,16 +273,7 @@ func validateComposeFile(dt []byte, fn string) (bool, error) {
}

func validateCompose(dt []byte, envs map[string]string) error {
_, err := loader.LoadWithContext(context.Background(), composetypes.ConfigDetails{
ConfigFiles: []composetypes.ConfigFile{
{
Content: dt,
},
},
Environment: envs,
}, func(options *loader.Options) {
options.SetProjectName("bake", false)
options.SkipNormalization = true
_, err := loadComposeFiles([]composetypes.ConfigFile{{Content: dt}}, envs, func(options *loader.Options) {
// consistency is checked later in ParseCompose to ensure multiple
// compose files can be merged together
options.SkipConsistencyCheck = true
Expand Down
47 changes: 36 additions & 11 deletions bake/compose_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ services:

_, err := ParseCompose([]composetypes.ConfigFile{{Content: dt}}, nil)
require.Error(t, err)
require.ErrorContains(t, err, `has neither an image nor a build context specified`)
}

func TestAdvancedNetwork(t *testing.T) {
Expand Down Expand Up @@ -610,7 +611,6 @@ func TestValidateComposeFile(t *testing.T) {
fn string
dt []byte
isCompose bool
wantErr bool
}{
{
name: "empty service",
Expand All @@ -620,7 +620,6 @@ services:
foo:
`),
isCompose: true,
wantErr: true,
},
{
name: "build",
Expand All @@ -631,7 +630,6 @@ services:
build: .
`),
isCompose: true,
wantErr: false,
},
{
name: "image",
Expand All @@ -642,7 +640,6 @@ services:
image: nginx
`),
isCompose: true,
wantErr: false,
},
{
name: "unknown ext",
Expand All @@ -653,7 +650,6 @@ services:
image: nginx
`),
isCompose: true,
wantErr: false,
},
{
name: "hcl",
Expand All @@ -664,18 +660,13 @@ target "default" {
}
`),
isCompose: false,
wantErr: false,
},
}
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
isCompose, err := validateComposeFile(tt.dt, tt.fn)
assert.Equal(t, tt.isCompose, isCompose)
if tt.wantErr {
require.Error(t, err)
} else {
require.NoError(t, err)
}
require.NoError(t, err)
})
}
}
Expand Down Expand Up @@ -888,6 +879,40 @@ services:
require.Equal(t, map[string]*string{"TEST_VALUE": ptrstr("abc"), "FOO_VALUE": ptrstr("abc")}, c.Targets[0].Args)
}

func TestUnknownField(t *testing.T) {
tmpdir := t.TempDir()
dt := []byte(`
services:
webapp:
bar: baz
build:
context: .

foo:
- bar.baz
`)

chdir(t, tmpdir)
_, err := ParseComposeFiles([]File{{Name: "compose.yml", Data: dt}})
require.NoError(t, err)
}

func TestUnknownBuildField(t *testing.T) {
tmpdir := t.TempDir()
dt := []byte(`
services:
webapp:
build:
context: .
foo: bar
`)

chdir(t, tmpdir)
_, err := ParseComposeFiles([]File{{Name: "compose.yml", Data: dt}})
require.Error(t, err)
require.ErrorContains(t, err, `additional properties 'foo' not allowed`)
}

// chdir changes the current working directory to the named directory,
// and then restore the original working directory at the end of the test.
func chdir(t *testing.T, dir string) {
Expand Down
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ require (
github.com/Masterminds/semver/v3 v3.2.1
github.com/Microsoft/go-winio v0.6.2
github.com/aws/aws-sdk-go-v2/config v1.27.27
github.com/compose-spec/compose-go/v2 v2.7.1
github.com/compose-spec/compose-go/v2 v2.7.2-0.20250703132301-891fce532a51 // main
github.com/containerd/console v1.0.5
github.com/containerd/containerd/v2 v2.1.1
github.com/containerd/continuity v0.4.5
Expand Down Expand Up @@ -105,7 +105,7 @@ require (
github.com/go-openapi/jsonpointer v0.21.0 // indirect
github.com/go-openapi/jsonreference v0.20.2 // indirect
github.com/go-openapi/swag v0.23.0 // indirect
github.com/go-viper/mapstructure/v2 v2.0.0 // indirect
github.com/go-viper/mapstructure/v2 v2.3.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/google/gnostic-models v0.6.8 // indirect
Expand Down
8 changes: 4 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XL
github.com/cloudflare/cfssl v0.0.0-20180223231731-4e2dcbde5004/go.mod h1:yMWuSON2oQp+43nFtAV/uvKQIFpSPerB57DCt9t8sSA=
github.com/codahale/rfc6979 v0.0.0-20141003034818-6a90f24967eb h1:EDmT6Q9Zs+SbUoc7Ik9EfrFqcylYqgPZ9ANSbTAntnE=
github.com/codahale/rfc6979 v0.0.0-20141003034818-6a90f24967eb/go.mod h1:ZjrT6AXHbDs86ZSdt/osfBi5qfexBrKUdONk989Wnk4=
github.com/compose-spec/compose-go/v2 v2.7.1 h1:EUIbuaD0R/J1KA+FbJMNbcS9+jt/CVudbp5iHqUllSs=
github.com/compose-spec/compose-go/v2 v2.7.1/go.mod h1:TmjkIB9W73fwVxkYY+u2uhMbMUakjiif79DlYgXsyvU=
github.com/compose-spec/compose-go/v2 v2.7.2-0.20250703132301-891fce532a51 h1:AjI75N9METifYMZK7eNt8XIgY9Sryv+1w3XDA7X2vZQ=
github.com/compose-spec/compose-go/v2 v2.7.2-0.20250703132301-891fce532a51/go.mod h1:Zow/3eYNOnl2T4qLGZEizf8d/ht1qfy09G7WGOSzGOY=
github.com/containerd/cgroups/v3 v3.0.5 h1:44na7Ud+VwyE7LIoJ8JTNQOa549a8543BmzaJHo6Bzo=
github.com/containerd/cgroups/v3 v3.0.5/go.mod h1:SA5DLYnXO8pTGYiAHXz94qvLQTKfVM5GEVisn4jpins=
github.com/containerd/console v1.0.5 h1:R0ymNeydRqH2DmakFNdmjR2k0t7UPuiOV/N/27/qqsc=
Expand Down Expand Up @@ -159,8 +159,8 @@ github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1v
github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8=
github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68=
github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=
github.com/go-viper/mapstructure/v2 v2.0.0 h1:dhn8MZ1gZ0mzeodTG3jt5Vj/o87xZKuNAprG2mQfMfc=
github.com/go-viper/mapstructure/v2 v2.0.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/go-viper/mapstructure/v2 v2.3.0 h1:27XbWsHIqhbdR5TIC911OfYvgSaW93HM+dX7970Q7jk=
github.com/go-viper/mapstructure/v2 v2.3.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/gofrs/flock v0.12.1 h1:MTLVXXHf8ekldpJk3AKicLij9MdwOWkZ+a/jHHZby9E=
github.com/gofrs/flock v0.12.1/go.mod h1:9zxTsyu5xtJ9DK+1tFZyibEV7y3uwDxPPfbxeeHCoD0=
github.com/gogo/protobuf v1.0.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading