ps.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "text/tabwriter"
  7. "github.com/docker/docker/pkg/stringid"
  8. "github.com/pkg/errors"
  9. "github.com/spf13/cobra"
  10. "github.com/docker/api/cli/formatter"
  11. "github.com/docker/api/client"
  12. )
  13. type psOpts struct {
  14. quiet bool
  15. }
  16. // PsCommand lists containers
  17. func PsCommand() *cobra.Command {
  18. var opts psOpts
  19. cmd := &cobra.Command{
  20. Use: "ps",
  21. Short: "List containers",
  22. RunE: func(cmd *cobra.Command, args []string) error {
  23. return runPs(cmd.Context(), opts)
  24. },
  25. }
  26. cmd.Flags().BoolVarP(&opts.quiet, "quiet", "q", false, "Only display IDs")
  27. return cmd
  28. }
  29. func runPs(ctx context.Context, opts psOpts) error {
  30. c, err := client.New(ctx)
  31. if err != nil {
  32. return errors.Wrap(err, "cannot connect to backend")
  33. }
  34. containers, err := c.ContainerService().List(ctx)
  35. if err != nil {
  36. return errors.Wrap(err, "fetch containers")
  37. }
  38. if opts.quiet {
  39. for _, c := range containers {
  40. fmt.Println(c.ID)
  41. }
  42. return nil
  43. }
  44. w := tabwriter.NewWriter(os.Stdout, 0, 0, 8, ' ', 0)
  45. fmt.Fprintf(w, "CONTAINER ID\tIMAGE\tCOMMAND\tSTATUS\tPORTS\n")
  46. format := "%s\t%s\t%s\t%s\t%s\n"
  47. for _, c := range containers {
  48. fmt.Fprintf(w, format, stringid.TruncateID(c.ID), c.Image, c.Command, c.Status, formatter.PortsString(c.Ports))
  49. }
  50. return w.Flush()
  51. }