Skip to content

Report the right line for invalid encoding in an IO sample - #393

Open
sourya2704 wants to merge 1 commit into
ruby:mainfrom
sourya2704:invalid-encoding-line-number-io
Open

sourya2704 wants to merge 1 commit into
ruby:mainfrom
sourya2704:invalid-encoding-line-number-io

Conversation

@sourya2704

Copy link
Copy Markdown

Fix GH-385.

With row_sep: :auto, CSV reads a sample from a File or another IO to detect the row separator. build_scanner only finds the line of an invalid byte when that sample is the whole input. Otherwise the sample goes to InputsScanner, whose first read_chunk raises InvalidEncoding for the whole sample before any row is parsed. @scanner is still nil, so parse reports line 1.

This checks the samples the same way before building InputsScanner. The existing check is moved into a check_encoding helper and used for both cases. As @wtn suggested in the issue, the samples are joined only when one of them is invalid, so valid input isn't copied.

With the script from the issue:

small String: CSV::InvalidEncodingError: Invalid byte sequence in UTF-8 in line 2. (line_number=2)
small File  : CSV::InvalidEncodingError: Invalid byte sequence in UTF-8 in line 2. (line_number=2)
large String: CSV::InvalidEncodingError: Invalid byte sequence in UTF-8 in line 2. (line_number=2)
large File  : CSV::InvalidEncodingError: Invalid byte sequence in UTF-8 in line 2. (line_number=2)

A pipe (IO.popen) and a bad byte on line 3 give the right line too. A bad byte after the sample was already reported correctly and still is.

The issue's "small" file also took the InputsScanner path. gets(nil, 32 * 1024) stops after the invalid byte, so the input isn't at EOF after the sample.

Tests: two tests in test/csv/interface/test_read.rb, one for a file that fits in the sample and one for a file longer than it. They use read because with CSV_PARSER_SCANNER_TEST=yes the error is raised later, not on the first shift. Both fail without the fix. The full suite passes with and without CSV_PARSER_SCANNER_TEST=yes.

GitHub: fix rubyGH-385

With row_sep: :auto, a File or another IO is sampled to detect the row
separator. build_scanner computed the line of an invalid byte only when
the sample was the whole input. Otherwise the sample went to
InputsScanner, which raised InvalidEncoding for the whole sample before
any row was parsed, so the error always said line 1.

Check the samples the same way before building InputsScanner. They're
joined only when one of them is invalid, so valid input isn't copied.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

InvalidEncodingError reports line 1 when the invalid byte is in the row separator detection sample (File/IO input)

1 participant