-
Notifications
You must be signed in to change notification settings - Fork 0
/
marshal.go
84 lines (65 loc) · 1.69 KB
/
marshal.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
package goflat
import (
"context"
"encoding/csv"
"fmt"
)
// Marshaller can be used to tell goflat to use custom logic to convert a field
// into a string.
type Marshaller interface {
Marshal() (string, error)
}
// MarshalSliceToWriter marshals a slice of structs to a CSV file.
func MarshalSliceToWriter[T any](ctx context.Context, values []T, writer *csv.Writer, opts Options) error {
ch := make(chan T) //nolint:varnamelen // Fine here.
go func() {
defer close(ch)
for _, value := range values {
select {
case <-ctx.Done():
return
case ch <- value:
}
}
}()
return MarshalChannelToWriter(ctx, ch, writer, opts)
}
// MarshalChannelToWriter marshals a channel of structs to a CSV file.
func MarshalChannelToWriter[T any](ctx context.Context, inputCh <-chan T, writer *csv.Writer, opts Options) error {
opts.headersFromStruct = true
factory, err := newFactory[T](nil, opts)
if err != nil {
return fmt.Errorf("new factory: %w", err)
}
err = writer.Write(factory.marshalHeaders())
if err != nil {
return fmt.Errorf("write headers: %w", err)
}
var currentLine int
var value T
for {
var channelHasValue bool
select {
case <-ctx.Done():
return context.Cause(ctx) //nolint:wrapcheck // Fine here.
case value, channelHasValue = <-inputCh:
}
if !channelHasValue {
break
}
record, err := factory.marshal(value, string(writer.Comma))
if err != nil {
return fmt.Errorf("marshal %d: %w", currentLine, err)
}
err = writer.Write(record)
if err != nil {
return fmt.Errorf("write line %d: %w", currentLine, err)
}
currentLine++
}
writer.Flush()
if err = writer.Error(); err != nil {
return fmt.Errorf("flush: %w", err)
}
return nil
}