github.com/containerd/nerdctl@v1.7.7/pkg/composer/build.go (about) 1 /* 2 Copyright The containerd Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package composer 18 19 import ( 20 "context" 21 "fmt" 22 "os" 23 24 "github.com/compose-spec/compose-go/types" 25 "github.com/containerd/log" 26 "github.com/containerd/nerdctl/pkg/composer/serviceparser" 27 ) 28 29 type BuildOptions struct { 30 Args []string // --build-arg strings 31 NoCache bool 32 Progress string 33 } 34 35 func (c *Composer) Build(ctx context.Context, bo BuildOptions, services []string) error { 36 return c.project.WithServices(services, func(svc types.ServiceConfig) error { 37 ps, err := serviceparser.Parse(c.project, svc) 38 if err != nil { 39 return err 40 } 41 if ps.Build != nil { 42 return c.buildServiceImage(ctx, ps.Image, ps.Build, ps.Unparsed.Platform, bo) 43 } 44 return nil 45 }, types.IgnoreDependencies) 46 } 47 48 func (c *Composer) buildServiceImage(ctx context.Context, image string, b *serviceparser.Build, platform string, bo BuildOptions) error { 49 log.G(ctx).Infof("Building image %s", image) 50 51 var args []string // nolint: prealloc 52 if platform != "" { 53 args = append(args, "--platform="+platform) 54 } 55 for _, a := range bo.Args { 56 args = append(args, "--build-arg="+a) 57 } 58 if bo.NoCache { 59 args = append(args, "--no-cache") 60 } 61 if bo.Progress != "" { 62 args = append(args, "--progress="+bo.Progress) 63 } 64 args = append(args, b.BuildArgs...) 65 66 cmd := c.createNerdctlCmd(ctx, append([]string{"build"}, args...)...) 67 if c.DebugPrintFull { 68 log.G(ctx).Debugf("Running %v", cmd.Args) 69 } 70 cmd.Stdout = os.Stdout 71 cmd.Stderr = os.Stderr 72 if err := cmd.Run(); err != nil { 73 return fmt.Errorf("error while building image %s: %w", image, err) 74 } 75 return nil 76 }