ps.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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/cli/formatter"
  10. "github.com/docker/api/client"
  11. )
  12. type psOpts struct {
  13. all bool
  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. cmd.Flags().BoolVarP(&opts.all, "all", "a", false, "Show all containers (default shows just running)")
  28. return cmd
  29. }
  30. func runPs(ctx context.Context, opts psOpts) error {
  31. c, err := client.New(ctx)
  32. if err != nil {
  33. return errors.Wrap(err, "cannot connect to backend")
  34. }
  35. containers, err := c.ContainerService().List(ctx, opts.all)
  36. if err != nil {
  37. return errors.Wrap(err, "fetch containers")
  38. }
  39. if opts.quiet {
  40. for _, c := range containers {
  41. fmt.Println(c.ID)
  42. }
  43. return nil
  44. }
  45. w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
  46. fmt.Fprintf(w, "CONTAINER ID\tIMAGE\tCOMMAND\tSTATUS\tPORTS\n")
  47. format := "%s\t%s\t%s\t%s\t%s\n"
  48. for _, c := range containers {
  49. fmt.Fprintf(w, format, c.ID, c.Image, c.Command, c.Status, formatter.PortsString(c.Ports))
  50. }
  51. return w.Flush()
  52. }