// Copyright 2014 Oleku Konko All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.

// This module is a Table Writer  API for the Go Programming Language.
// The protocols were written in pure Go and works on windows and unix systems

// Create & Generate text based table
package tablewriter import ( ) const ( MAX_ROW_WIDTH = 30 ) const ( CENTER = "+" ROW = "-" COLUMN = "|" SPACE = " " NEWLINE = "\n" ) const ( ALIGN_DEFAULT = iota ALIGN_CENTER ALIGN_RIGHT ALIGN_LEFT ) var ( decimal = regexp.MustCompile(`^-?(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d+)?$`) percent = regexp.MustCompile(`^-?\d+\.?\d*$%$`) ) type Border struct { Left bool Right bool Top bool Bottom bool } type Table struct { out io.Writer rows [][]string lines [][][]string cs map[int]int rs map[int]int headers [][]string footers [][]string caption bool captionText string autoFmt bool autoWrap bool reflowText bool mW int pCenter string pRow string pColumn string tColumn int tRow int hAlign int fAlign int align int newLine string rowLine bool autoMergeCells bool columnsToAutoMergeCells map[int]bool noWhiteSpace bool tablePadding string hdrLine bool borders Border colSize int headerParams []string columnsParams []string footerParams []string columnsAlign []int } // Start New Table // Take io.Writer Directly func ( io.Writer) *Table { := &Table{ out: , rows: [][]string{}, lines: [][][]string{}, cs: make(map[int]int), rs: make(map[int]int), headers: [][]string{}, footers: [][]string{}, caption: false, captionText: "Table caption.", autoFmt: true, autoWrap: true, reflowText: true, mW: MAX_ROW_WIDTH, pCenter: CENTER, pRow: ROW, pColumn: COLUMN, tColumn: -1, tRow: -1, hAlign: ALIGN_DEFAULT, fAlign: ALIGN_DEFAULT, align: ALIGN_DEFAULT, newLine: NEWLINE, rowLine: false, hdrLine: true, borders: Border{Left: true, Right: true, Bottom: true, Top: true}, colSize: -1, headerParams: []string{}, columnsParams: []string{}, footerParams: []string{}, columnsAlign: []int{}} return } // Render table output func ( *Table) () { if .borders.Top { .printLine(true) } .printHeading() if .autoMergeCells { .printRowsMergeCells() } else { .printRows() } if !.rowLine && .borders.Bottom { .printLine(true) } .printFooter() if .caption { .printCaption() } } const ( headerRowIdx = -1 footerRowIdx = -2 ) // Set table header func ( *Table) ( []string) { .colSize = len() for , := range { := .parseDimension(, , headerRowIdx) .headers = append(.headers, ) } } // Set table Footer func ( *Table) ( []string) { //t.colSize = len(keys) for , := range { := .parseDimension(, , footerRowIdx) .footers = append(.footers, ) } } // Set table Caption func ( *Table) ( bool, ...string) { .caption = if len() == 1 { .captionText = [0] } } // Turn header autoformatting on/off. Default is on (true). func ( *Table) ( bool) { .autoFmt = } // Turn automatic multiline text adjustment on/off. Default is on (true). func ( *Table) ( bool) { .autoWrap = } // Turn automatic reflowing of multiline text when rewrapping. Default is on (true). func ( *Table) ( bool) { .reflowText = } // Set the Default column width func ( *Table) ( int) { .mW = } // Set the minimal width for a column func ( *Table) ( int, int) { .cs[] = } // Set the Column Separator func ( *Table) ( string) { .pColumn = } // Set the Row Separator func ( *Table) ( string) { .pRow = } // Set the center Separator func ( *Table) ( string) { .pCenter = } // Set Header Alignment func ( *Table) ( int) { .hAlign = } // Set Footer Alignment func ( *Table) ( int) { .fAlign = } // Set Table Alignment func ( *Table) ( int) { .align = } // Set No White Space func ( *Table) ( bool) { .noWhiteSpace = } // Set Table Padding func ( *Table) ( string) { .tablePadding = } func ( *Table) ( []int) { for , := range { switch { case ALIGN_CENTER: break case ALIGN_LEFT: break case ALIGN_RIGHT: break default: = ALIGN_DEFAULT } .columnsAlign = append(.columnsAlign, ) } } // Set New Line func ( *Table) ( string) { .newLine = } // Set Header Line // This would enable / disable a line after the header func ( *Table) ( bool) { .hdrLine = } // Set Row Line // This would enable / disable a line on each row of the table func ( *Table) ( bool) { .rowLine = } // Set Auto Merge Cells // This would enable / disable the merge of cells with identical values func ( *Table) ( bool) { .autoMergeCells = } // Set Auto Merge Cells By Column Index // This would enable / disable the merge of cells with identical values for specific columns // If cols is empty, it is the same as `SetAutoMergeCells(true)`. func ( *Table) ( []int) { .autoMergeCells = true if len() > 0 { := make(map[int]bool) for , := range { [] = true } .columnsToAutoMergeCells = } } // Set Table Border // This would enable / disable line around the table func ( *Table) ( bool) { .SetBorders(Border{, , , }) } func ( *Table) ( Border) { .borders = } // Append row to table func ( *Table) ( []string) { := len(.headers) if > .colSize { .colSize = } := len(.lines) := [][]string{} for , := range { // Detect string width // Detect String height // Break strings into words := .parseDimension(, , ) // Append broken words = append(, ) } .lines = append(.lines, ) } // Append row to table with color attributes func ( *Table) ( []string, []Colors) { := len(.headers) if > .colSize { .colSize = } := len(.lines) := [][]string{} for , := range { // Detect string width // Detect String height // Break strings into words := .parseDimension(, , ) if len() > { := [] [0] = format([0], ) } // Append broken words = append(, ) } .lines = append(.lines, ) } // Allow Support for Bulk Append // Eliminates repeated for loops func ( *Table) ( [][]string) { for , := range { .Append() } } // NumLines to get the number of lines func ( *Table) () int { return len(.lines) } // Clear rows func ( *Table) () { .lines = [][][]string{} } // Clear footer func ( *Table) () { .footers = [][]string{} } // Center based on position and border. func ( *Table) ( int) string { if == -1 && !.borders.Left { return .pRow } if == len(.cs)-1 && !.borders.Right { return .pRow } return .pCenter } // Print line based on row width func ( *Table) ( bool) { fmt.Fprint(.out, .center(-1)) for := 0; < len(.cs); ++ { := .cs[] fmt.Fprintf(.out, "%s%s%s%s", .pRow, strings.Repeat(string(.pRow), ), .pRow, .center()) } if { fmt.Fprint(.out, .newLine) } } // Print line based on row width with our without cell separator func ( *Table) ( bool, []bool) { fmt.Fprint(.out, .pCenter) for := 0; < len(.cs); ++ { := .cs[] if > len() || [] { // Display the cell separator fmt.Fprintf(.out, "%s%s%s%s", .pRow, strings.Repeat(string(.pRow), ), .pRow, .pCenter) } else { // Don't display the cell separator for this cell fmt.Fprintf(.out, "%s%s", strings.Repeat(" ", +2), .pCenter) } } if { fmt.Fprint(.out, .newLine) } } // Return the PadRight function if align is left, PadLeft if align is right, // and Pad by default func pad( int) func(string, string, int) string { := Pad switch { case ALIGN_LEFT: = PadRight case ALIGN_RIGHT: = PadLeft } return } // Print heading information func ( *Table) () { // Check if headers is available if len(.headers) < 1 { return } // Identify last column := len(.cs) - 1 // Get pad function := pad(.hAlign) // Checking for ANSI escape sequences for header := false if len(.headerParams) > 0 { = true } // Maximum height. := .rs[headerRowIdx] // Print Heading for := 0; < ; ++ { // Check if border is set // Replace with space if not set if !.noWhiteSpace { fmt.Fprint(.out, ConditionString(.borders.Left, .pColumn, SPACE)) } for := 0; <= ; ++ { := .cs[] := "" if < len(.headers) && < len(.headers[]) { = .headers[][] } if .autoFmt { = Title() } := ConditionString(( == && !.borders.Left), SPACE, .pColumn) if .noWhiteSpace { = ConditionString(( == && !.borders.Left), SPACE, .tablePadding) } if { if !.noWhiteSpace { fmt.Fprintf(.out, " %s %s", format((, SPACE, ), .headerParams[]), ) } else { fmt.Fprintf(.out, "%s %s", format((, SPACE, ), .headerParams[]), ) } } else { if !.noWhiteSpace { fmt.Fprintf(.out, " %s %s", (, SPACE, ), ) } else { // the spaces between breaks the kube formatting fmt.Fprintf(.out, "%s%s", (, SPACE, ), ) } } } // Next line fmt.Fprint(.out, .newLine) } if .hdrLine { .printLine(true) } } // Print heading information func ( *Table) () { // Check if headers is available if len(.footers) < 1 { return } // Only print line if border is not set if !.borders.Bottom { .printLine(true) } // Identify last column := len(.cs) - 1 // Get pad function := pad(.fAlign) // Checking for ANSI escape sequences for header := false if len(.footerParams) > 0 { = true } // Maximum height. := .rs[footerRowIdx] // Print Footer := make([]bool, len(.footers)) for := 0; < ; ++ { // Check if border is set // Replace with space if not set fmt.Fprint(.out, ConditionString(.borders.Bottom, .pColumn, SPACE)) for := 0; <= ; ++ { := .cs[] := "" if < len(.footers) && < len(.footers[]) { = .footers[][] } if .autoFmt { = Title() } := ConditionString(( == && !.borders.Top), SPACE, .pColumn) if [] || ( == 0 && len() == 0) { = SPACE [] = true } if { fmt.Fprintf(.out, " %s %s", format((, SPACE, ), .footerParams[]), ) } else { fmt.Fprintf(.out, " %s %s", (, SPACE, ), ) } //fmt.Fprintf(t.out, " %s %s", // padFunc(f, SPACE, v), // pad) } // Next line fmt.Fprint(.out, .newLine) //t.printLine(true) } := false for := 0; <= ; ++ { := .cs[] := .pRow := .pCenter := len(.footers[][0]) if > 0 { = true } // Set center to be space if length is 0 if == 0 && !.borders.Right { = SPACE } // Print first junction if == 0 { if > 0 && !.borders.Left { = .pRow } fmt.Fprint(.out, ) } // Pad With space of length is 0 if == 0 { = SPACE } // Ignore left space as it has printed before if || .borders.Left { = .pRow = .pCenter } // Change Center end position if != SPACE { if == && !.borders.Right { = .pRow } } // Change Center start position if == SPACE { if < && len(.footers[+1][0]) != 0 { if !.borders.Left { = .pRow } else { = .pCenter } } } // Print the footer fmt.Fprintf(.out, "%s%s%s%s", , strings.Repeat(string(), ), , ) } fmt.Fprint(.out, .newLine) } // Print caption text func ( Table) () { := .getTableWidth() , := WrapString(.captionText, ) for := 0; < len(); ++ { fmt.Fprintln(.out, []) } } // Calculate the total number of characters in a row func ( Table) () int { var int for , := range .cs { += } // Add chars, spaces, seperators to calculate the total width of the table. // ncols := t.colSize // spaces := ncols * 2 // seps := ncols + 1 return ( + (3 * .colSize) + 2) } func ( Table) () { for , := range .lines { .printRow(, ) } } func ( *Table) ( int) { if len(.columnsAlign) < { .columnsAlign = make([]int, ) for := range .columnsAlign { .columnsAlign[] = .align } } } // Print Row Information // Adjust column alignment based on type func ( *Table) ( [][]string, int) { // Get Maximum Height := .rs[] := len() // TODO Fix uneven col size // if total < t.colSize { // for n := t.colSize - total; n < t.colSize ; n++ { // columns = append(columns, []string{SPACE}) // t.cs[n] = t.mW // } //} // Pad Each Height := []int{} // Checking for ANSI escape sequences for columns := false if len(.columnsParams) > 0 { = true } .fillAlignment() for , := range { := len() := - = append(, ) for := 0; < ; ++ { [] = append([], " ") } } //fmt.Println(max, "\n") for := 0; < ; ++ { for := 0; < ; ++ { // Check if border is set if !.noWhiteSpace { fmt.Fprint(.out, ConditionString((!.borders.Left && == 0), SPACE, .pColumn)) fmt.Fprintf(.out, SPACE) } := [][] // Embedding escape sequence with column value if { = format(, .columnsParams[]) } // This would print alignment // Default alignment would use multiple configuration switch .columnsAlign[] { case ALIGN_CENTER: // fmt.Fprintf(.out, "%s", Pad(, SPACE, .cs[])) case ALIGN_RIGHT: fmt.Fprintf(.out, "%s", PadLeft(, SPACE, .cs[])) case ALIGN_LEFT: fmt.Fprintf(.out, "%s", PadRight(, SPACE, .cs[])) default: if decimal.MatchString(strings.TrimSpace()) || percent.MatchString(strings.TrimSpace()) { fmt.Fprintf(.out, "%s", PadLeft(, SPACE, .cs[])) } else { fmt.Fprintf(.out, "%s", PadRight(, SPACE, .cs[])) // TODO Custom alignment per column //if max == 1 || pads[y] > 0 { // fmt.Fprintf(t.out, "%s", Pad(str, SPACE, t.cs[y])) //} else { // fmt.Fprintf(t.out, "%s", PadRight(str, SPACE, t.cs[y])) //} } } if !.noWhiteSpace { fmt.Fprintf(.out, SPACE) } else { fmt.Fprintf(.out, .tablePadding) } } // Check if border is set // Replace with space if not set if !.noWhiteSpace { fmt.Fprint(.out, ConditionString(.borders.Left, .pColumn, SPACE)) } fmt.Fprint(.out, .newLine) } if .rowLine { .printLine(true) } } // Print the rows of the table and merge the cells that are identical func ( *Table) () { var []string var []bool var bytes.Buffer for , := range .lines { // We store the display of the current line in a tmp writer, as we need to know which border needs to be print above , = .printRowMergeCells(&, , , ) if > 0 { //We don't need to print borders above first line if .rowLine { .printLineOptionalCellSeparators(true, ) } } .WriteTo(.out) } //Print the end of the table if .rowLine { .printLine(true) } } // Print Row Information to a writer and merge identical cells. // Adjust column alignment based on type func ( *Table) ( io.Writer, [][]string, int, []string) ([]string, []bool) { // Get Maximum Height := .rs[] := len() // Pad Each Height := []int{} // Checking for ANSI escape sequences for columns := false if len(.columnsParams) > 0 { = true } for , := range { := len() := - = append(, ) for := 0; < ; ++ { [] = append([], " ") } } var []bool .fillAlignment() for := 0; < ; ++ { for := 0; < ; ++ { // Check if border is set fmt.Fprint(, ConditionString((!.borders.Left && == 0), SPACE, .pColumn)) fmt.Fprintf(, SPACE) := [][] // Embedding escape sequence with column value if { = format(, .columnsParams[]) } if .autoMergeCells { var bool if .columnsToAutoMergeCells != nil { // Check to see if the column index is in columnsToAutoMergeCells. if .columnsToAutoMergeCells[] { = true } } else { // columnsToAutoMergeCells was not set. = true } //Store the full line to merge mutli-lines cells := strings.TrimRight(strings.Join([], " "), " ") if len() > && == [] && != "" && { // If this cell is identical to the one above but not empty, we don't display the border and keep the cell empty. = append(, false) = "" } else { // First line or different content, keep the content and print the cell border = append(, true) } } // This would print alignment // Default alignment would use multiple configuration switch .columnsAlign[] { case ALIGN_CENTER: // fmt.Fprintf(, "%s", Pad(, SPACE, .cs[])) case ALIGN_RIGHT: fmt.Fprintf(, "%s", PadLeft(, SPACE, .cs[])) case ALIGN_LEFT: fmt.Fprintf(, "%s", PadRight(, SPACE, .cs[])) default: if decimal.MatchString(strings.TrimSpace()) || percent.MatchString(strings.TrimSpace()) { fmt.Fprintf(, "%s", PadLeft(, SPACE, .cs[])) } else { fmt.Fprintf(, "%s", PadRight(, SPACE, .cs[])) } } fmt.Fprintf(, SPACE) } // Check if border is set // Replace with space if not set fmt.Fprint(, ConditionString(.borders.Left, .pColumn, SPACE)) fmt.Fprint(, .newLine) } //The new previous line is the current one = make([]string, ) for := 0; < ; ++ { [] = strings.TrimRight(strings.Join([], " "), " ") //Store the full line for multi-lines cells } //Returns the newly added line and wether or not a border should be displayed above. return , } func ( *Table) ( string, , int) []string { var ( []string int ) = getLines() = 0 for , := range { if := DisplayWidth(); > { = } } // If wrapping, ensure that all paragraphs in the cell fit in the // specified width. if .autoWrap { // If there's a maximum allowed width for wrapping, use that. if > .mW { = .mW } // In the process of doing so, we need to recompute maxWidth. This // is because perhaps a word in the cell is longer than the // allowed maximum width in t.mW. := := make([]string, 0, len()) if .reflowText { // Make a single paragraph of everything. = []string{strings.Join(, " ")} } for , := range { , := WrapString(, ) for , := range { if := DisplayWidth(); > { = } } if > 0 { = append(, " ") } = append(, ...) } = = } // Store the new known maximum width. , := .cs[] if ! || < || == 0 { .cs[] = } // Remember the number of lines for the row printer. := len() , = .rs[] if ! || < || == 0 { .rs[] = } //fmt.Printf("Raw %+v %d\n", raw, len(raw)) return }