ps.go 781 B

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