Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 15 additions & 8 deletions lib/csv/parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -891,23 +891,30 @@ def build_scanner
string = @samples[0]
end
if string
unless string.valid_encoding?
index = string.lines(@row_separator).index do |line|
!line.valid_encoding?
end
if index
raise InvalidEncodingError.new(@encoding, @lineno + index + 1)
end
end
check_encoding(string)
Scanner.new(string)
else
unless @samples.all?(&:valid_encoding?)
check_encoding(@samples.join(""))
end
inputs = @samples.collect do |sample|
StringIO.new(sample)
end
inputs << @input
InputsScanner.new(inputs, @encoding, @row_separator)
end
end

def check_encoding(string)
return if string.valid_encoding?

index = string.lines(@row_separator).index do |line|
!line.valid_encoding?
end
if index
raise InvalidEncodingError.new(@encoding, @lineno + index + 1)
end
end
end

def skip_needless_lines
Expand Down
29 changes: 29 additions & 0 deletions test/csv/interface/test_read.rb
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,35 @@ def test_open_encoding_invalid
end
end

def test_open_encoding_invalid_line_number
File.open(@input.path, "wb") do |file|
file << "a,b\nc,d\n\xFF,1\n"
end
CSV.open(@input.path, encoding: "UTF-8") do |csv|
error = assert_raise(CSV::InvalidEncodingError) do
csv.read
end
assert_equal([Encoding::UTF_8, "Invalid byte sequence in UTF-8 in line 3."],
[error.encoding, error.message])
end
end

def test_open_encoding_invalid_line_number_in_partial_sample
# The row separator is detected from the first 32 KiB of a File. The
# invalid byte is in that sample, but the file is longer than it.
File.open(@input.path, "wb") do |file|
file << "a,b\n\x80,1\n"
file << "x,y\n" * 16384
end
CSV.open(@input.path, encoding: "UTF-8") do |csv|
error = assert_raise(CSV::InvalidEncodingError) do
csv.read
end
assert_equal([Encoding::UTF_8, "Invalid byte sequence in UTF-8 in line 2."],
[error.encoding, error.message])
end
end

def test_open_encoding_nonexistent
_output, error = capture_output do
CSV.open(@input.path, encoding: "nonexistent") do
Expand Down