-
Notifications
You must be signed in to change notification settings - Fork 216
/
record_writer_csvlite.go
86 lines (73 loc) · 2.29 KB
/
record_writer_csvlite.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
package output
import (
"bufio"
"strings"
"github.com/johnkerl/miller/v6/pkg/cli"
"github.com/johnkerl/miller/v6/pkg/colorizer"
"github.com/johnkerl/miller/v6/pkg/mlrval"
"github.com/johnkerl/miller/v6/pkg/types"
)
type RecordWriterCSVLite struct {
writerOptions *cli.TWriterOptions
// For reporting schema changes: we print a newline and the new header
lastJoinedHeader *string
// Only write one blank line for schema changes / blank input lines
justWroteEmptyLine bool
}
func NewRecordWriterCSVLite(writerOptions *cli.TWriterOptions) (*RecordWriterCSVLite, error) {
return &RecordWriterCSVLite{
writerOptions: writerOptions,
lastJoinedHeader: nil,
justWroteEmptyLine: false,
}, nil
}
func (writer *RecordWriterCSVLite) Write(
outrec *mlrval.Mlrmap,
_ *types.Context,
bufferedOutputStream *bufio.Writer,
outputIsStdout bool,
) error {
if outrec == nil {
// End of record stream: nothing special for this output format
return nil
}
if outrec.IsEmpty() {
if !writer.justWroteEmptyLine {
bufferedOutputStream.WriteString(writer.writerOptions.ORS)
}
joinedHeader := ""
writer.lastJoinedHeader = &joinedHeader
writer.justWroteEmptyLine = true
return nil
}
needToPrintHeader := false
joinedHeader := strings.Join(outrec.GetKeys(), ",")
if writer.lastJoinedHeader == nil || *writer.lastJoinedHeader != joinedHeader {
if writer.lastJoinedHeader != nil {
if !writer.justWroteEmptyLine {
bufferedOutputStream.WriteString(writer.writerOptions.ORS)
}
writer.justWroteEmptyLine = true
}
writer.lastJoinedHeader = &joinedHeader
needToPrintHeader = true
}
if needToPrintHeader && !writer.writerOptions.HeaderlessOutput {
for pe := outrec.Head; pe != nil; pe = pe.Next {
bufferedOutputStream.WriteString(colorizer.MaybeColorizeKey(pe.Key, outputIsStdout))
if pe.Next != nil {
bufferedOutputStream.WriteString(writer.writerOptions.OFS)
}
}
bufferedOutputStream.WriteString(writer.writerOptions.ORS)
}
for pe := outrec.Head; pe != nil; pe = pe.Next {
bufferedOutputStream.WriteString(colorizer.MaybeColorizeValue(pe.Value.String(), outputIsStdout))
if pe.Next != nil {
bufferedOutputStream.WriteString(writer.writerOptions.OFS)
}
}
bufferedOutputStream.WriteString(writer.writerOptions.ORS)
writer.justWroteEmptyLine = false
return nil
}