github.com/piiano/go-licenses@v1.2.1-c/writer.go (about) 1 package main 2 3 import ( 4 "encoding/csv" 5 "io" 6 7 "github.com/olekukonko/tablewriter" 8 ) 9 10 type writer interface { 11 Write(...string) error 12 Flush() 13 Error() error 14 } 15 16 // ----------- CSV ----------- // 17 type csvWriter struct { 18 w *csv.Writer 19 } 20 21 func NewCSVWriter(w io.Writer) csvWriter { 22 return csvWriter{ 23 w: csv.NewWriter(w), 24 } 25 } 26 27 func (cw csvWriter) Write(args ...string) error { 28 return cw.w.Write(args) 29 } 30 31 func (cw csvWriter) Flush() { 32 cw.w.Flush() 33 } 34 35 func (cw csvWriter) Error() error { 36 return cw.w.Error() 37 } 38 39 // ----------- Table ----------- // 40 type tableWriter struct { 41 w *tablewriter.Table 42 } 43 44 func NewTableWriter(w io.Writer, header []string) tableWriter { 45 table := tablewriter.NewWriter(w) 46 47 // Do not auto capitalize the header. 48 table.SetAutoFormatHeaders(false) 49 table.SetHeader(header) 50 51 // If just one column, allow it to be extra long. 52 if len(header) == 1 { 53 table.SetAutoWrapText(false) 54 table.SetReflowDuringAutoWrap(false) 55 } 56 57 return tableWriter{ 58 w: table, 59 } 60 } 61 62 func NewMarkdownTableWriter(w io.Writer, header []string) tableWriter { 63 table := tablewriter.NewWriter(w) 64 65 table.SetHeader(header) 66 table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false}) 67 table.SetCenterSeparator("|") 68 69 return tableWriter{ 70 w: table, 71 } 72 } 73 74 func (tw tableWriter) Write(args ...string) error { 75 tw.w.Append(args) 76 return nil 77 } 78 79 func (tw tableWriter) Flush() { 80 tw.w.Render() 81 } 82 83 func (tw tableWriter) Error() error { 84 return nil 85 }