-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender.go
More file actions
350 lines (325 loc) · 7.23 KB
/
Copy pathrender.go
File metadata and controls
350 lines (325 loc) · 7.23 KB
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
// Package render turns slices of record structs into one of the output formats
// hackernews-cli supports: table, json, jsonl, csv, tsv, url, and raw. It works
// off struct reflection and json tags, so any record type renders without
// per-type code.
package render
import (
"encoding/csv"
"encoding/json"
"fmt"
"io"
"reflect"
"strconv"
"strings"
"text/tabwriter"
"text/template"
"time"
)
// Format is an output rendering format.
type Format string
const (
FormatTable Format = "table"
FormatJSON Format = "json"
FormatJSONL Format = "jsonl"
FormatCSV Format = "csv"
FormatTSV Format = "tsv"
FormatURL Format = "url"
FormatRaw Format = "raw"
)
// Valid reports whether f is one of the supported formats.
func (f Format) Valid() bool {
switch f {
case FormatTable, FormatJSON, FormatJSONL, FormatCSV, FormatTSV, FormatURL, FormatRaw:
return true
}
return false
}
// Renderer writes records in a chosen format.
type Renderer struct {
Format Format
Fields []string
NoHeader bool
Template string
w io.Writer
}
// New builds a Renderer writing to w.
func New(w io.Writer, format Format, fields []string, noHeader bool, tmpl string) *Renderer {
return &Renderer{Format: format, Fields: fields, NoHeader: noHeader, Template: tmpl, w: w}
}
// Render writes records (a slice of structs, or a single struct) in the configured format.
func (r *Renderer) Render(records any) error {
rv := reflect.ValueOf(records)
if rv.Kind() == reflect.Pointer {
rv = rv.Elem()
}
if rv.Kind() != reflect.Slice {
s := reflect.MakeSlice(reflect.SliceOf(rv.Type()), 1, 1)
s.Index(0).Set(rv)
rv = s
}
n := rv.Len()
items := make([]any, n)
for i := 0; i < n; i++ {
items[i] = rv.Index(i).Interface()
}
if r.Template != "" {
return r.renderTemplate(items)
}
switch r.Format {
case FormatJSON:
return r.renderJSON(items)
case FormatJSONL:
return r.renderJSONL(items)
case FormatCSV:
return r.renderDelimited(items, ',')
case FormatTSV:
return r.renderDelimited(items, '\t')
case FormatURL:
return r.renderURL(items)
case FormatRaw:
return r.renderRaw(items)
default:
return r.renderTable(items)
}
}
func (r *Renderer) renderJSON(items []any) error {
enc := json.NewEncoder(r.w)
enc.SetIndent("", " ")
if len(items) == 1 {
return enc.Encode(items[0])
}
return enc.Encode(items)
}
func (r *Renderer) renderJSONL(items []any) error {
enc := json.NewEncoder(r.w)
for _, it := range items {
if err := enc.Encode(it); err != nil {
return err
}
}
return nil
}
func (r *Renderer) renderTemplate(items []any) error {
t, err := template.New("row").Funcs(template.FuncMap{
"join": func(sep string, v any) string { return joinAny(sep, v) },
}).Parse(r.Template)
if err != nil {
return fmt.Errorf("parse --template: %w", err)
}
for _, it := range items {
if err := t.Execute(r.w, toAnyMap(it)); err != nil {
return err
}
_, _ = fmt.Fprintln(r.w)
}
return nil
}
func (r *Renderer) renderURL(items []any) error {
for _, it := range items {
m := toMap(it)
if u := firstNonEmpty(m["url"], m["hn_url"], m["permalink"]); u != "" {
_, _ = fmt.Fprintln(r.w, u)
}
}
return nil
}
func (r *Renderer) renderRaw(items []any) error {
cols := r.columns(items)
for _, it := range items {
m := toMap(it)
vals := make([]string, 0, len(cols))
for _, c := range cols {
vals = append(vals, m[c])
}
_, _ = fmt.Fprintln(r.w, strings.Join(vals, " "))
}
return nil
}
func (r *Renderer) renderTable(items []any) error {
if len(items) == 0 {
return nil
}
cols := r.columns(items)
tw := tabwriter.NewWriter(r.w, 0, 4, 2, ' ', 0)
if !r.NoHeader {
_, _ = fmt.Fprintln(tw, strings.Join(upperAll(cols), "\t"))
}
for _, it := range items {
m := toMap(it)
cells := make([]string, len(cols))
for i, c := range cols {
cells[i] = truncate(m[c], 60)
}
_, _ = fmt.Fprintln(tw, strings.Join(cells, "\t"))
}
return tw.Flush()
}
func (r *Renderer) renderDelimited(items []any, comma rune) error {
if len(items) == 0 {
return nil
}
cols := r.columns(items)
cw := csv.NewWriter(r.w)
cw.Comma = comma
if !r.NoHeader {
if err := cw.Write(cols); err != nil {
return err
}
}
for _, it := range items {
m := toMap(it)
row := make([]string, len(cols))
for i, c := range cols {
row[i] = m[c]
}
if err := cw.Write(row); err != nil {
return err
}
}
cw.Flush()
return cw.Error()
}
func (r *Renderer) columns(items []any) []string {
if len(r.Fields) > 0 {
return r.Fields
}
if len(items) == 0 {
return nil
}
return structJSONKeys(items[0])
}
func toAnyMap(v any) any {
data, err := json.Marshal(v)
if err != nil {
return v
}
var m map[string]any
if err := json.Unmarshal(data, &m); err != nil {
return v
}
return m
}
func joinAny(sep string, v any) string {
switch vv := v.(type) {
case nil:
return ""
case []string:
return strings.Join(vv, sep)
case []any:
parts := make([]string, len(vv))
for i, e := range vv {
parts[i] = fmt.Sprintf("%v", e)
}
return strings.Join(parts, sep)
default:
return fmt.Sprintf("%v", v)
}
}
func toMap(v any) map[string]string {
out := map[string]string{}
rv := reflect.ValueOf(v)
if rv.Kind() == reflect.Pointer {
rv = rv.Elem()
}
if rv.Kind() != reflect.Struct {
return out
}
rt := rv.Type()
for i := 0; i < rt.NumField(); i++ {
f := rt.Field(i)
if f.PkgPath != "" {
continue
}
key := jsonKey(f)
if key == "-" {
continue
}
out[key] = formatValue(rv.Field(i))
}
return out
}
func structJSONKeys(v any) []string {
rv := reflect.ValueOf(v)
if rv.Kind() == reflect.Pointer {
rv = rv.Elem()
}
if rv.Kind() != reflect.Struct {
return nil
}
rt := rv.Type()
var keys []string
for i := 0; i < rt.NumField(); i++ {
f := rt.Field(i)
if f.PkgPath != "" {
continue
}
key := jsonKey(f)
if key == "-" {
continue
}
keys = append(keys, key)
}
return keys
}
func jsonKey(f reflect.StructField) string {
tag := f.Tag.Get("json")
if tag == "" {
return f.Name
}
name := strings.Split(tag, ",")[0]
if name == "" {
return f.Name
}
return name
}
func formatValue(v reflect.Value) string {
switch v.Kind() {
case reflect.String:
return v.String()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return strconv.FormatInt(v.Int(), 10)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return strconv.FormatUint(v.Uint(), 10)
case reflect.Float32, reflect.Float64:
return strconv.FormatFloat(v.Float(), 'g', -1, 64)
case reflect.Bool:
return strconv.FormatBool(v.Bool())
case reflect.Slice:
parts := make([]string, v.Len())
for i := 0; i < v.Len(); i++ {
parts[i] = formatValue(v.Index(i))
}
return strings.Join(parts, ";")
case reflect.Struct:
if t, ok := v.Interface().(time.Time); ok {
if t.IsZero() {
return ""
}
return t.Format(time.RFC3339)
}
}
return fmt.Sprintf("%v", v.Interface())
}
func upperAll(ss []string) []string {
out := make([]string, len(ss))
for i, s := range ss {
out[i] = strings.ToUpper(s)
}
return out
}
func firstNonEmpty(ss ...string) string {
for _, s := range ss {
if s != "" {
return s
}
}
return ""
}
func truncate(s string, n int) string {
s = strings.ReplaceAll(s, "\n", " ")
if len([]rune(s)) <= n {
return s
}
rs := []rune(s)
return string(rs[:n-1]) + "..."
}