File: table_printer.go

package info (click to toggle)
golang-github-pterm-pterm 0.12.79-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,640 kB
  • sloc: makefile: 4
file content (288 lines) | stat: -rw-r--r-- 7,386 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
package pterm

import (
	"encoding/csv"
	"io"
	"strings"

	"github.com/pterm/pterm/internal"
)

// DefaultTable contains standards, which can be used to print a TablePrinter.
var DefaultTable = TablePrinter{
	Style:                   &ThemeDefault.TableStyle,
	HeaderStyle:             &ThemeDefault.TableHeaderStyle,
	HeaderRowSeparator:      "",
	HeaderRowSeparatorStyle: &ThemeDefault.TableSeparatorStyle,
	Separator:               " | ",
	SeparatorStyle:          &ThemeDefault.TableSeparatorStyle,
	RowSeparator:            "",
	RowSeparatorStyle:       &ThemeDefault.TableSeparatorStyle,
	LeftAlignment:           true,
	RightAlignment:          false,
}

// TableData is the type that contains the data of a TablePrinter.
type TableData [][]string

// TablePrinter is able to render tables.
type TablePrinter struct {
	Style                   *Style
	HasHeader               bool
	HeaderStyle             *Style
	HeaderRowSeparator      string
	HeaderRowSeparatorStyle *Style
	Separator               string
	SeparatorStyle          *Style
	RowSeparator            string
	RowSeparatorStyle       *Style
	Data                    TableData
	Boxed                   bool
	LeftAlignment           bool
	RightAlignment          bool
	Writer                  io.Writer
}

// WithStyle returns a new TablePrinter with a specific Style.
func (p TablePrinter) WithStyle(style *Style) *TablePrinter {
	p.Style = style
	return &p
}

// WithHasHeader returns a new TablePrinter, where the first line is marked as a header.
func (p TablePrinter) WithHasHeader(b ...bool) *TablePrinter {
	p.HasHeader = internal.WithBoolean(b)
	return &p
}

// WithHeaderStyle returns a new TablePrinter with a specific HeaderStyle.
func (p TablePrinter) WithHeaderStyle(style *Style) *TablePrinter {
	p.HeaderStyle = style
	return &p
}

// WithHeaderRowSeparator returns a new TablePrinter with a specific header HeaderRowSeparator.
func (p TablePrinter) WithHeaderRowSeparator(separator string) *TablePrinter {
	p.HeaderRowSeparator = separator
	return &p
}

// WithHeaderRowSeparatorStyle returns a new TablePrinter with a specific header HeaderRowSeparatorStyle.
func (p TablePrinter) WithHeaderRowSeparatorStyle(style *Style) *TablePrinter {
	p.HeaderRowSeparatorStyle = style
	return &p
}

// WithSeparator returns a new TablePrinter with a specific separator.
func (p TablePrinter) WithSeparator(separator string) *TablePrinter {
	p.Separator = separator
	return &p
}

// WithSeparatorStyle returns a new TablePrinter with a specific SeparatorStyle.
func (p TablePrinter) WithSeparatorStyle(style *Style) *TablePrinter {
	p.SeparatorStyle = style
	return &p
}

// WithRowSeparator returns a new TablePrinter with a specific RowSeparator.
func (p TablePrinter) WithRowSeparator(separator string) *TablePrinter {
	p.RowSeparator = separator
	return &p
}

// WithRowSeparatorStyle returns a new TablePrinter with a specific RowSeparatorStyle.
func (p TablePrinter) WithRowSeparatorStyle(style *Style) *TablePrinter {
	p.RowSeparatorStyle = style
	return &p
}

// WithData returns a new TablePrinter with specific Data.
func (p TablePrinter) WithData(data [][]string) *TablePrinter {
	p.Data = data
	return &p
}

// WithCSVReader return a new TablePrinter with specified Data extracted from CSV.
func (p TablePrinter) WithCSVReader(reader *csv.Reader) *TablePrinter {
	if records, err := reader.ReadAll(); err == nil {
		p.Data = records
	}
	return &p
}

// WithBoxed returns a new TablePrinter with a box around the table.
func (p TablePrinter) WithBoxed(b ...bool) *TablePrinter {
	p.Boxed = internal.WithBoolean(b)
	return &p
}

// WithLeftAlignment returns a new TablePrinter with left alignment.
func (p TablePrinter) WithLeftAlignment(b ...bool) *TablePrinter {
	b2 := internal.WithBoolean(b)
	p.LeftAlignment = b2
	p.RightAlignment = false
	return &p
}

