Skip to content

Commit

Permalink
Allow for optional headers (#29)
Browse files Browse the repository at this point in the history
* Allow for omitting the header when printing

* Add documentation for WithPrintHeaders
  • Loading branch information
punnie committed Aug 2, 2024
1 parent 863add3 commit 6d722ac
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions table.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand All @@ -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
Expand All @@ -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)
Expand All @@ -154,6 +163,7 @@ type table struct {
Writer io.Writer
Width WidthFunc
HeaderSeparatorRune rune
PrintHeaders bool

header []string
rows [][]string
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
}
Expand Down

0 comments on commit 6d722ac

Please sign in to comment.