build.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package compose
  14. import (
  15. "context"
  16. "fmt"
  17. "os"
  18. "strings"
  19. "github.com/compose-spec/compose-go/v2/cli"
  20. "github.com/compose-spec/compose-go/v2/types"
  21. "github.com/docker/cli/cli/command"
  22. cliopts "github.com/docker/cli/opts"
  23. "github.com/docker/compose/v2/cmd/display"
  24. "github.com/docker/compose/v2/pkg/compose"
  25. "github.com/spf13/cobra"
  26. "github.com/docker/compose/v2/pkg/api"
  27. )
  28. type buildOptions struct {
  29. *ProjectOptions
  30. quiet bool
  31. pull bool
  32. push bool
  33. args []string
  34. noCache bool
  35. memory cliopts.MemBytes
  36. ssh string
  37. builder string
  38. deps bool
  39. print bool
  40. check bool
  41. sbom string
  42. provenance string
  43. }
  44. func (opts buildOptions) toAPIBuildOptions(services []string) (api.BuildOptions, error) {
  45. var SSHKeys []types.SSHKey
  46. if opts.ssh != "" {
  47. id, path, found := strings.Cut(opts.ssh, "=")
  48. if !found && id != "default" {
  49. return api.BuildOptions{}, fmt.Errorf("invalid ssh key %q", opts.ssh)
  50. }
  51. SSHKeys = append(SSHKeys, types.SSHKey{
  52. ID: id,
  53. Path: path,
  54. })
  55. }
  56. builderName := opts.builder
  57. if builderName == "" {
  58. builderName = os.Getenv("BUILDX_BUILDER")
  59. }
  60. uiMode := display.Mode
  61. if uiMode == display.ModeJSON {
  62. uiMode = "rawjson"
  63. }
  64. return api.BuildOptions{
  65. Pull: opts.pull,
  66. Push: opts.push,
  67. Progress: uiMode,
  68. Args: types.NewMappingWithEquals(opts.args),
  69. NoCache: opts.noCache,
  70. Quiet: opts.quiet,
  71. Services: services,
  72. Deps: opts.deps,
  73. Memory: int64(opts.memory),
  74. Print: opts.print,
  75. Check: opts.check,
  76. SSHs: SSHKeys,
  77. Builder: builderName,
  78. SBOM: opts.sbom,
  79. Provenance: opts.provenance,
  80. }, nil
  81. }
  82. func buildCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command {
  83. opts := buildOptions{
  84. ProjectOptions: p,
  85. }
  86. cmd := &cobra.Command{
  87. Use: "build [OPTIONS] [SERVICE...]",
  88. Short: "Build or rebuild services",
  89. PreRunE: Adapt(func(ctx context.Context, args []string) error {
  90. if opts.quiet {
  91. display.Mode = display.ModeQuiet
  92. devnull, err := os.Open(os.DevNull)
  93. if err != nil {
  94. return err
  95. }
  96. os.Stdout = devnull
  97. }
  98. return nil
  99. }),
  100. RunE: AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error {
  101. if cmd.Flags().Changed("ssh") && opts.ssh == "" {
  102. opts.ssh = "default"
  103. }
  104. if cmd.Flags().Changed("progress") && opts.ssh == "" {
  105. fmt.Fprint(os.Stderr, "--progress is a global compose flag, better use `docker compose --progress xx build ...\n")
  106. }
  107. return runBuild(ctx, dockerCli, backendOptions, opts, args)
  108. }),
  109. ValidArgsFunction: completeServiceNames(dockerCli, p),
  110. }
  111. flags := cmd.Flags()
  112. flags.BoolVar(&opts.push, "push", false, "Push service images")
  113. flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Suppress the build output")
  114. flags.BoolVar(&opts.pull, "pull", false, "Always attempt to pull a newer version of the image")
  115. flags.StringArrayVar(&opts.args, "build-arg", []string{}, "Set build-time variables for services")
  116. flags.StringVar(&opts.ssh, "ssh", "", "Set SSH authentications used when building service images. (use 'default' for using your default SSH Agent)")
  117. flags.StringVar(&opts.builder, "builder", "", "Set builder to use")
  118. flags.BoolVar(&opts.deps, "with-dependencies", false, "Also build dependencies (transitively)")
  119. flags.StringVar(&opts.provenance, "provenance", "", `Add a provenance attestation`)
  120. flags.StringVar(&opts.sbom, "sbom", "", `Add a SBOM attestation`)
  121. flags.Bool("parallel", true, "Build images in parallel. DEPRECATED")
  122. flags.MarkHidden("parallel") //nolint:errcheck
  123. flags.Bool("compress", true, "Compress the build context using gzip. DEPRECATED")
  124. flags.MarkHidden("compress") //nolint:errcheck
  125. flags.Bool("force-rm", true, "Always remove intermediate containers. DEPRECATED")
  126. flags.MarkHidden("force-rm") //nolint:errcheck
  127. flags.BoolVar(&opts.noCache, "no-cache", false, "Do not use cache when building the image")
  128. flags.Bool("no-rm", false, "Do not remove intermediate containers after a successful build. DEPRECATED")
  129. flags.MarkHidden("no-rm") //nolint:errcheck
  130. flags.VarP(&opts.memory, "memory", "m", "Set memory limit for the build container. Not supported by BuildKit.")
  131. flags.StringVar(&p.Progress, "progress", "", fmt.Sprintf(`Set type of ui output (%s)`, strings.Join(printerModes, ", ")))
  132. flags.MarkHidden("progress") //nolint:errcheck
  133. flags.BoolVar(&opts.print, "print", false, "Print equivalent bake file")
  134. flags.BoolVar(&opts.check, "check", false, "Check build configuration")
  135. return cmd
  136. }
  137. func runBuild(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts buildOptions, services []string) error {
  138. if opts.print {
  139. backendOptions.Add(compose.WithEventProcessor(display.Quiet()))
  140. }
  141. backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...)
  142. if err != nil {
  143. return err
  144. }
  145. opts.All = true // do not drop resources as build may involve some dependencies by additional_contexts
  146. project, _, err := opts.ToProject(ctx, dockerCli, backend, nil, cli.WithoutEnvironmentResolution)
  147. if err != nil {
  148. return err
  149. }
  150. if err := applyPlatforms(project, false); err != nil {
  151. return err
  152. }
  153. apiBuildOptions, err := opts.toAPIBuildOptions(services)
  154. if err != nil {
  155. return err
  156. }
  157. apiBuildOptions.Attestations = true
  158. return backend.Build(ctx, project, apiBuildOptions)
  159. }