table.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. // Package table provides a convenient way to generate tabular output of any
  2. // data, primarily useful for CLI tools.
  3. //
  4. // Columns are left-aligned and padded to accomodate the largest cell in that
  5. // column.
  6. //
  7. // Source: https://github.com/rodaine/table
  8. //
  9. // table.DefaultHeaderFormatter = func(format string, vals ...interface{}) string {
  10. // return strings.ToUpper(fmt.Sprintf(format, vals...))
  11. // }
  12. //
  13. // tbl := table.New("ID", "Name", "Cost ($)")
  14. //
  15. // for _, widget := range Widgets {
  16. // tbl.AddRow(widget.ID, widget.Name, widget.Cost)
  17. // }
  18. //
  19. // tbl.Print()
  20. //
  21. // // Output:
  22. // // ID NAME COST ($)
  23. // // 1 Foobar 1.23
  24. // // 2 Fizzbuzz 4.56
  25. // // 3 Gizmo 78.90
  26. package table
  27. import (
  28. "fmt"
  29. "io"
  30. "os"
  31. "strings"
  32. "unicode/utf8"
  33. )
  34. // These are the default properties for all Tables created from this package
  35. // and can be modified.
  36. var (
  37. // DefaultPadding specifies the number of spaces between columns in a table.
  38. DefaultPadding = 2
  39. // DefaultWriter specifies the output io.Writer for the Table.Print method.
  40. DefaultWriter io.Writer = os.Stdout
  41. // DefaultHeaderFormatter specifies the default Formatter for the table header.
  42. DefaultHeaderFormatter Formatter
  43. // DefaultFirstColumnFormatter specifies the default Formatter for the first column cells.
  44. DefaultFirstColumnFormatter Formatter
  45. // DefaultWidthFunc specifies the default WidthFunc for calculating column widths
  46. DefaultWidthFunc WidthFunc = utf8.RuneCountInString
  47. )
  48. // Formatter functions expose a fmt.Sprintf signature that can be used to modify
  49. // the display of the text in either the header or first column of a Table.
  50. // The formatter should not change the width of original text as printed since
  51. // column widths are calculated pre-formatting (though this issue can be mitigated
  52. // with increased padding).
  53. //
  54. // tbl.WithHeaderFormatter(func(format string, vals ...interface{}) string {
  55. // return strings.ToUpper(fmt.Sprintf(format, vals...))
  56. // })
  57. //
  58. // A good use case for formatters is to use ANSI escape codes to color the cells
  59. // for a nicer interface. The package color (https://github.com/fatih/color) makes
  60. // it easy to generate these automatically: http://godoc.org/github.com/fatih/color#Color.SprintfFunc
  61. type Formatter func(string, ...interface{}) string
  62. // A WidthFunc calculates the width of a string. By default, the number of runes
  63. // is used but this may not be appropriate for certain character sets. The
  64. // package runewidth (https://github.com/mattn/go-runewidth) could be used to
  65. // accomodate multi-cell characters (such as emoji or CJK characters).
  66. type WidthFunc func(string) int
  67. // Table describes the interface for building up a tabular representation of data.
  68. // It exposes fluent/chainable methods for convenient table building.
  69. //
  70. // WithHeaderFormatter and WithFirstColumnFormatter sets the Formatter for the
  71. // header and first column, respectively. If nil is passed in (the default), no
  72. // formatting will be applied.
  73. //
  74. // New("foo", "bar").WithFirstColumnFormatter(func(f string, v ...interface{}) string {
  75. // return strings.ToUpper(fmt.Sprintf(f, v...))
  76. // })
  77. //
  78. // WithPadding specifies the minimum padding between cells in a row and defaults
  79. // to DefaultPadding. Padding values less than or equal to zero apply no extra
  80. // padding between the columns.
  81. //
  82. // New("foo", "bar").WithPadding(3)
  83. //
  84. // WithWriter modifies the writer which Print outputs to, defaulting to DefaultWriter
  85. // when instantiated. If nil is passed, os.Stdout will be used.
  86. //
  87. // New("foo", "bar").WithWriter(os.Stderr)
  88. //
  89. // WithWidthFunc sets the function used to calculate the width of the string in
  90. // a column. By default, the number of utf8 runes in the string is used.
  91. //
  92. // AddRow adds another row of data to the table. Any values can be passed in and
  93. // will be output as its string representation as described in the fmt standard
  94. // package. Rows can have less cells than the total number of columns in the table;
  95. // subsequent cells will be rendered empty. Rows with more cells than the total
  96. // number of columns will be truncated. References to the data are not held, so
  97. // the passed in values can be modified without affecting the table's output.
  98. //
  99. // New("foo", "bar").AddRow("fizz", "buzz").AddRow(time.Now()).AddRow(1, 2, 3).Print()
  100. // // Output:
  101. // // foo bar
  102. // // fizz buzz
  103. // // 2006-01-02 15:04:05.0 -0700 MST
  104. // // 1 2
  105. //
  106. // Print writes the string representation of the table to the provided writer.
  107. // Print can be called multiple times, even after subsequent mutations of the
  108. // provided data. The output is always preceded and followed by a new line.
  109. type Table interface {
  110. WithHeaderFormatter(f Formatter) Table
  111. WithFirstColumnFormatter(f Formatter) Table
  112. WithPadding(p int) Table
  113. WithWriter(w io.Writer) Table
  114. WithWidthFunc(f WidthFunc) Table
  115. AddRow(vals ...interface{}) Table
  116. Print()
  117. }
  118. // New creates a Table instance with the specified header(s) provided. The number
  119. // of columns is fixed at this point to len(columnHeaders) and the defined defaults
  120. // are set on the instance.
  121. func New(columnHeaders ...interface{}) Table {
  122. t := table{header: make([]string, len(columnHeaders))}
  123. t.WithPadding(DefaultPadding)
  124. t.WithWriter(DefaultWriter)
  125. t.WithHeaderFormatter(DefaultHeaderFormatter)
  126. t.WithFirstColumnFormatter(DefaultFirstColumnFormatter)
  127. t.WithWidthFunc(DefaultWidthFunc)
  128. for i, col := range columnHeaders {
  129. t.header[i] = fmt.Sprint(col)
  130. }
  131. return &t
  132. }
  133. type table struct {
  134. FirstColumnFormatter Formatter
  135. HeaderFormatter Formatter
  136. Padding int
  137. Writer io.Writer
  138. Width WidthFunc
  139. header []string
  140. rows [][]string
  141. widths []int
  142. }
  143. func (t *table) WithHeaderFormatter(f Formatter) Table {
  144. t.HeaderFormatter = f
  145. return t
  146. }
  147. func (t *table) WithFirstColumnFormatter(f Formatter) Table {
  148. t.FirstColumnFormatter = f
  149. return t
  150. }
  151. func (t *table) WithPadding(p int) Table {
  152. if p < 0 {
  153. p = 0
  154. }
  155. t.Padding = p
  156. return t
  157. }
  158. func (t *table) WithWriter(w io.Writer) Table {
  159. if w == nil {
  160. w = os.Stdout
  161. }
  162. t.Writer = w
  163. return t
  164. }
  165. func (t *table) WithWidthFunc(f WidthFunc) Table {
  166. t.Width = f
  167. return t
  168. }
  169. func (t *table) AddRow(vals ...interface{}) Table {
  170. row := make([]string, len(t.header))
  171. for i, val := range vals {
  172. if i >= len(t.header) {
  173. break
  174. }
  175. row[i] = fmt.Sprint(val)
  176. }
  177. t.rows = append(t.rows, row)
  178. return t
  179. }
  180. func (t *table) Print() {
  181. format := strings.Repeat("%s", len(t.header)) + "\n"
  182. t.calculateWidths()
  183. fmt.Fprintln(t.Writer)
  184. t.printHeader(format)
  185. for _, row := range t.rows {
  186. t.printRow(format, row)
  187. }
  188. }
  189. func (t *table) printHeader(format string) {
  190. vals := t.applyWidths(t.header, t.widths)
  191. if t.HeaderFormatter != nil {
  192. txt := t.HeaderFormatter(format, vals...)
  193. fmt.Fprint(t.Writer, txt)
  194. } else {
  195. fmt.Fprintf(t.Writer, format, vals...)
  196. }
  197. }
  198. func (t *table) printRow(format string, row []string) {
  199. vals := t.applyWidths(row, t.widths)
  200. if t.FirstColumnFormatter != nil {
  201. vals[0] = t.FirstColumnFormatter("%s", vals[0])
  202. }
  203. fmt.Fprintf(t.Writer, format, vals...)
  204. }
  205. func (t *table) calculateWidths() {
  206. t.widths = make([]int, len(t.header))
  207. for _, row := range t.rows {
  208. for i, v := range row {
  209. if w := t.Width(v) + t.Padding; w > t.widths[i] {
  210. t.widths[i] = w
  211. }
  212. }
  213. }
  214. for i, v := range t.header {
  215. if w := t.Width(v) + t.Padding; w > t.widths[i] {
  216. t.widths[i] = w
  217. }
  218. }
  219. }
  220. func (t *table) applyWidths(row []string, widths []int) []interface{} {
  221. out := make([]interface{}, len(row))
  222. for i, s := range row {
  223. out[i] = s + t.lenOffset(s, widths[i])
  224. }
  225. return out
  226. }
  227. func (t *table) lenOffset(s string, w int) string {
  228. l := w - t.Width(s)
  229. if l <= 0 {
  230. return ""
  231. }
  232. return strings.Repeat(" ", l)
  233. }