Add possibility to set a max width for each column

main
Stefano 2021-11-17 21:32:38 +01:00
parent d705166019
commit b465f6e9b6
1 changed files with 15 additions and 3 deletions

View File

@ -8,9 +8,10 @@ import (
type Row []string type Row []string
type TablePrinter struct { type TablePrinter struct {
Headers []string Headers []string
Rows []Row Rows []Row
MaxRows int MaxRows int
MaxWidths []int
} }
func NewTablePrinter(headers []string) *TablePrinter { func NewTablePrinter(headers []string) *TablePrinter {
@ -20,6 +21,10 @@ func NewTablePrinter(headers []string) *TablePrinter {
} }
} }
func (printer *TablePrinter) SetMaxWidths(widths []int) {
printer.MaxWidths = widths
}
func centerString(s string, width int) string { func centerString(s string, width int) string {
padSpace := width - len(s) padSpace := width - len(s)
leftPadding := padSpace / 2 leftPadding := padSpace / 2
@ -70,6 +75,13 @@ func (printer *TablePrinter) computeColumnWidthds() []int {
for i := 0; i < printer.NumCols(); i++ { for i := 0; i < printer.NumCols(); i++ {
widths[i] += paddingDefault widths[i] += paddingDefault
if printer.MaxWidths != nil {
if printer.MaxWidths[i] > 0 && widths[i] > printer.MaxWidths[i] {
widths[i] = printer.MaxWidths[i]
}
}
} }
return widths return widths
} }