|
| 1 | +require 'csv' |
| 2 | +require 'stringio' |
| 3 | + |
| 4 | +module CSVImporter |
| 5 | + |
| 6 | + # Reads, sanitize and parse a CSV file |
| 7 | + class CSVBatchReader < CSVReader |
| 8 | + |
| 9 | + attr_reader :separator |
| 10 | + |
| 11 | + def initialize(**kwargs) |
| 12 | + super |
| 13 | + # To avoid reprocessing the stream, let's process & cache the first few lines while detecting the separator |
| 14 | + @separator = detect_separator(lines.take(10).join("\n")) |
| 15 | + end |
| 16 | + |
| 17 | + # Returns the header as an Array of Strings |
| 18 | + def header |
| 19 | + return @header if @header |
| 20 | + |
| 21 | + parsed = CSV.parse_line(lines.first, col_sep: separator, quote_char: quote_char, skip_blanks: true, |
| 22 | + external_encoding: source_encoding) |
| 23 | + @header = encode_cells([parsed])[0] |
| 24 | + end |
| 25 | + |
| 26 | + # Returns the rows as an Enumerator |
| 27 | + def rows |
| 28 | + @rows ||= csv_enumerator |
| 29 | + end |
| 30 | + |
| 31 | + private |
| 32 | + |
| 33 | + def memoized_enumerator(enum, limit = 10) |
| 34 | + cache = [] |
| 35 | + Enumerator.new do |yielder| |
| 36 | + # Yield from cache first |
| 37 | + cache.each { |value| yielder << value } |
| 38 | + |
| 39 | + # Fill cache and yield values from the underlying enumerator |
| 40 | + while cache.size < limit |
| 41 | + begin |
| 42 | + value = enum.next |
| 43 | + cache << value |
| 44 | + yielder << value |
| 45 | + rescue StopIteration |
| 46 | + break |
| 47 | + end |
| 48 | + end |
| 49 | + |
| 50 | + # Yield the remaining values directly from the original enumerator |
| 51 | + loop do |
| 52 | + begin |
| 53 | + yielder << enum.next |
| 54 | + rescue StopIteration |
| 55 | + break |
| 56 | + end |
| 57 | + end |
| 58 | + end |
| 59 | + end |
| 60 | + |
| 61 | + def lines |
| 62 | + @lines ||= memoized_enumerator(stream_lines(content_stream)) |
| 63 | + end |
| 64 | + |
| 65 | + def stream_lines(stream, chunk_size = 4096, line_endings_regex = /(\r\n|\r|\n)/) |
| 66 | + Enumerator.new do |yielder| |
| 67 | + case stream |
| 68 | + when StringIO, IO |
| 69 | + buffer = "".force_encoding(source_encoding) |
| 70 | + until stream.eof? |
| 71 | + chunk = stream.read(chunk_size) |
| 72 | + buffer << chunk.force_encoding(source_encoding).encode(Encoding.find(source_encoding), invalid: :replace, undef: :replace, replace: '') # Remove invalid byte sequences |
| 73 | + |
| 74 | + while (match = buffer.match(line_endings_regex)) |
| 75 | + # Yield the part of the buffer before the line ending |
| 76 | + line = sanitize_content(buffer[0...match.begin(0)]) |
| 77 | + yielder << line unless line.empty? |
| 78 | + # Remove the processed part (including the line ending) |
| 79 | + buffer = buffer[match.end(0)..-1] |
| 80 | + end |
| 81 | + end |
| 82 | + |
| 83 | + # Yield any remaining content in the buffer after the end of the file |
| 84 | + yielder << sanitize_content(buffer) unless buffer.empty? |
| 85 | + stream.close if stream.respond_to?(:close) |
| 86 | + |
| 87 | + when String |
| 88 | + File.open(stream, 'r:' + source_encoding) do |file| |
| 89 | + stream_lines(file, chunk_size, line_endings_regex).each { |line| yielder << line } |
| 90 | + end |
| 91 | + |
| 92 | + else |
| 93 | + raise ArgumentError, "Unsupported stream type: #{stream.class}" |
| 94 | + end |
| 95 | + end |
| 96 | + end |
| 97 | + |
| 98 | + def csv_enumerator |
| 99 | + Enumerator.new do |yielder| |
| 100 | + lines.each_with_index do |line, index| |
| 101 | + next if index == 0 # skip header |
| 102 | + row = CSV.parse_line( |
| 103 | + line, |
| 104 | + col_sep: separator, |
| 105 | + quote_char: quote_char, |
| 106 | + skip_blanks: true, |
| 107 | + external_encoding: source_encoding |
| 108 | + ) |
| 109 | + yielder << encode_and_sanitize_row(row) if row |
| 110 | + end |
| 111 | + end |
| 112 | + end |
| 113 | + |
| 114 | + def content_stream |
| 115 | + if content.is_a?(StringIO) |
| 116 | + content |
| 117 | + elsif content.is_a?(String) |
| 118 | + StringIO.new(content) |
| 119 | + elsif file |
| 120 | + file |
| 121 | + elsif path |
| 122 | + File.open(path, 'r') |
| 123 | + else |
| 124 | + raise Error, "Please provide content, file, or path" |
| 125 | + end |
| 126 | + end |
| 127 | + |
| 128 | + def encode_and_sanitize_row(row) |
| 129 | + row.map do |cell| |
| 130 | + cell ? cell.encode(target_encoding).strip : "" |
| 131 | + end |
| 132 | + end |
| 133 | + end |
| 134 | +end |
0 commit comments