github.com/hazelops/ize@v1.1.12-0.20230915191306-97d7c0e48f11/pkg/terminal/table.go (about) 1 package terminal 2 3 import ( 4 "github.com/fatih/color" 5 "github.com/olekukonko/tablewriter" 6 ) 7 8 // Passed to UI.Table to provide a nicely formatted table. 9 type Table struct { 10 Headers []string 11 Rows [][]TableEntry 12 } 13 14 // Table creates a new Table structure that can be used with UI.Table. 15 func NewTable(headers ...string) *Table { 16 return &Table{ 17 Headers: headers, 18 } 19 } 20 21 // TableEntry is a single entry for a table. 22 type TableEntry struct { 23 Value string 24 Color string 25 } 26 27 // Rich adds a row to the table. 28 func (t *Table) Rich(cols []string, colors []string) { 29 var row []TableEntry 30 31 for i, col := range cols { 32 if i < len(colors) { 33 row = append(row, TableEntry{Value: col, Color: colors[i]}) 34 } else { 35 row = append(row, TableEntry{Value: col}) 36 } 37 } 38 39 t.Rows = append(t.Rows, row) 40 } 41 42 // Table implements UI 43 func (u *basicUI) Table(tbl *Table, opts ...Option) { 44 // Build our config and set our options 45 cfg := &config{Writer: color.Output} 46 for _, opt := range opts { 47 opt(cfg) 48 } 49 50 table := tablewriter.NewWriter(cfg.Writer) 51 52 table.SetHeader(tbl.Headers) 53 table.SetBorder(false) 54 table.SetAutoWrapText(false) 55 56 if cfg.Style == "Simple" { 57 // Format the table without borders, simple output 58 59 table.SetAutoFormatHeaders(true) 60 table.SetHeaderAlignment(tablewriter.ALIGN_LEFT) 61 table.SetAlignment(tablewriter.ALIGN_LEFT) 62 table.SetCenterSeparator("") 63 table.SetColumnSeparator("") 64 table.SetRowSeparator("") 65 table.SetHeaderLine(false) 66 table.SetTablePadding("\t") // pad with tabs 67 table.SetNoWhiteSpace(true) 68 } 69 70 for _, row := range tbl.Rows { 71 colors := make([]tablewriter.Colors, len(row)) 72 entries := make([]string, len(row)) 73 74 for i, ent := range row { 75 entries[i] = ent.Value 76 77 color, ok := colorMapping[ent.Color] 78 if ok { 79 colors[i] = tablewriter.Colors{color} 80 } 81 } 82 83 table.Rich(entries, colors) 84 } 85 86 table.Render() 87 } 88 89 const ( 90 Yellow = "yellow" 91 Green = "green" 92 Red = "red" 93 ) 94 95 var colorMapping = map[string]int{ 96 Green: tablewriter.FgGreenColor, 97 Yellow: tablewriter.FgYellowColor, 98 Red: tablewriter.FgRedColor, 99 }