Skip to content

Commit 50e14b7

Browse files
committed
Added one test, for embedded newlines, and fixed all the bugs it found
1 parent 7294a1b commit 50e14b7

File tree

3 files changed

+52
-4
lines changed

3 files changed

+52
-4
lines changed

lua/csv.lua

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,8 @@ local function separated_values_iterator(file, parameters)
201201
local function sub(a, b)
202202
truncate()
203203
extend(b)
204-
return buffer:sub(anchor_pos + a - 1, anchor_pos + b - 1)
204+
local b = b == -1 and b or anchor_pos + b - 1
205+
return buffer:sub(anchor_pos + a - 1, b)
205206
end
206207

207208

@@ -237,8 +238,8 @@ local function separated_values_iterator(file, parameters)
237238
format(filename, field_start_line, field_start_column))
238239
end
239240
tidy = fix_quotes
240-
field_end, sep_end, this_sep = find("%s*(%S)", current_pos+1)
241-
if not this_sep:match(sep) then
241+
field_end, sep_end, this_sep = find(" *([^ ])", current_pos+1)
242+
if this_sep and not this_sep:match(sep) then
242243
error(("%s:%d:%d: unmatched quote"):
243244
format(filename, field_start_line, field_start_column))
244245
end
@@ -247,7 +248,7 @@ local function separated_values_iterator(file, parameters)
247248
tidy = trim_space
248249
end
249250

250-
-- Look for the separator or a newline.
251+
-- Look for the separator or a newline or the end of the file
251252
field_end = (field_end or 0) - 1
252253

253254
-- Read the field, then convert all the line endings to \n, and

lua/test.lua

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
pcall(require, "strict")
2+
local csv = require"csv"
3+
4+
local errors = 0
5+
6+
local function test(filename, correct_result, parameters)
7+
local result = {}
8+
local f = csv.open(filename)
9+
for r in f:lines() do
10+
result[#result+1] = table.concat(r, ",")
11+
end
12+
result = table.concat(result, "\n")
13+
if result ~= correct_result then
14+
io.stderr:write(
15+
("Error reading %s. Expected output\n%s\nActual output\n%s\n"):
16+
format(filename, correct_result, result))
17+
errors = errors + 1
18+
end
19+
end
20+
21+
test("../test-data/embedded-newlines.csv", [[
22+
embedded
23+
newline,embedded
24+
newline,embedded
25+
newline
26+
embedded
27+
newline,embedded
28+
newline,embedded
29+
newline]])
30+
31+
if errors == 0 then
32+
io.stdout:write("Passed\n")
33+
elseif errors == 1 then
34+
io.stdout:write("1 error\n")
35+
else
36+
io.stdout:write(("%d errors\n"):format(errors))
37+
end
38+
39+
os.exit(errors)

test-data/embedded-newlines.csv

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
"embedded
2+
newline","embedded
3+
newline","embedded
4+
newline"
5+
"embedded
6+
newline","embedded
7+
newline","embedded
8+
newline"

0 commit comments

Comments
 (0)