-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreader.go
65 lines (51 loc) · 1.2 KB
/
reader.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
package goflat
import (
"bytes"
"encoding/csv"
"fmt"
"io"
"strings"
)
//nolint:gochecknoglobals // We are fine for now.
var commonSeparators = []string{",", ";", "\t", "|"}
func readFirstLine(reader io.Reader) (string, error) {
b := make([]byte, 1) //nolint:varnamelen // Fine here.
var line string
for {
_, err := reader.Read(b)
if err != nil {
if err == io.EOF {
return line, nil
}
return "", fmt.Errorf("read row: %w", err)
}
line += string(b)
if b[0] == '\n' {
return line, nil
}
}
}
// DetectReader returns a CSV reader with a separator based on a best guess
// about the first line.
func DetectReader(reader io.Reader) (*csv.Reader, error) {
headers, err := readFirstLine(reader)
if err != nil {
return nil, fmt.Errorf("read first line: %w", err)
}
var bestSeparator string
var bestCount int
for _, sep := range commonSeparators {
count := strings.Count(headers, sep)
if count > bestCount {
bestCount = count
bestSeparator = sep
}
}
// Read headers again
rr := io.MultiReader(bytes.NewBufferString(headers), reader)
csvReader := csv.NewReader(rr)
if bestSeparator != "," {
csvReader.Comma = rune(bestSeparator[0])
}
return csvReader, nil
}