ps.go 1.1 KB

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