watch.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. "github.com/docker/cli/cli/command"
  19. "github.com/docker/compose/v2/internal/locker"
  20. "github.com/docker/compose/v2/pkg/api"
  21. "github.com/spf13/cobra"
  22. )
  23. type watchOptions struct {
  24. *ProjectOptions
  25. quiet bool
  26. }
  27. func watchCommand(p *ProjectOptions, dockerCli command.Cli, backend api.Service) *cobra.Command {
  28. opts := watchOptions{
  29. ProjectOptions: p,
  30. }
  31. cmd := &cobra.Command{
  32. Use: "watch [SERVICE...]",
  33. Short: "EXPERIMENTAL - Watch build context for service and rebuild/refresh containers when files are updated",
  34. PreRunE: Adapt(func(ctx context.Context, args []string) error {
  35. return nil
  36. }),
  37. RunE: Adapt(func(ctx context.Context, args []string) error {
  38. return runWatch(ctx, dockerCli, backend, opts, args)
  39. }),
  40. ValidArgsFunction: completeServiceNames(dockerCli, p),
  41. }
  42. cmd.Flags().BoolVar(&opts.quiet, "quiet", false, "hide build output")
  43. return cmd
  44. }
  45. func runWatch(ctx context.Context, dockerCli command.Cli, backend api.Service, opts watchOptions, services []string) error {
  46. fmt.Fprintln(os.Stderr, "watch command is EXPERIMENTAL")
  47. project, err := opts.ToProject(dockerCli, nil)
  48. if err != nil {
  49. return err
  50. }
  51. l, err := locker.NewPidfile(project.Name)
  52. if err != nil {
  53. return fmt.Errorf("cannot take exclusive lock for project %q: %v", project.Name, err)
  54. }
  55. if err := l.Lock(); err != nil {
  56. return fmt.Errorf("cannot take exclusive lock for project %q: %v", project.Name, err)
  57. }
  58. return backend.Watch(ctx, project, services, api.WatchOptions{})
  59. }