Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Normalize line endings before parsing CSV files (#4988)

sentry[bot]2daca5d8ba8c
diff --git a/app/models/import.rb b/app/models/import.rb
index cf05b971e2..346513c85a 100644
--- a/app/models/import.rb
+++ b/app/models/import.rb
@@ -189,7 +189,7 @@ class Import < ApplicationRecord
def parse_csv_str(csv_str, col_sep: ",")
CSV.parse(
- (csv_str || "").strip,
+ normalize_line_endings(csv_str).strip,
headers: true,
col_sep: col_sep,
converters: [ ->(str) { str&.strip } ],
@@ -197,6 +197,13 @@ class Import < ApplicationRecord
)
end
+ # Ruby's CSV auto-detects the row separator from the first newline it sees
+ # (ignoring quotes), so files mixing LF and CRLF (e.g. a quoted multi-line
+ # header followed by CRLF rows) fail to parse. Normalize to LF first.
+ def normalize_line_endings(csv_str)
+ (csv_str || "").gsub(/\r\n?/, "\n")
+ end
+
# Attempts to identify the best-matching date format from a list of candidates
# by trying to parse sample date strings with each format.
#
diff --git a/app/models/rule_import.rb b/app/models/rule_import.rb
index aa526007fb..e20c3e0ad2 100644
--- a/app/models/rule_import.rb
+++ b/app/models/rule_import.rb
@@ -125,7 +125,7 @@ class RuleImport < Import
# headers cannot tell a blank header cell from the nil CSV pads in for a
# row with more fields than the header.
def header_row_size
- header = CSV.parse_line((raw_file_str || "").strip, col_sep: col_sep, liberal_parsing: true)
+ header = CSV.parse_line(Import.normalize_line_endings(raw_file_str).strip, col_sep: col_sep, liberal_parsing: true)
header ? header.size : 0
end
diff --git a/test/models/import_test.rb b/test/models/import_test.rb
index 4eccb24236..2473ccd0ce 100644
--- a/test/models/import_test.rb
+++ b/test/models/import_test.rb
@@ -3,6 +3,26 @@ require "test_helper"
class ImportTest < ActiveSupport::TestCase
include ActiveJob::TestHelper
+ test "parse_csv_str handles a quoted multi-line header followed by CRLF rows" do
+ csv = Import.parse_csv_str("\"Date\nPosted\",Amount\r\n2024-01-01,5\r\n2024-01-02,6\r\n")
+
+ assert_equal [ "Date\nPosted", "Amount" ], csv.headers
+ assert_equal [ "5", "6" ], csv.map { |row| row["Amount"] }
+ end
+
+ test "parse_csv_str handles mixed LF and CRLF line endings" do
+ csv = Import.parse_csv_str("date,amount\n2024-01-01,5\r\n2024-01-02,6\r\n")
+
+ assert_equal [ "date", "amount" ], csv.headers
+ assert_equal [ "5", "6" ], csv.map { |row| row["amount"] }
+ end
+
+ test "parse_csv_str handles CR-only line endings" do
+ csv = Import.parse_csv_str("date,amount\r2024-01-01,5\r")
+
+ assert_equal [ "5" ], csv.map { |row| row["amount"] }
+ end
+
test "publish skips imports in terminal statuses" do
import = imports(:transaction)
import.update_columns(status: "complete")