github.com/cilium/cilium@v1.16.2/test/controlplane/suite/table_writer.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright Authors of Cilium
     3  
     4  package suite
     5  
     6  import (
     7  	"fmt"
     8  	"io"
     9  	"strings"
    10  )
    11  
    12  // TableBuilder is an utility for formatting data as tables.
    13  type TableBuilder struct {
    14  	tableName   string
    15  	columnNames []string
    16  	rows        [][]string
    17  }
    18  
    19  func NewEmptyTable(name string, columnNames ...string) *TableBuilder {
    20  	return &TableBuilder{name, columnNames, nil}
    21  }
    22  
    23  func (tw *TableBuilder) Write(w io.Writer) {
    24  	// Compute the width of each column. Either length of column name, or
    25  	// the length of widest value in that column.
    26  	colWidths := make([]int, len(tw.columnNames))
    27  	for i, hdr := range tw.columnNames {
    28  		colWidths[i] = len(hdr)
    29  	}
    30  	for _, row := range tw.rows {
    31  		for j, col := range row {
    32  			if len(col) > colWidths[j] {
    33  				colWidths[j] = len(col)
    34  			}
    35  		}
    36  	}
    37  
    38  	// Create the divider between the header and rows
    39  	headingDiv := "|"
    40  	for i := range colWidths {
    41  		headingDiv += strings.Repeat("-", colWidths[i]+2)
    42  		if i != len(colWidths)-1 {
    43  			headingDiv += "+"
    44  		}
    45  	}
    46  	headingDiv += "\n"
    47  
    48  	// Print out the table name and columnNames
    49  	fmt.Fprintf(w, " - %s %s\n", tw.tableName, strings.Repeat("-", len(headingDiv)-len(tw.tableName)-5))
    50  	w.Write([]byte("| "))
    51  	for i, hdr := range tw.columnNames[:len(tw.columnNames)-1] {
    52  		fmt.Fprintf(w, "%[2]*[1]s | ", hdr, colWidths[i])
    53  	}
    54  	fmt.Fprintf(w, "%[2]*[1]s |\n",
    55  		tw.columnNames[len(tw.columnNames)-1],
    56  		colWidths[len(tw.columnNames)-1])
    57  	w.Write([]byte(headingDiv))
    58  
    59  	for _, row := range tw.rows {
    60  		w.Write([]byte{'|'})
    61  		col := 0
    62  		for ; col < len(row); col++ {
    63  			fmt.Fprintf(w, " %*s |", colWidths[col], row[col])
    64  		}
    65  		for ; col < len(colWidths); col++ {
    66  			fmt.Fprintf(w, " %*s |", colWidths[col], "")
    67  		}
    68  		w.Write([]byte{'\n'})
    69  	}
    70  
    71  	fmt.Fprintf(w, " %s\n\n", strings.Repeat("-", len(headingDiv)-2))
    72  }
    73  
    74  func (tw *TableBuilder) AddRow(fields ...string) {
    75  	tw.rows = append(tw.rows, fields)
    76  }