-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathexport.go
64 lines (58 loc) · 1.03 KB
/
export.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
package retraced
import (
"context"
"encoding/csv"
"io"
)
// ExportCSV writes all events matching a query to w as CSV records
func (c *Client) ExportCSV(ctx context.Context, w io.Writer, sq *StructuredQuery, mask *EventNodeMask) (err error) {
ctx, cancel := context.WithCancel(ctx)
events := make(chan *EventNode)
errors := make(chan error, 1)
out := csv.NewWriter(w)
defer func() {
out.Flush()
cancel()
}()
if err := out.Write(mask.CSVHeaders()); err != nil {
return err
}
go func() {
stream, err := c.NewStream(sq, mask)
if err != nil {
errors <- err
return
}
for {
e, err := stream.Read()
if err == io.EOF {
close(events)
return
}
if err != nil {
errors <- err
return
}
select {
case events <- e:
case <-ctx.Done():
return
}
}
}()
for {
select {
case e, ok := <-events:
if !ok {
return nil
}
if err := out.Write(mask.CSVRow(e)); err != nil {
return err
}
case err := <-errors:
return err
case <-ctx.Done():
return nil
}
}
}