Write prints the table to w.
(w io.Writer)
| 113 | |
| 114 | // Write prints the table to w. |
| 115 | func (t *Table) Write(w io.Writer) error { |
| 116 | columns := len(t.templates) |
| 117 | if columns == 0 { |
| 118 | return nil |
| 119 | } |
| 120 | |
| 121 | // collect all data fields from all columns |
| 122 | lines := make([][]string, 0, len(t.data)) |
| 123 | buf := bytes.NewBuffer(nil) |
| 124 | |
| 125 | for _, data := range t.data { |
| 126 | row := make([]string, 0, len(t.templates)) |
| 127 | for _, tmpl := range t.templates { |
| 128 | err := tmpl.Execute(buf, data) |
| 129 | if err != nil { |
| 130 | return err |
| 131 | } |
| 132 | |
| 133 | row = append(row, buf.String()) |
| 134 | buf.Reset() |
| 135 | } |
| 136 | lines = append(lines, row) |
| 137 | } |
| 138 | |
| 139 | // find max width for each cell |
| 140 | columnWidths := make([]int, columns) |
| 141 | for i, desc := range t.columns { |
| 142 | for _, line := range strings.Split(desc, "\n") { |
| 143 | width := ui.DisplayWidth(line) |
| 144 | if columnWidths[i] < width { |
| 145 | columnWidths[i] = width |
| 146 | } |
| 147 | } |
| 148 | } |
| 149 | for _, line := range lines { |
| 150 | for i, content := range line { |
| 151 | for _, l := range strings.Split(content, "\n") { |
| 152 | width := ui.DisplayWidth(l) |
| 153 | if columnWidths[i] < width { |
| 154 | columnWidths[i] = width |
| 155 | } |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | // calculate the total width of the table |
| 161 | totalWidth := 0 |
| 162 | for _, width := range columnWidths { |
| 163 | totalWidth += width |
| 164 | } |
| 165 | totalWidth += (columns - 1) * ui.DisplayWidth(t.CellSeparator) |
| 166 | |
| 167 | // write header |
| 168 | if len(t.columns) > 0 { |
| 169 | err := printLine(w, t.PrintHeader, t.CellSeparator, t.columns, columnWidths) |
| 170 | if err != nil { |
| 171 | return err |
| 172 | } |