Class: CSVUtils::CSVOptions

Inherits:
Object
  • Object
show all
Defined in:
lib/csv_utils/csv_options.rb

Overview

Detects the separators, byte order mark, encoding and column count of a CSV file from its header row and, for the encoding, its first SAMPLE_SIZE bytes or, with full_scan, all of them.

Examples:

options = CSVUtils::CSVOptions.new('data.csv')
CSV.open('data.csv', 'rb', col_sep: options.col_separator) if options.valid?

Constant Summary collapse

BYTE_ORDER_MARKS =

Returns byte order marks, as binary strings, to the encoding they indicate.

Returns:

  • (Hash{String => String}) —

    byte order marks, as binary strings, to the encoding they indicate

ByteOrderMark::ENCODINGS
COL_SEPARATORS =

Returns column separators to look for; the one found most often outside quotes in the header row wins, and on a tie the one listed first.

Returns:

  • (Array<String>) —

    column separators to look for; the one found most often outside quotes in the header row wins, and on a tie the one listed first

[
  "\x02",
  "\t",
  '|',
  ',',
  ';'
].freeze
ROW_SEPARATORS =

Returns row separators to look for, the first one found in the line wins.

Returns:

  • (Array<String>) —

    row separators to look for, the first one found in the line wins

[
  "\r\n",
  "\n",
  "\r"
].freeze
WIDE_ENCODINGS =

Returns UTF-16 and UTF-32 byte order marks, as binary strings, to the :encoding option that decodes them to UTF-8.

Returns:

  • (Hash{String => String}) —

    UTF-16 and UTF-32 byte order marks, as binary strings, to the :encoding option that decodes them to UTF-8

{
  (+"\x00\x00\xFE\xFF").force_encoding('ASCII-8BIT').freeze => 'BOM|UTF-32BE:UTF-8',
  (+"\xFF\xFE\x00\x00").force_encoding('ASCII-8BIT').freeze => 'BOM|UTF-32LE:UTF-8',
  (+"\xFE\xFF").force_encoding('ASCII-8BIT').freeze => 'BOM|UTF-16BE:UTF-8',
  (+"\xFF\xFE").force_encoding('ASCII-8BIT').freeze => 'BOM|UTF-16LE:UTF-8'
}.freeze
SAMPLE_SIZE =

Returns bytes read to detect the encoding of a file without a byte order mark.

Returns:

  • (Integer) —

    bytes read to detect the encoding of a file without a byte order mark

1024 * 1024

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(io, full_scan: false) ⇒ CSVOptions

Returns a new instance of CSVOptions.

Parameters:

  • io (String, IO) —

    path of the file, or an IO positioned at its first line; up to SAMPLE_SIZE bytes are read from it, or all of it with full_scan

  • full_scan (Boolean) (defaults to: false) —

    check the encoding of the whole file, in SAMPLE_SIZE chunks, for files whose first bytes that aren't UTF-8 may come after the sample



66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/csv_utils/csv_options.rb', line 66

def initialize(io, full_scan: false)
  open_io(io) do |input|
    sample = input.read(SAMPLE_SIZE) || ''
    line = first_line(sample)

    @col_separator = auto_detect_col_sep(line)
    @row_separator = auto_detect_row_sep(line)
    @byte_order_mark = get_byte_order_mark(line)
    @encoding = get_character_encoding(@byte_order_mark, sample, full_scan ? input : nil)
    @columns = get_number_of_columns(line) if @col_separator
  end
end

Instance Attribute Details

#byte_order_mark ⇒ String? (readonly)

Returns the byte order mark the file starts with, as a binary string.

Returns:

  • (String, nil) —

    the byte order mark the file starts with, as a binary string



52
53
54
# File 'lib/csv_utils/csv_options.rb', line 52

def byte_order_mark
  @byte_order_mark
end

#col_separator ⇒ String? (readonly)

Returns one of COL_SEPARATORS.

Returns:



58
59
60
# File 'lib/csv_utils/csv_options.rb', line 58

def col_separator
  @col_separator
end

#columns ⇒ Integer? (readonly)

Returns number of headers, nil without a column separator.

Returns:

  • (Integer, nil) —

    number of headers, nil without a column separator



50
51
52
# File 'lib/csv_utils/csv_options.rb', line 50

def columns
  @columns
end

#encoding ⇒ String (readonly)

Returns 'UTF-8', 'UTF-16' or 'UTF-32' from the byte order mark; without one, from the first SAMPLE_SIZE bytes, or all of them with full_scan: 'UTF-8', 'Windows-1252' or 'ISO-8859-1' (see CSVUtils::CharacterEncoding.detect).

