build.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  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/cli"
  20. "github.com/compose-spec/compose-go/loader"
  21. "github.com/compose-spec/compose-go/types"
  22. buildx "github.com/docker/buildx/util/progress"
  23. cliopts "github.com/docker/cli/opts"
  24. ui "github.com/docker/compose/v2/pkg/progress"
  25. "github.com/spf13/cobra"
  26. "github.com/docker/compose/v2/pkg/api"
  27. )
  28. type buildOptions struct {
  29. *ProjectOptions
  30. composeOptions
  31. quiet bool
  32. pull bool
  33. push bool
  34. args []string
  35. noCache bool
  36. memory cliopts.MemBytes
  37. ssh string
  38. builder string
  39. }
  40. func (opts buildOptions) toAPIBuildOptions(services []string) (api.BuildOptions, error) {
  41. var SSHKeys []types.SSHKey
  42. var err error
  43. if opts.ssh != "" {
  44. SSHKeys, err = loader.ParseShortSSHSyntax(opts.ssh)
  45. if err != nil {
  46. return api.BuildOptions{}, err
  47. }
  48. }
  49. builderName := opts.builder
  50. if builderName == "" {
  51. builderName = os.Getenv("BUILDX_BUILDER")
  52. }
  53. return api.BuildOptions{
  54. Pull: opts.pull,
  55. Push: opts.push,
  56. Progress: ui.Mode,
  57. Args: types.NewMappingWithEquals(opts.args),
  58. NoCache: opts.noCache,
  59. Quiet: opts.quiet,
  60. Services: services,
  61. SSHs: SSHKeys,
  62. Builder: builderName,
  63. }, nil
  64. }
  65. func buildCommand(p *ProjectOptions, progress *string, backend api.Service) *cobra.Command {
  66. opts := buildOptions{
  67. ProjectOptions: p,
  68. }
  69. cmd := &cobra.Command{
  70. Use: "build [OPTIONS] [SERVICE...]",
  71. Short: "Build or rebuild services",
  72. PreRunE: Adapt(func(ctx context.Context, args []string) error {
  73. if opts.quiet {
  74. ui.Mode = ui.ModeQuiet
  75. devnull, err := os.Open(os.DevNull)
  76. if err != nil {
  77. return err
  78. }
  79. os.Stdout = devnull
  80. }
  81. return nil
  82. }),
  83. RunE: AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error {
  84. if cmd.Flags().Changed("ssh") && opts.ssh == "" {
  85. opts.ssh = "default"
  86. }
  87. if cmd.Flags().Changed("progress") && opts.ssh == "" {
  88. fmt.Fprint(os.Stderr, "--progress is a global compose flag, better use `docker compose --progress xx build ...")
  89. }
  90. return runBuild(ctx, backend, opts, args)
  91. }),
  92. ValidArgsFunction: completeServiceNames(p),
  93. }
  94. cmd.Flags().BoolVar(&opts.push, "push", false, "Push service images.")
  95. cmd.Flags().BoolVarP(&opts.quiet, "quiet", "q", false, "Don't print anything to STDOUT")
  96. cmd.Flags().BoolVar(&opts.pull, "pull", false, "Always attempt to pull a newer version of the image.")
  97. cmd.Flags().StringArrayVar(&opts.args, "build-arg", []string{}, "Set build-time variables for services.")
  98. cmd.Flags().StringVar(&opts.ssh, "ssh", "", "Set SSH authentications used when building service images. (use 'default' for using your default SSH Agent)")
  99. cmd.Flags().StringVar(&opts.builder, "builder", "", "Set builder to use.")
  100. cmd.Flags().Bool("parallel", true, "Build images in parallel. DEPRECATED")
  101. cmd.Flags().MarkHidden("parallel") //nolint:errcheck
  102. cmd.Flags().Bool("compress", true, "Compress the build context using gzip. DEPRECATED")
  103. cmd.Flags().MarkHidden("compress") //nolint:errcheck
  104. cmd.Flags().Bool("force-rm", true, "Always remove intermediate containers. DEPRECATED")
  105. cmd.Flags().MarkHidden("force-rm") //nolint:errcheck
  106. cmd.Flags().BoolVar(&opts.noCache, "no-cache", false, "Do not use cache when building the image")
  107. cmd.Flags().Bool("no-rm", false, "Do not remove intermediate containers after a successful build. DEPRECATED")
  108. cmd.Flags().MarkHidden("no-rm") //nolint:errcheck
  109. cmd.Flags().VarP(&opts.memory, "memory", "m", "Set memory limit for the build container. Not supported by BuildKit.")
  110. cmd.Flags().StringVar(progress, "progress", buildx.PrinterModeAuto, fmt.Sprintf(`Set type of ui output (%s)`, strings.Join(printerModes, ", ")))
  111. cmd.Flags().MarkHidden("progress") //nolint:errcheck
  112. return cmd
  113. }
  114. func runBuild(ctx context.Context, backend api.Service, opts buildOptions, services []string) error {
  115. project, err := opts.ToProject(services, cli.WithResolvedPaths(true))
  116. if err != nil {
  117. return err
  118. }
  119. apiBuildOptions, err := opts.toAPIBuildOptions(services)
  120. if err != nil {
  121. return err
  122. }
  123. apiBuildOptions.Memory = int64(opts.memory)
  124. return backend.Build(ctx, project, apiBuildOptions)
  125. }