// WithRightAlignment returns a new TablePrinter with right alignment.
func (p TablePrinter) WithRightAlignment(b ...bool) *TablePrinter {
	b2 := internal.WithBoolean(b)
	p.LeftAlignment = false
	p.RightAlignment = b2
	return &p
}

// WithWriter sets the Writer.
func (p TablePrinter) WithWriter(writer io.Writer) *TablePrinter {
	p.Writer = writer
	return &p
}

type table struct {
	rows            []row
	maxColumnWidths []int
}

type row struct {
	height       int
	cells        []cell
	columnWidths []int
}

type cell struct {
	width  int
	height int
	lines  []string
}

// Srender renders the TablePrinter as a string.
func (p TablePrinter) Srender() (string, error) {
	if p.Style == nil {
		p.Style = NewStyle()
	}
	if p.SeparatorStyle == nil {
		p.SeparatorStyle = NewStyle()
	}
	if p.HeaderStyle == nil {
		p.HeaderStyle = NewStyle()
	}
	if p.HeaderRowSeparatorStyle == nil {
		p.HeaderRowSeparatorStyle = NewStyle()
	}
	if p.RowSeparatorStyle == nil {
		p.RowSeparatorStyle = NewStyle()
	}

	var t table

	// convert data to table and calculate values
	for _, rRaw := range p.Data {
		var r row
		for _, cRaw := range rRaw {
			var c cell
			c.lines = strings.Split(cRaw, "\n")
			c.height = len(c.lines)
			for _, l := range c.lines {
				if maxWidth := internal.GetStringMaxWidth(l); maxWidth > c.width {
					c.width = maxWidth
				}
			}
			r.cells = append(r.cells, c)
			if c.height > r.height {
				r.height = c.height
			}
		}

		// set max column widths of table
		for i, c := range r.cells {
			if len(t.maxColumnWidths) <= i {
				t.maxColumnWidths = append(t.maxColumnWidths, c.width)
			} else if c.width > t.maxColumnWidths[i] {
				t.maxColumnWidths[i] = c.width
			}
		}

		t.rows = append(t.rows, r)
	}

	var maxRowWidth int
	for _, r := range t.rows {
		rowWidth := internal.GetStringMaxWidth(p.renderRow(t, r))
		if rowWidth > maxRowWidth {
			maxRowWidth = rowWidth
		}
	}

	// render table
	var s string

	for i, r := range t.rows {
		if i == 0 && p.HasHeader {
			s += p.HeaderStyle.Sprint(p.renderRow(t, r))

			if p.HeaderRowSeparator != "" {
				s += strings.Repeat(p.HeaderRowSeparatorStyle.Sprint(p.HeaderRowSeparator), maxRowWidth) + "\n"
			}
			continue
		}

		s += p.renderRow(t, r)

		if p.RowSeparator != "" {
			s += strings.Repeat(p.RowSeparatorStyle.Sprint(p.RowSeparator), maxRowWidth) + "\n"
		}
	}

	if p.Boxed {
		s = DefaultBox.Sprint(strings.TrimSuffix(s, "\n"))
	}

	return s, nil
}

// renderRow renders a row.
// It merges the cells of a row into one string.
// Each line of each cell is merged with the same line of the other cells.
func (p TablePrinter) renderRow(t table, r row) string {
	var s string

	// merge lines of cells and add separator
	// use the t.maxColumnWidths to add padding to the corresponding cell
	// a newline in a cell should be in the same column as the original cell
	for i := 0; i < r.height; i++ {
		for j, c := range r.cells {
			var currentLine string
			if i < len(c.lines) {
				currentLine = c.lines[i]
			}
			paddingForLine := t.maxColumnWidths[j] - internal.GetStringMaxWidth(currentLine)

			if p.RightAlignment {
				s += strings.Repeat(" ", paddingForLine)
			}

			if i < len(c.lines) {
				s += c.lines[i]
			}

			if j < len(r.cells)-1 {
				if p.LeftAlignment {
					s += strings.Repeat(" ", paddingForLine)
				}
				s += p.SeparatorStyle.Sprint(p.Separator)
			}
		}
		s += "\n"
	}

	return s
}

// Render prints the TablePrinter to the terminal.
func (p TablePrinter) Render() error {
	s, _ := p.Srender()
	Fprintln(p.Writer, s)

	return nil
}