From 6d722ac3871b2ad7c92f4f146b80f6845f653152 Mon Sep 17 00:00:00 2001 From: Pedro Coelho Date: Fri, 2 Aug 2024 15:55:10 +0100 Subject: [PATCH] Allow for optional headers (#29) * Allow for omitting the header when printing * Add documentation for WithPrintHeaders --- table.go | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/table.go b/table.go index a0270fe..ccd5124 100644 --- a/table.go +++ b/table.go @@ -50,6 +50,9 @@ var ( // DefaultWidthFunc specifies the default WidthFunc for calculating column widths DefaultWidthFunc WidthFunc = utf8.RuneCountInString + + // DefaultPrintHeaders specifies if headers should be printed + DefaultPrintHeaders = true ) // Formatter functions expose a fmt.Sprintf signature that can be used to modify @@ -98,6 +101,10 @@ type WidthFunc func(string) int // WithWidthFunc sets the function used to calculate the width of the string in // a column. By default, the number of utf8 runes in the string is used. // +// WithPrintHeaders specifies whether if the headers of the table should be +// printed or not, which might be useful if the output is being piped to other +// processes. By default, they are printed. +// // AddRow adds another row of data to the table. Any values can be passed in and // will be output as its string representation as described in the fmt standard // package. Rows can have less cells than the total number of columns in the table; @@ -122,6 +129,7 @@ type Table interface { WithWriter(w io.Writer) Table WithWidthFunc(f WidthFunc) Table WithHeaderSeparatorRow(r rune) Table + WithPrintHeaders(b bool) Table AddRow(vals ...interface{}) Table SetRows(rows [][]string) Table @@ -139,6 +147,7 @@ func New(columnHeaders ...interface{}) Table { t.WithHeaderFormatter(DefaultHeaderFormatter) t.WithFirstColumnFormatter(DefaultFirstColumnFormatter) t.WithWidthFunc(DefaultWidthFunc) + t.WithPrintHeaders(DefaultPrintHeaders) for i, col := range columnHeaders { t.header[i] = fmt.Sprint(col) @@ -154,6 +163,7 @@ type table struct { Writer io.Writer Width WidthFunc HeaderSeparatorRune rune + PrintHeaders bool header []string rows [][]string @@ -198,6 +208,11 @@ func (t *table) WithWidthFunc(f WidthFunc) Table { return t } +func (t *table) WithPrintHeaders(b bool) Table { + t.PrintHeaders = b + return t +} + func (t *table) AddRow(vals ...interface{}) Table { maxNumNewlines := 0 for _, val := range vals { @@ -237,10 +252,14 @@ func (t *table) Print() { format := strings.Repeat("%s", len(t.header)) + "\n" t.calculateWidths() - t.printHeader(format) - if t.HeaderSeparatorRune != 0 { - t.printHeaderSeparator(format) - } + if t.PrintHeaders { + t.printHeader(format) + + if t.HeaderSeparatorRune != 0 { + t.printHeaderSeparator(format) + } + } + for _, row := range t.rows { t.printRow(format, row) }