ps.go 812 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package cmd
  2. import (
  3. "fmt"
  4. "os"
  5. "text/tabwriter"
  6. "github.com/pkg/errors"
  7. "github.com/spf13/cobra"
  8. "github.com/docker/api/client"
  9. )
  10. // PsCommand lists containers
  11. var PsCommand = cobra.Command{
  12. Use: "ps",
  13. Short: "List containers",
  14. RunE: func(cmd *cobra.Command, args []string) error {
  15. ctx := cmd.Context()
  16. c, err := client.New(ctx)
  17. if err != nil {
  18. return errors.Wrap(err, "cannot connect to backend")
  19. }
  20. containers, err := c.ContainerService().List(ctx)
  21. if err != nil {
  22. return errors.Wrap(err, "fetch containers")
  23. }
  24. w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
  25. fmt.Fprintf(w, "NAME\tIMAGE\tSTATUS\tCOMMAND\n")
  26. format := "%s\t%s\t%s\t%s\n"
  27. for _, c := range containers {
  28. fmt.Fprintf(w, format, c.ID, c.Image, c.Status, c.Command)
  29. }
  30. return w.Flush()
  31. },
  32. }