diff --git a/lib/csv/writer.rb b/lib/csv/writer.rb index b59f111e..3691822f 100644 --- a/lib/csv/writer.rb +++ b/lib/csv/writer.rb @@ -186,6 +186,19 @@ def quote_field(field) encoded_quote_character end + # An invalid byte makes Regexp#match? raise, and the old guard then + # wrote the field raw. Search for the separator bytes instead so a + # newline or comma still forces quotes (csv#395). + def field_needs_quotes?(field) + return @quotable_pattern.match?(field) if field.valid_encoding? + + encoding = field.encoding + field.include?("\r".encode(encoding)) || + field.include?("\n".encode(encoding)) || + field.include?(@column_separator.encode(encoding)) || + field.include?(@quote_character.encode(encoding)) + end + def quote(field, i) if @force_quotes quote_field(field) @@ -197,7 +210,7 @@ def quote(field, i) else field = String(field) # Stringify fields # represent empty fields as empty quoted fields - if (@quote_empty and field.empty?) or (field.valid_encoding? and @quotable_pattern.match?(field)) + if (@quote_empty and field.empty?) or field_needs_quotes?(field) quote_field(field) else field # unquoted field diff --git a/test/csv/write/test_general.rb b/test/csv/write/test_general.rb index 4788d99e..e4f04f41 100644 --- a/test/csv/write/test_general.rb +++ b/test/csv/write/test_general.rb @@ -26,6 +26,30 @@ def test_quote generate_line(["foo", %Q["bar"], "baz"])) end + def test_quote_invalid_encoding + ["UTF-8", "Shift_JIS", "EUC-JP"].each do |name| + newline = "x\xFF\nadmin,true".dup.force_encoding(name) + assert_equal(%Q["x\xFF\nadmin,true"#{$INPUT_RECORD_SEPARATOR}].b, + generate_line([newline]).b, + name) + comma = "x\xFF,approved".dup.force_encoding(name) + assert_equal(%Q["x\xFF,approved"#{$INPUT_RECORD_SEPARATOR}].b, + generate_line([comma]).b, + name) + quote = "x\xFF\"y".dup.force_encoding(name) + assert_equal(%Q["x\xFF""y"#{$INPUT_RECORD_SEPARATOR}].b, + generate_line([quote]).b, + name) + line = generate_line(["user", newline, "role"]) + assert_equal([["user", newline.b, "role"]], + CSV.parse(line.b, encoding: "ASCII-8BIT"), + name) + end + plain = "x\xFFok".dup.force_encoding("UTF-8") + assert_equal("x\xFFok#{$INPUT_RECORD_SEPARATOR}", + generate_line([plain])) + end + def test_quote_lf assert_equal(%Q["""\n","""\n"#{$INPUT_RECORD_SEPARATOR}], generate_line([%Q["\n], %Q["\n]]))