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
41 changes: 38 additions & 3 deletions lib/csv.rb
Original file line number Diff line number Diff line change
Expand Up @@ -851,6 +851,9 @@
class CSV

# The error thrown when the parser encounters illegal CSV formatting.
#
# After a CSV::InvalidEncodingError, parsing stops. After any other of
# these errors, CSV#shift continues reading at the next line.
class MalformedCSVError < RuntimeError
attr_reader :line_number
alias_method :lineno, :line_number
Expand All @@ -860,12 +863,22 @@ def initialize(message, line_number)
end
end

# The error thrown when the parser encounters invalid encoding in CSV.
# The error thrown when the parser encounters invalid encoding in CSV,
# or when the input File or IO can't convert the data to the internal
# encoding. In the second case, the original Encoding error is #cause.
# Parsing stops at this error; see CSV#shift. With String input, a
# conversion error is raised by CSV.new as the Encoding error itself.
#
# #encoding is the encoding the data was read in. +message+ replaces
# the default "Invalid byte sequence in ..." text, for example for
# data that is valid but can't be converted.
class InvalidEncodingError < MalformedCSVError
attr_reader :encoding
def initialize(encoding, line_number)
def initialize(encoding,
line_number,
message: "Invalid byte sequence in #{encoding}")
@encoding = encoding
super("Invalid byte sequence in #{encoding}", line_number)
super(message, line_number)
end
end

Expand Down Expand Up @@ -2429,6 +2442,10 @@ def to_io
@io.respond_to?(:to_io) ? @io.to_io : @io
end

# Returns +true+ when all of the input has been read, and +false+
# before the first row is read. It also returns +true+ after a
# CSV::InvalidEncodingError, which stops parsing, even though the
# input has unread data. See #shift.
def eof?
parser.eof?
end
Expand Down Expand Up @@ -2783,6 +2800,24 @@ def header_row?
# csv.close
# # Raises IOError (not opened for reading)
# csv.shift
#
# Raises CSV::InvalidEncodingError if the data has an invalid byte
# sequence, or if the IO can't convert it to the internal encoding.
# Parsing stops at that error: later calls return +nil+, #eof? returns
# +true+, and the rest of the input isn't read. So a loop that rescues
# CSV::MalformedCSVError and continues ends at the first such error,
# and #eof? doesn't show whether all the input was read.
#
# The rows before the error are returned, except with String input,
# and except when the error is in the data read from the start of a
# File or IO to detect the row separator (with the default
# <tt>row_sep: :auto</tt>).
#
# To read past invalid data, replace it before parsing. String#scrub
# does this for a String; for a large IO, scrub each line as it is
# read. When the IO converts to a different internal encoding,
# <tt>invalid: :replace</tt> and <tt>undef: :replace</tt>, which
# CSV.open passes to File.open, also replace it.
def shift
parser.parse do |row|
return row
Expand Down
165 changes: 151 additions & 14 deletions lib/csv/parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ def eof?(input)
class InvalidEncoding < StandardError
end

# Raised when the input IO can't transcode its data.
class InvalidTranscoding < InvalidEncoding
end

# Raised when unexpected case is happen.
class UnexpectedError < StandardError
end
Expand Down Expand Up @@ -92,6 +96,9 @@ def keep_drop
# CSV::InputsScanner.scan() tries to match with pattern at the current position.
# If there's a match, the scanner advances the "scan pointer" and returns the matched string.
# Otherwise, the scanner returns nil.
# If reading the next chunk after a match fails with InvalidEncoding,
# scan() still returns the match, and the error is raised when the
# scanner next reads from the input that failed.
#
# CSV::InputsScanner.rest() returns the "rest" of the string (i.e. everything after the scan pointer).
# If there is no more data (eos? = true), it returns "".
Expand All @@ -104,6 +111,8 @@ def initialize(inputs, encoding, row_separator, chunk_size: 8192)
@chunk_size = chunk_size
@last_scanner = @inputs.empty?
@keeps = []
@pending_invalid_encoding = nil
@pending_invalid_encoding_input = nil
read_chunk
end

