-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcsv_output.go
More file actions
86 lines (77 loc) · 2.17 KB
/
Copy pathcsv_output.go
File metadata and controls
86 lines (77 loc) · 2.17 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
package main
import (
"bytes"
"encoding/csv"
"fmt"
)
// dciCSVContentType renders list responses and report results as CSV for
// spreadsheet import. Report rows are keyed through the result schema so the
// header row carries column names.
type dciCSVContentType struct{}
func (t dciCSVContentType) Detect(contentType string) bool { return false }
func (t dciCSVContentType) Marshal(value interface{}) ([]byte, error) {
jsonSafe, err := toJSONSafe(value)
if err != nil {
return nil, err
}
jsonSafe = normalizeIntegralNumbers(jsonSafe)
// Labels keep full RFC3339 UTC: CSV is a machine format and must be
// byte-identical regardless of the host's zone.
rows, err := toTableRows(jsonSafe, labelRFC3339)
if err != nil {
return nil, fmt.Errorf("response is not table-shaped; use --output json instead: %w", err)
}
// CSV drops the list wrapper (pageToken and friends); say so on stderr
// when that hides a continuation token — stdout stays pure CSV.
notePageTokenDropped(jsonSafe)
columns := getTableOptions().columns
keys := collectKeys(rows, columns)
if len(keys) == 0 && len(columns) == 0 {
keys = reportSchemaColumnNames(jsonSafe)
}
var buf bytes.Buffer
writer := csv.NewWriter(&buf)
if err := writer.Write(keys); err != nil {
return nil, err
}
for _, row := range rows {
record := make([]string, len(keys))
for i, k := range keys {
record[i] = csvCell(row[k])
}
if err := writer.Write(record); err != nil {
return nil, err
}
}
writer.Flush()
if err := writer.Error(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func reportSchemaColumnNames(value interface{}) []string {
_, _, schema, ok := reportResultContainer(value)
if !ok {
return nil
}
names := make([]string, 0, len(schema))
for _, column := range schema {
names = append(names, column.Name)
}
return names
}
func (t dciCSVContentType) Unmarshal(data []byte, value interface{}) error {
return fmt.Errorf("unimplemented")
}
func csvCell(v interface{}) string {
switch value := v.(type) {
case nil:
return ""
case []interface{}:
return joinPrimitives(value)
case map[string]interface{}:
return jsonCell(value)
default:
return fmt.Sprintf("%v", value)
}
}