Skip to content

Commit ec3137b

Browse files
committed
Fixes #16559 - Do not trim leading spaces for tab delimited
1 parent b428b0f commit ec3137b

File tree

2 files changed

+49
-8
lines changed

2 files changed

+49
-8
lines changed

modules/csv/csv.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,11 @@ var quoteRegexp = regexp.MustCompile(`["'][\s\S]+?["']`)
2222
func CreateReader(input io.Reader, delimiter rune) *stdcsv.Reader {
2323
rd := stdcsv.NewReader(input)
2424
rd.Comma = delimiter
25-
rd.TrimLeadingSpace = true
25+
if delimiter != '\t' && delimiter != ' ' {
26+
// TrimLeadingSpace can't be true when delimiter is a tab or a space as the value for a column might be empty,
27+
// thus would change `\t\t` to just `\t` or ` ` (two spaces) to just ` ` (single space)
28+
rd.TrimLeadingSpace = true
29+
}
2630
return rd
2731
}
2832

modules/csv/csv_test.go

+44-7
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,52 @@ func TestCreateReader(t *testing.T) {
1818
}
1919

2020
func TestCreateReaderAndGuessDelimiter(t *testing.T) {
21-
input := "a;b;c\n1;2;3\n4;5;6"
21+
var csvToRowsMap = map[string][][]string{
22+
`col1 col2 col3
23+
a b c
24+
e f
25+
g h i
26+
j l
27+
m n
28+
p q r
29+
u
30+
v w x
31+
y
32+
`: {{"col1", "col2", "col3"},
33+
{"a", "b", "c"},
34+
{"", "e", "f"},
35+
{"g", "h", "i"},
36+
{"j", "", "l"},
37+
{"m", "n", ""},
38+
{"p", "q", "r"},
39+
{"", "", "u"},
40+
{"v", "w", "x"},
41+
{"y", "", ""},
42+
{"", "", ""}},
43+
` col1,col2,col3
44+
a, b, c
45+
d,e,f
46+
,h, i
47+
j, ,
48+
, , `: {{"col1", "col2", "col3"},
49+
{"a", "b", "c"},
50+
{"d", "e", "f"},
51+
{"", "h", "i"},
52+
{"j", "", ""},
53+
{"", "", ""}},
54+
}
2255

23-
rd, err := CreateReaderAndGuessDelimiter(strings.NewReader(input))
24-
assert.NoError(t, err)
25-
assert.Equal(t, ';', rd.Comma)
56+
for csv, expectedRows := range csvToRowsMap {
57+
rd, err := CreateReaderAndGuessDelimiter(strings.NewReader(csv))
58+
assert.NoError(t, err)
59+
rows, err := rd.ReadAll()
60+
assert.NoError(t, err)
61+
assert.EqualValues(t, rows, expectedRows)
62+
}
2663
}
2764

2865
func TestGuessDelimiter(t *testing.T) {
29-
var kases = map[string]rune{
66+
var csvToDelimiterMap = map[string]rune{
3067
"a": ',',
3168
"1,2": ',',
3269
"1;2": ';',
@@ -37,7 +74,7 @@ func TestGuessDelimiter(t *testing.T) {
3774
"<br/>": ',',
3875
}
3976

40-
for k, v := range kases {
41-
assert.EqualValues(t, guessDelimiter([]byte(k)), v)
77+
for csv, expectedDelimiter := range csvToDelimiterMap {
78+
assert.EqualValues(t, guessDelimiter([]byte(csv)), expectedDelimiter)
4279
}
4380
}

0 commit comments

Comments
 (0)