Expand Down Expand Up @@ -155,23 +164,35 @@ def each_line(row_separator)

def scan(pattern)
# trace(__method__, pattern, :start)
read_chunk if @pending_invalid_encoding and @scanner.eos?
value = @scanner.scan(pattern)
# trace(__method__, pattern, :done, :last, value) if @last_scanner
return value if @last_scanner

read_chunk if value and @scanner.eos?
if value and @scanner.eos?
begin
read_chunk
rescue InvalidEncoding => error
# scan() never extends a match into the next chunk, so the
# error can wait for the next read.
defer_invalid_encoding(error)
end
end
# trace(__method__, pattern, :done, value)
value
end

def scan_all(pattern)
# trace(__method__, pattern, :start)
read_chunk if @pending_invalid_encoding and @scanner.eos?
value = @scanner.scan(pattern)
# trace(__method__, pattern, :done, :last, value) if @last_scanner
return value if @last_scanner

# trace(__method__, pattern, :done, :nil) if value.nil?
return nil if value.nil?
# The value may continue in the next chunk, so a failed read here
# raises at once instead of being deferred like in scan().
while @scanner.eos? and read_chunk and (sub_value = @scanner.scan(pattern))
# trace(__method__, pattern, :sub, sub_value)
value << sub_value
Expand Down Expand Up @@ -304,26 +325,80 @@ def adjust_last_keep
# trace(__method__, :done)
end

def defer_invalid_encoding(error)
@pending_invalid_encoding = error
@pending_invalid_encoding_input = @inputs.first
end

# Raises the deferred error once the next read would come from the
# input that failed. Data that keep_back pushed back in front of it
# is read first.
def raise_pending_invalid_encoding
error = @pending_invalid_encoding
return if error.nil?
return unless @inputs.first.equal?(@pending_invalid_encoding_input)
@pending_invalid_encoding = nil
@pending_invalid_encoding_input = nil
raise error
end

# When the previous chunk ends with the start of the row separator
# and +chunk+ starts with the remainder, returns that remainder;
# otherwise nil.
def row_separator_rest(chunk)
# There is no previous chunk while the first chunk is read.
return nil if @scanner.nil?
return nil if @row_separator.size < 2
previous = @scanner.string
(1...@row_separator.size).each do |n|
next unless previous.end_with?(@row_separator[0, n])
rest = @row_separator[n..-1]
return rest if chunk.byteslice(0, rest.bytesize).b == rest.b
end
nil
end

def read_chunk
raise_pending_invalid_encoding
return false if @last_scanner

adjust_last_keep

# Call adjust_last_keep only just before replacing @scanner: it
# copies the kept part of @scanner into the keep's buffer, so if
# @scanner stays (a failed read), keep_end returns that part twice.
input = @inputs.first
case input
when StringIO
string = input.read
raise InvalidEncoding unless string.valid_encoding?
# trace(__method__, :stringio, string)
adjust_last_keep
@scanner = StringScanner.new(string)
@inputs.shift
@last_scanner = @inputs.empty?
true
else
chunk = input.gets(@row_separator, @chunk_size)
begin
chunk = input.gets(@row_separator, @chunk_size)
rescue Encoding::InvalidByteSequenceError,
Encoding::UndefinedConversionError => error
# IO#gets discards the data it read before the error, so when
# the previous chunk ended in the middle of the row separator,
# the rest of it is lost with the previous row.
raise InvalidTranscoding, cause: error
end
if chunk
raise InvalidEncoding unless chunk.valid_encoding?
unless chunk.valid_encoding?
rest = row_separator_rest(chunk)
raise InvalidEncoding unless rest
# Scan the rest of the row separator first so the previous
# row can end, and raise the error on the next read.
adjust_last_keep
@scanner = StringScanner.new(rest)
defer_invalid_encoding(InvalidEncoding.new)
return true
end
# trace(__method__, :chunk, chunk)
adjust_last_keep
@scanner = StringScanner.new(chunk)
if Parser.eof?(input)
@inputs.shift
Expand All @@ -332,6 +407,7 @@ def read_chunk
true
else
# trace(__method__, :no_chunk)
adjust_last_keep
@scanner = StringScanner.new("".encode(@encoding))
@inputs.shift
@last_scanner = @inputs.empty?
Expand All @@ -349,6 +425,8 @@ def initialize(input, options)
@input = input
@options = options
@samples = []
@samples_transcoding_error = nil
@invalid_encoding_after_broken_line = nil

