github.com/rakutentech/cli@v6.12.5-0.20151006231303-24468b65536e+incompatible/cf/terminal/table.go (about)

     1  package terminal
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  	"unicode/utf8"
     7  )
     8  
     9  type Table interface {
    10  	Add(row ...string)
    11  	Print()
    12  }
    13  
    14  type PrintableTable struct {
    15  	ui            UI
    16  	headers       []string
    17  	headerPrinted bool
    18  	maxSizes      []int
    19  	rows          [][]string
    20  }
    21  
    22  func NewTable(ui UI, headers []string) Table {
    23  	return &PrintableTable{
    24  		ui:       ui,
    25  		headers:  headers,
    26  		maxSizes: make([]int, len(headers)),
    27  	}
    28  }
    29  
    30  func (t *PrintableTable) Add(row ...string) {
    31  	t.rows = append(t.rows, row)
    32  }
    33  
    34  func (t *PrintableTable) Print() {
    35  	for _, row := range append(t.rows, t.headers) {
    36  		t.calculateMaxSize(row)
    37  	}
    38  
    39  	if t.headerPrinted == false {
    40  		t.printHeader()
    41  		t.headerPrinted = true
    42  	}
    43  
    44  	for _, line := range t.rows {
    45  		t.printRow(line)
    46  	}
    47  
    48  	t.rows = [][]string{}
    49  }
    50  
    51  func (t *PrintableTable) calculateMaxSize(row []string) {
    52  	for index, value := range row {
    53  		cellLength := utf8.RuneCountInString(Decolorize(value))
    54  		if t.maxSizes[index] < cellLength {
    55  			t.maxSizes[index] = cellLength
    56  		}
    57  	}
    58  }
    59  
    60  func (t *PrintableTable) printHeader() {
    61  	output := ""
    62  	for col, value := range t.headers {
    63  		output = output + t.cellValue(col, HeaderColor(value))
    64  	}
    65  	t.ui.Say(output)
    66  }
    67  
    68  func (t *PrintableTable) printRow(row []string) {
    69  	output := ""
    70  	for columnIndex, value := range row {
    71  		if columnIndex == 0 {
    72  			value = TableContentHeaderColor(value)
    73  		}
    74  
    75  		output = output + t.cellValue(columnIndex, value)
    76  	}
    77  	t.ui.Say("%s", output)
    78  }
    79  
    80  func (t *PrintableTable) cellValue(col int, value string) string {
    81  	padding := ""
    82  	if col < len(t.headers)-1 {
    83  		padding = strings.Repeat(" ", t.maxSizes[col]-utf8.RuneCountInString(Decolorize(value)))
    84  	}
    85  	return fmt.Sprintf("%s%s   ", value, padding)
    86  }