wait.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package container
  2. import (
  3. "fmt"
  4. "strings"
  5. "golang.org/x/net/context"
  6. "github.com/docker/docker/api/client"
  7. "github.com/docker/docker/cli"
  8. "github.com/spf13/cobra"
  9. )
  10. type waitOptions struct {
  11. containers []string
  12. }
  13. // NewWaitCommand creates a new cobra.Command for `docker wait`
  14. func NewWaitCommand(dockerCli *client.DockerCli) *cobra.Command {
  15. var opts waitOptions
  16. cmd := &cobra.Command{
  17. Use: "wait CONTAINER [CONTAINER...]",
  18. Short: "Block until a container stops, then print its exit code",
  19. Args: cli.RequiresMinArgs(1),
  20. RunE: func(cmd *cobra.Command, args []string) error {
  21. opts.containers = args
  22. return runWait(dockerCli, &opts)
  23. },
  24. }
  25. cmd.SetFlagErrorFunc(flagErrorFunc)
  26. return cmd
  27. }
  28. func runWait(dockerCli *client.DockerCli, opts *waitOptions) error {
  29. ctx := context.Background()
  30. var errs []string
  31. for _, container := range opts.containers {
  32. status, err := dockerCli.Client().ContainerWait(ctx, container)
  33. if err != nil {
  34. errs = append(errs, err.Error())
  35. } else {
  36. fmt.Fprintf(dockerCli.Out(), "%d\n", status)
  37. }
  38. }
  39. if len(errs) > 0 {
  40. return fmt.Errorf("%s", strings.Join(errs, "\n"))
  41. }
  42. return nil
  43. }