prepare
end
Expand Down Expand Up @@ -421,16 +499,33 @@ def parse(&block)
end

begin
@scanner ||= build_scanner
__send__(@parse_method, &block)
rescue InvalidEncoding
if @scanner
ignore_broken_line
lineno = @lineno
else
lineno = @lineno + 1
unless @scanner
if @samples_transcoding_error
raise InvalidTranscoding, cause: @samples_transcoding_error
end
begin
@scanner = build_scanner
rescue InvalidEncodingError
# build_scanner raises InvalidEncodingError itself when the
# whole input is one string.
finish_scanner
raise
end
end
if @invalid_encoding_after_broken_line
error = @invalid_encoding_after_broken_line
@invalid_encoding_after_broken_line = nil
raise error
end
raise InvalidEncodingError.new(@encoding, lineno)
__send__(@parse_method, &block)
rescue InvalidEncoding => error
# The error is in the line after the last row. For a transcoding
# error in the samples, IO#gets discards the data it read before
# the error, so that line isn't known and line 1 is reported.
@lineno += 1
finish_scanner
cause = error.is_a?(InvalidTranscoding) ? error.cause : error
raise invalid_encoding_error(error, @lineno), cause: cause
rescue UnexpectedError => error
if @scanner
ignore_broken_line
Expand Down Expand Up @@ -723,6 +818,12 @@ def resolve_row_separator(separator)
end
rescue IOError
# do nothing: ensure will set default
rescue Encoding::InvalidByteSequenceError,
Encoding::UndefinedConversionError => error
# #parse raises this as InvalidEncodingError. Raising it here
# would fail the parser's construction, and CSV would build a
# new parser, reading on from the IO, on every call.
@samples_transcoding_error = error
end
end
separator = InputRecordSeparator.value if separator == :auto
Expand Down Expand Up @@ -1254,6 +1355,42 @@ def ignore_broken_line
@scanner.scan_all(@not_line_end)
@scanner.scan_all(@line_end)
@lineno += 1
rescue InvalidEncoding => error
# The line end can reach an invalid next chunk. Raise the error on
# the next #parse call, so the error for the broken line comes
# first.
@lineno += 1
@invalid_encoding_after_broken_line = error
end

# Replaces the scanner with an empty one, so later #parse calls
# yield no data rows, #eof? returns true and #line returns "".
def finish_scanner
@scanner = Scanner.new("".encode(@encoding))
@scanner.keep_start
@last_line = nil
end

def invalid_encoding_error(error, lineno)
cause = error.cause if error.is_a?(InvalidTranscoding)
return InvalidEncodingError.new(@encoding, lineno) if cause.nil?

# Use the IO's encodings: the cause names the step that failed,
# which can be an intermediate encoding such as UTF-8.
source = io_encoding(:external_encoding) || cause.source_encoding
if cause.is_a?(Encoding::UndefinedConversionError)
destination =
io_encoding(:internal_encoding) || cause.destination_encoding
message = "Undefined conversion from #{source} to #{destination}"
InvalidEncodingError.new(source, lineno, message: message)
else
InvalidEncodingError.new(source, lineno)
end
end

def io_encoding(name)
return nil unless @input.respond_to?(name)
@input.public_send(name)
end

def start_row
Expand Down
Loading