build.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. "os"
  17. "github.com/compose-spec/compose-go/types"
  18. "github.com/spf13/cobra"
  19. "github.com/docker/compose-cli/api/client"
  20. "github.com/docker/compose-cli/api/compose"
  21. "github.com/docker/compose-cli/api/progress"
  22. )
  23. type buildOptions struct {
  24. *projectOptions
  25. composeOptions
  26. quiet bool
  27. pull bool
  28. progress string
  29. args []string
  30. }
  31. func buildCommand(p *projectOptions) *cobra.Command {
  32. opts := buildOptions{
  33. projectOptions: p,
  34. }
  35. cmd := &cobra.Command{
  36. Use: "build [SERVICE...]",
  37. Short: "Build or rebuild services",
  38. RunE: func(cmd *cobra.Command, args []string) error {
  39. if opts.quiet {
  40. devnull, err := os.Open(os.DevNull)
  41. if err != nil {
  42. return err
  43. }
  44. os.Stdout = devnull
  45. }
  46. return runBuild(cmd.Context(), opts, args)
  47. },
  48. }
  49. cmd.Flags().BoolVarP(&opts.quiet, "quiet", "q", false, "Don't print anything to STDOUT")
  50. cmd.Flags().BoolVar(&opts.pull, "pull", false, "Always attempt to pull a newer version of the image.")
  51. cmd.Flags().StringVar(&opts.progress, "progress", "auto", `Set type of progress output ("auto", "plain", "tty")`)
  52. cmd.Flags().StringArrayVar(&opts.args, "build-arg", []string{}, "Set build-time variables for services.")
  53. return cmd
  54. }
  55. func runBuild(ctx context.Context, opts buildOptions, services []string) error {
  56. c, err := client.NewWithDefaultLocalBackend(ctx)
  57. if err != nil {
  58. return err
  59. }
  60. project, err := opts.toProject(services)
  61. if err != nil {
  62. return err
  63. }
  64. _, err = progress.Run(ctx, func(ctx context.Context) (string, error) {
  65. return "", c.ComposeService().Build(ctx, project, compose.BuildOptions{
  66. Pull: opts.pull,
  67. Progress: opts.progress,
  68. Args: types.NewMapping(opts.args),
  69. })
  70. })
  71. return err
  72. }