ps.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. all bool
  15. quiet bool
  16. }
  17. // PsCommand lists containers
  18. func PsCommand() *cobra.Command {
  19. var opts psOpts
  20. cmd := &cobra.Command{
  21. Use: "ps",
  22. Short: "List containers",
  23. RunE: func(cmd *cobra.Command, args []string) error {
  24. return runPs(cmd.Context(), opts)
  25. },
  26. }
  27. cmd.Flags().BoolVarP(&opts.quiet, "quiet", "q", false, "Only display IDs")
  28. cmd.Flags().BoolVarP(&opts.all, "all", "a", false, "Show all containers (default shows just running)")
  29. return cmd
  30. }
  31. func runPs(ctx context.Context, opts psOpts) error {
  32. c, err := client.New(ctx)
  33. if err != nil {
  34. return errors.Wrap(err, "cannot connect to backend")
  35. }
  36. containers, err := c.ContainerService().List(ctx, opts.all)
  37. if err != nil {
  38. return errors.Wrap(err, "fetch containers")
  39. }
  40. if opts.quiet {
  41. for _, c := range containers {
  42. fmt.Println(c.ID)
  43. }
  44. return nil
  45. }
  46. w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
  47. fmt.Fprintf(w, "CONTAINER ID\tIMAGE\tCOMMAND\tSTATUS\tPORTS\n")
  48. format := "%s\t%s\t%s\t%s\t%s\n"
  49. for _, c := range containers {
  50. fmt.Fprintf(w, format, stringid.TruncateID(c.ID), c.Image, c.Command, c.Status, formatter.PortsString(c.Ports))
  51. }
  52. return w.Flush()
  53. }