-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrenderer.go
118 lines (107 loc) · 2.55 KB
/
renderer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package llcm
import (
"encoding/csv"
"encoding/json"
"io"
"github.com/nekrassov01/mintab"
)
// OutputType represents the type of the output.
type Renderer[E Entry, D EntryData[E]] struct {
Data D
OutputType OutputType
w io.Writer
}
// NewRenderer creates a new renderer with the specified parameters.
func NewRenderer[E Entry, D EntryData[E]](w io.Writer, data D, outputType OutputType) *Renderer[E, D] {
return &Renderer[E, D]{
Data: data,
OutputType: outputType,
w: w,
}
}
// String returns the string representation of the renderer.
func (ren *Renderer[E, D]) String() string {
b, _ := json.MarshalIndent(ren, "", " ")
return string(b)
}
// Render renders the output.
func (ren *Renderer[E, D]) Render() error {
switch ren.OutputType {
case OutputTypeJSON, OutputTypePrettyJSON:
return ren.toJSON()
case OutputTypeText, OutputTypeCompressedText, OutputTypeMarkdown, OutputTypeBacklog:
return ren.toTable()
case OutputTypeTSV:
return ren.toTSV()
case OutputTypeChart:
return ren.toChart()
default:
return nil
}
}
func (ren *Renderer[E, D]) toJSON() error {
b := json.NewEncoder(ren.w)
if ren.OutputType == OutputTypePrettyJSON {
b.SetIndent("", " ")
}
return b.Encode(ren.Data.Entries())
}
func (ren *Renderer[E, D]) toTable() error {
var opt mintab.Option
switch ren.OutputType {
case OutputTypeText:
opt = mintab.WithFormat(mintab.TextFormat)
case OutputTypeCompressedText:
opt = mintab.WithFormat(mintab.CompressedTextFormat)
case OutputTypeMarkdown:
opt = mintab.WithFormat(mintab.MarkdownFormat)
case OutputTypeBacklog:
opt = mintab.WithFormat(mintab.BacklogFormat)
}
table := mintab.New(ren.w, opt)
if err := table.Load(ren.getInput()); err != nil {
return err
}
table.Render()
return nil
}
func (ren *Renderer[E, D]) toTSV() error {
entries := ren.Data.Entries()
if len(entries) == 0 {
return nil
}
w := csv.NewWriter(ren.w)
w.Comma = '\t'
if err := w.Write(ren.Data.Header()); err != nil {
return err
}
for _, entry := range entries {
if err := w.Write(entry.toTSV()); err != nil {
return err
}
}
w.Flush()
return w.Error()
}
func (ren *Renderer[E, D]) toChart() error {
if len(ren.Data.Entries()) == 0 {
return nil
}
return ren.Data.Chart()
}
func (ren *Renderer[E, D]) getInput() mintab.Input {
var (
entries = ren.Data.Entries()
data = make([][]any, len(entries))
)
if len(entries) == 0 {
return mintab.Input{}
}
for i, entry := range entries {
data[i] = entry.toInput()
}
return mintab.Input{
Header: ren.Data.Header(),
Data: data,
}
}