build.go 2.1 KB

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