formatter.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package ps
  2. import (
  3. "io"
  4. "github.com/docker/docker/api/types"
  5. )
  6. const (
  7. tableFormatKey = "table"
  8. rawFormatKey = "raw"
  9. defaultTableFormat = "table {{.ID}}\t{{.Image}}\t{{.Command}}\t{{.RunningFor}} ago\t{{.Status}}\t{{.Ports}}\t{{.Names}}"
  10. defaultQuietFormat = "{{.ID}}"
  11. )
  12. // Context contains information required by the formatter to print the output as desired.
  13. type Context struct {
  14. // Output is the output stream to which the formatted string is written.
  15. Output io.Writer
  16. // Format is used to choose raw, table or custom format for the output.
  17. Format string
  18. // Size when set to true will display the size of the output.
  19. Size bool
  20. // Quiet when set to true will simply print minimal information.
  21. Quiet bool
  22. // Trunc when set to true will truncate the output of certain fields such as Container ID.
  23. Trunc bool
  24. }
  25. // Format helps to format the output using the parameters set in the Context.
  26. // Currently Format allow to display in raw, table or custom format the output.
  27. func Format(ctx Context, containers []types.Container) {
  28. switch ctx.Format {
  29. case tableFormatKey:
  30. tableFormat(ctx, containers)
  31. case rawFormatKey:
  32. rawFormat(ctx, containers)
  33. default:
  34. customFormat(ctx, containers)
  35. }
  36. }
  37. func rawFormat(ctx Context, containers []types.Container) {
  38. if ctx.Quiet {
  39. ctx.Format = `container_id: {{.ID}}`
  40. } else {
  41. ctx.Format = `container_id: {{.ID}}
  42. image: {{.Image}}
  43. command: {{.Command}}
  44. created_at: {{.CreatedAt}}
  45. status: {{.Status}}
  46. names: {{.Names}}
  47. labels: {{.Labels}}
  48. ports: {{.Ports}}
  49. `
  50. if ctx.Size {
  51. ctx.Format += `size: {{.Size}}
  52. `
  53. }
  54. }
  55. customFormat(ctx, containers)
  56. }
  57. func tableFormat(ctx Context, containers []types.Container) {
  58. ctx.Format = defaultTableFormat
  59. if ctx.Quiet {
  60. ctx.Format = defaultQuietFormat
  61. }
  62. customFormat(ctx, containers)
  63. }