Returns:

  • (String) —

    'UTF-8', 'UTF-16' or 'UTF-32' from the byte order mark; without one, from the first SAMPLE_SIZE bytes, or all of them with full_scan: 'UTF-8', 'Windows-1252' or 'ISO-8859-1' (see CSVUtils::CharacterEncoding.detect)



56
57
58
# File 'lib/csv_utils/csv_options.rb', line 56

def encoding
  @encoding
end

#row_separator ⇒ String? (readonly)

Returns one of ROW_SEPARATORS.

Returns:



60
61
62
# File 'lib/csv_utils/csv_options.rb', line 60

def row_separator
  @row_separator
end

Instance Method Details

#auto_detect_col_sep(line) ⇒ String?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns the separator found most often outside quotes, nil when there's none.

Parameters:

  • line (String) —

    the header row

Returns:

  • (String, nil) —

    the separator found most often outside quotes, nil when there's none



105
106
107
108
109
110
111
# File 'lib/csv_utils/csv_options.rb', line 105

def auto_detect_col_sep(line)
  unquoted = line.b.gsub(QUOTED, '')
  counts = COL_SEPARATORS.map { |sep| unquoted.count(sep) }
  return if counts.max.zero?

  COL_SEPARATORS[counts.index(counts.max)]
end

#auto_detect_row_sep(line) ⇒ String?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • line (String)

Returns:

  • (String, nil)


116
117
118
# File 'lib/csv_utils/csv_options.rb', line 116

def auto_detect_row_sep(line)
  ROW_SEPARATORS.detect { |sep| line.include?(sep) }
end

#get_byte_order_mark(line) ⇒ String?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • line (String)

Returns:

  • (String, nil)


141
142
143
# File 'lib/csv_utils/csv_options.rb', line 141

def get_byte_order_mark(line)
  ByteOrderMark.detect(line)
end

#get_character_encoding(bom, sample, rest = nil) ⇒ String

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • bom (String, nil)
  • sample (String) —

    bytes from the start of the file

  • rest (IO, nil) (defaults to: nil) —

    the rest of the file, to scan it all

Returns:

  • (String)


150
151
152
153
154
155
# File 'lib/csv_utils/csv_options.rb', line 150

def get_character_encoding(bom, sample, rest = nil)
  return BYTE_ORDER_MARKS[bom] if bom
  return CharacterEncoding.detect_stream(chunks(sample, rest)) if rest

  CharacterEncoding.detect(sample, truncated: sample.bytesize == SAMPLE_SIZE)
end

#get_headers(line) ⇒ Array<String, nil>

Parses the header line like a CSV row, so quoted headers can contain the separator, and falls back to a plain split when the line is malformed.

Parameters:

  • line (String) —

    the first line of the file

Returns:

  • (Array<String, nil>) —

    headers without the byte order mark or row separator



124
125
126
127
128
129
# File 'lib/csv_utils/csv_options.rb', line 124

def get_headers(line)
  line = strip_byte_order_marks(line)
  CSV.parse_line(line, **header_parse_options) || []
rescue CSV::MalformedCSVError
  line.chomp(row_separator.to_s).split(col_separator, -1)
end

#get_number_of_columns(line) ⇒ Integer

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • line (String)

Returns:

  • (Integer)


134
135
136
# File 'lib/csv_utils/csv_options.rb', line 134

def get_number_of_columns(line)
  get_headers(line).size
end

#strip_byte_order_marks(header) ⇒ String

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • header (String)

Returns:

  • (String)


160
161
162
# File 'lib/csv_utils/csv_options.rb', line 160

def strip_byte_order_marks(header)
  ByteOrderMark.strip(header)
end

#to_csv_options ⇒ Hash{Symbol => String}

Options for CSV.open, or any class in this library, with the detected separators and an :encoding that reads values as UTF-8 strings: 'bom|utf-8', 'Windows-1252:UTF-8', 'BOM|UTF-16LE:UTF-8' and so on. A separator that wasn't detected is left to CSV, and so is the row separator of UTF-16 and UTF-32 files, since it's detected from raw bytes.

Examples:

CSV.open(path, 'rb', **options.to_csv_options)
CSVUtils::CSVSort.new(path, 'sorted.csv', true, options.to_csv_options).sort

Returns:

  • (Hash{Symbol => String})


95
96
97
98
99
100
# File 'lib/csv_utils/csv_options.rb', line 95

def to_csv_options
  options = { encoding: encoding_option }
  options[:col_sep] = col_separator if col_separator
  options[:row_sep] = row_separator if row_separator && !wide_encoding?
  options
end

#valid? ⇒ Boolean

Whether both separators were found. An empty file, or a single line without a newline, isn't valid.

Returns:

  • (Boolean)


81
82
83
84
85
# File 'lib/csv_utils/csv_options.rb', line 81

def valid?
  return false if @col_separator.nil? || @row_separator.nil?

  true
end