Class: Csvlint::Validator

Inherits:
Object
  • Object
show all
Includes:
ErrorCollector
Defined in:
lib/csvlint/validate.rb

Defined Under Namespace

Classes: LineCSV

Constant Summary collapse

ERROR_MATCHERS =
{
  "Missing or stray quote" => :stray_quote,
  "Illegal quoting" => :whitespace,
  "Unclosed quoted field" => :unclosed_quote,
  "Any value after quoted field isn't allowed" => :unclosed_quote,
  "Unquoted fields do not allow \\r or \\n" => :line_breaks
}

Instance Attribute Summary collapse

Attributes included from ErrorCollector

#errors, #info_messages, #warnings

Instance Method Summary collapse

Methods included from ErrorCollector

#build_errors, #build_info_messages, #build_warnings, #reset, #valid?

Constructor Details

#initialize(source, dialect = {}, schema = nil, options = {}) ⇒ Validator

Returns a new instance of Validator.



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/csvlint/validate.rb', line 64

def initialize(source, dialect = {}, schema = nil, options = {})
  reset
  @source = source
  @formats = []
  @schema = schema
  @dialect = dialect
  @csv_header = true
  @headers = {}
  @lambda = options[:lambda]
  @validate = options[:validate].nil? ? true : options[:validate]
  @leading = ""

  @limit_lines = options[:limit_lines]
  @extension = parse_extension(source) unless @source.nil?

  @expected_columns = 0
  @col_counts = []
  @line_breaks = []

  @errors += @schema.errors unless @schema.nil?
  @warnings += @schema.warnings unless @schema.nil?

  @data = [] # it may be advisable to flush this on init?

  validate
end

Instance Attribute Details

#content_typeObject (readonly)

Returns the value of attribute content_type.



54
55
56
# File 'lib/csvlint/validate.rb', line 54

def content_type
  @content_type
end

#csv_headerObject (readonly)

Returns the value of attribute csv_header.



54
55
56
# File 'lib/csvlint/validate.rb', line 54

def csv_header
  @csv_header
end

#current_lineObject (readonly)

Returns the value of attribute current_line.



54
55
56
# File 'lib/csvlint/validate.rb', line 54

def current_line
  @current_line
end

#dataObject (readonly)

Returns the value of attribute data.



54
55
56
# File 'lib/csvlint/validate.rb', line 54

def data
  @data
end

#dialectObject (readonly)

Returns the value of attribute dialect.



54
55
56
# File 'lib/csvlint/validate.rb', line 54

def dialect
  @dialect
end

#encodingObject (readonly)

Returns the value of attribute encoding.



54
55
56
# File 'lib/csvlint/validate.rb', line 54

def encoding
  @encoding
end

#extensionObject (readonly)

Returns the value of attribute extension.



54
55
56
# File 'lib/csvlint/validate.rb', line 54

def extension
  @extension
end

#headersObject (readonly)

Returns the value of attribute headers.



54
55
56
# File 'lib/csvlint/validate.rb', line 54

def headers
  @headers
end

Returns the value of attribute link_headers.



54
55
56
# File 'lib/csvlint/validate.rb', line 54

def link_headers
  @link_headers
end

#schemaObject (readonly)

Returns the value of attribute schema.



54
55
56
# File 'lib/csvlint/validate.rb', line 54

def schema
  @schema
end

Instance Method Details

#build_exception_messages(csvException, errChars, lineNo) ⇒ Object



360
361
362
363
364
365
366
367
368
369
# File 'lib/csvlint/validate.rb', line 360

def build_exception_messages(csvException, errChars, lineNo)
  # TODO 1 - this is a change in logic, rather than straight refactor of previous error building, however original logic is bonkers
  # TODO 2 - using .kind_of? is a very ugly fix here and it meant to work around instances where :auto symbol is preserved in @csv_options
  type = fetch_error(csvException)
  if !@csv_options[:row_sep].is_a?(Symbol) && [:unclosed_quote, :stray_quote].include?(type) && !@input.match(@csv_options[:row_sep])
    build_linebreak_error
  else
    build_errors(type, :structure, lineNo, nil, errChars)
  end
end

#build_formats(row) ⇒ Object



416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
# File 'lib/csvlint/validate.rb', line 416

def build_formats(row)
  row.each_with_index do |col, i|
    next if col.nil? || col.empty?
    @formats[i] ||= Hash.new(0)

    format =
      if col.strip[FORMATS[:numeric]]
        :numeric
      elsif uri?(col)
        :uri
      elsif possible_date?(col)
        date_formats(col)
      else
        :string
      end

    @formats[i][format] += 1
  end
end

#build_linebreak_errorObject



371
372
373
# File 'lib/csvlint/validate.rb', line 371

def build_linebreak_error
  build_errors(:line_breaks, :structure) unless @errors.any? { |e| e.type == :line_breaks }
end

#check_consistencyObject



436
437
438
439
440
441
442
443
444
445
# File 'lib/csvlint/validate.rb', line 436

def check_consistency
  @formats.each_with_index do |format, i|
    if format
      total = format.values.reduce(:+).to_f
      if format.none? { |_, count| count / total >= 0.9 }
        build_warnings(:inconsistent_values, :schema, nil, i + 1)
      end
    end
  end
end

#check_foreign_keysObject



447
448
449
450
451
452
453
# File 'lib/csvlint/validate.rb', line 447

def check_foreign_keys
  if @schema.instance_of? Csvlint::Csvw::TableGroup
    @schema.validate_foreign_keys
    @errors += @schema.errors
    @warnings += @schema.warnings
  end
end

#check_mixed_linebreaksObject



344
345
346
# File 'lib/csvlint/validate.rb', line 344

def check_mixed_linebreaks
  build_linebreak_error if @line_breaks.uniq.count > 1
end

#dialect_to_csv_options(dialect) ⇒ Object



404
405
406
407
408
409
410
411
412
413
414
# File 'lib/csvlint/validate.rb', line 404

def dialect_to_csv_options(dialect)
  skipinitialspace = dialect["skipInitialSpace"] || true
  delimiter = dialect["delimiter"]
  delimiter += " " if !skipinitialspace
  {
    col_sep: delimiter,
    row_sep: dialect["lineTerminator"],
    quote_char: dialect["quoteChar"],
    skip_blanks: false
  }
end

#fetch_error(error) ⇒ Object



394
395
396
397
398
399
400
401
402
# File 'lib/csvlint/validate.rb', line 394

def fetch_error(error)
  e = error.message.match(/^(.+?)(?: [io]n)? \(?line \d+\)?\.?$/i)
  message = begin
    e[1]
  rescue
    nil
  end
  ERROR_MATCHERS.fetch(message, :unknown_error)
end

#finishObject



218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/csvlint/validate.rb', line 218

def finish
  sum = @col_counts.inject(:+)
  unless sum.nil?
    build_warnings(:title_row, :structure) if @col_counts.first < (sum / @col_counts.size.to_f)
  end
  # return expected_columns to calling class
  build_warnings(:check_options, :structure) if @expected_columns == 1
  check_consistency
  check_foreign_keys if @validate
  check_mixed_linebreaks
  validate_encoding
end

#header?Boolean

Returns:

  • (Boolean)


290
291
292
# File 'lib/csvlint/validate.rb', line 290

def header?
  @csv_header && @dialect["header"]
end

#line_breaksObject



348
349
350
351
352
353
354
# File 'lib/csvlint/validate.rb', line 348

def line_breaks
  if @line_breaks.uniq.count > 1
    :mixed
  else
    @line_breaks.uniq.first
  end
end

#line_breaks_reported?Boolean

Returns:

  • (Boolean)


306
307
308
# File 'lib/csvlint/validate.rb', line 306

def line_breaks_reported?
  @line_breaks_reported === true
end

#locate_schemaObject



455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
# File 'lib/csvlint/validate.rb', line 455

def locate_schema
  @source_url = nil
  warn_if_unsuccessful = false
  case @source
  when StringIO
    return
  when File
    uri_parser = URI::DEFAULT_PARSER
    @source_url = "file:#{uri_parser.escape(File.expand_path(@source))}"
  else
    @source_url = @source
  end
  unless @schema.nil?
    if @schema.tables[@source_url]
      return
    else
      @schema = nil
    end
  end
  paths = []
  if /^http(s)?/.match?(@source_url)
    begin
      well_known_uri = URI.join(@source_url, "/.well-known/csvm")
      paths = URI.open(well_known_uri.to_s).read.split("\n")
    rescue OpenURI::HTTPError, URI::BadURIError
    end
  end
  paths = ["{+url}-metadata.json", "csv-metadata.json"] if paths.empty?
  paths.each do |template|
    template = URITemplate.new(template)
    path = template.expand("url" => @source_url)
    url = URI.join(@source_url, path)
    url = File.new(url.to_s.sub(/^file:/, "")) if /^file:/.match?(url.to_s)
    schema = Schema.load_from_uri(url)
    if schema.instance_of? Csvlint::Csvw::TableGroup
      if schema.tables[@source_url]
        @schema = schema
        return
      else
        warn_if_unsuccessful = true
        build_warnings(:schema_mismatch, :context, nil, nil, @source_url, schema)
      end
    end
  rescue Errno::ENOENT
  rescue OpenURI::HTTPError, URI::BadURIError, ArgumentError
  rescue => e
    raise e
  end
  build_warnings(:schema_mismatch, :context, nil, nil, @source_url, schema) if warn_if_unsuccessful
  @schema = nil
end

#parse_contents(stream, line = nil) ⇒ Object

analyses the provided csv and builds errors, warnings and info messages



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/csvlint/validate.rb', line 180

def parse_contents(stream, line = nil)
  # parse_contents will parse one line and apply headers, formats methods and error handle as appropriate
  current_line = line.present? ? line : 1
  all_errors = []

  @csv_options[:encoding] = @encoding

  begin
    row = LineCSV.parse_line(stream, **@csv_options)
  rescue LineCSV::MalformedCSVError => e
    build_exception_messages(e, stream, current_line) unless e.message.include?("UTF") && @reported_invalid_encoding
  end

  if row
    if current_line <= 1 && @csv_header
      # this conditional should be refactored somewhere
      row = row.reject { |col| col.nil? || col.empty? }
      validate_header(row)
      @col_counts << row.size
    else
      build_formats(row)
      @col_counts << row.reject { |col| col.nil? || col.empty? }.size
      @expected_columns = row.size unless @expected_columns != 0
      build_errors(:blank_rows, :structure, current_line, nil, stream.to_s) if row.reject { |c| c.nil? || c.empty? }.size == 0
      # Builds errors and warnings related to the provided schema file
      if @schema
        @schema.validate_row(row, current_line, all_errors, @source, @validate)
        @errors += @schema.errors
        all_errors += @schema.errors
        @warnings += @schema.warnings
      elsif !row.empty? && row.size != @expected_columns
        build_errors(:ragged_rows, :structure, current_line, nil, stream.to_s)
      end
    end
  end
  @data << row
end

#parse_line(line) ⇒ Object



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/csvlint/validate.rb', line 144

def parse_line(line)
  line = @leading + line
  # Check if the last line is a line break - in which case it's a full line
  if line[-1, 1].include?("\n")
    # If the number of quotes is odd, the linebreak is inside some quotes
    if line.count(@dialect["quoteChar"]).odd?
      @leading = line
    else
      validate_line(line, @current_line)
      @leading = ""
      @current_line += 1
    end
  else
    # If it's not a full line, then prepare to add it to the beginning of the next chunk
    @leading = line
  end
rescue ArgumentError => ae
  build_errors(:invalid_encoding, :structure, @current_line, nil, @current_line) unless @reported_invalid_encoding
  @current_line += 1
  @reported_invalid_encoding = true
end

#report_line_breaks(line_no = nil) ⇒ Object



294
295
296
297
298
299
300
301
302
303
304
# File 'lib/csvlint/validate.rb', line 294

def report_line_breaks(line_no = nil)
  return unless @input[-1, 1].include?("\n") # Return straight away if there's no newline character - i.e. we're on the last line
  line_break = get_line_break(@input)
  @line_breaks << line_break
  unless line_breaks_reported?
    if line_break != "\r\n"
      build_info_messages(:nonrfc_line_breaks, :structure, line_no)
      @line_breaks_reported = true
    end
  end
end

#row_countObject



356
357
358
# File 'lib/csvlint/validate.rb', line 356

def row_count
  data.count
end

#set_dialectObject



310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/csvlint/validate.rb', line 310

def set_dialect
  @assumed_header = @dialect["header"].nil?
  @supplied_dialect = @dialect != {}

  begin
    schema_dialect = @schema.tables[@source_url].dialect || {}
  rescue
    schema_dialect = {}
  end
  @dialect = {
    "header" => true,
    "headerRowCount" => 1,
    "delimiter" => ",",
    "skipInitialSpace" => true,
    "lineTerminator" => :auto,
    "quoteChar" => '"',
    "trim" => :true
  }.merge(schema_dialect).merge(@dialect || {})

  @csv_header &&= @dialect["header"]
  @csv_options = dialect_to_csv_options(@dialect)
end

#validateObject



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/csvlint/validate.rb', line 91

def validate
  if /.xls(x)?/.match?(@extension)
    build_warnings(:excel, :context)
    return
  end
  locate_schema unless @schema.instance_of?(Csvlint::Schema)
  set_dialect

  if @source.instance_of?(String)
    validate_url
  else
    
    validate_stream
  end
  finish
end

#validate_encodingObject



333
334
335
336
337
338
339
340
341
342
# File 'lib/csvlint/validate.rb', line 333

def validate_encoding
  if @headers["content-type"]
    if !/charset=/.match?(@headers["content-type"])
      build_warnings(:no_encoding, :context)
    elsif !/charset=utf-8/i.match?(@headers["content-type"])
      build_warnings(:encoding, :context)
    end
  end
  build_warnings(:encoding, :context) if @encoding != "UTF-8"
end

#validate_header(header) ⇒ Object



375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# File 'lib/csvlint/validate.rb', line 375

def validate_header(header)
  names = Set.new
  header.map { |h| h.strip! } if @dialect["trim"] == :true
  header.each_with_index do |name, i|
    build_warnings(:empty_column_name, :schema, nil, i + 1) if name == ""
    if names.include?(name)
      build_warnings(:duplicate_column_name, :schema, nil, i + 1)
    else
      names << name
    end
  end
  if @schema
    @schema.validate_header(header, @source, @validate)
    @errors += @schema.errors
    @warnings += @schema.warnings
  end
  valid?
end

#validate_line(input = nil, index = nil) ⇒ Object



166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/csvlint/validate.rb', line 166

def validate_line(input = nil, index = nil)
  @input = input
  single_col = false
  line = index.present? ? index : 0
  @encoding = input.encoding.to_s
  report_line_breaks(line)
  parse_contents(input, line)
  @lambda&.call(self)
rescue ArgumentError => ae
  build_errors(:invalid_encoding, :structure, @current_line, nil, index) unless @reported_invalid_encoding
  @reported_invalid_encoding = true
end

#validate_metadataObject



231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
# File 'lib/csvlint/validate.rb', line 231

def 
  assumed_header = !@supplied_dialect
  unless @headers.empty?
    if /text\/csv/.match?(@headers["content-type"])
      @csv_header &&= true
      assumed_header = @assumed_header.present?
    end
    if @headers["content-type"] =~ /header=(present|absent)/
      @csv_header = true if $1 == "present"
      @csv_header = false if $1 == "absent"
      assumed_header = false
    end
    build_warnings(:no_content_type, :context) if @content_type.nil?
    build_errors(:wrong_content_type, :context) unless @content_type && @content_type =~ /text\/csv/
  end
  @header_processed = true
  build_info_messages(:assumed_header, :structure) if assumed_header

  @link_headers = begin
    @headers["link"].split(",")
  rescue
    nil
  end
  @link_headers&.each do |link_header|
    match = LINK_HEADER_REGEXP.match(link_header)
    uri = begin
      match["uri"].gsub(/(^<|>$)/, "")
    rescue
      nil
    end
    rel = begin
      match["rel-relationship"].gsub(/(^"|"$)/, "")
    rescue
      nil
    end
    param = match["param"]
    param_value = begin
      match["param-value"].gsub(/(^"|"$)/, "")
    rescue
      nil
    end
    if rel == "describedby" && param == "type" && ["application/csvm+json", "application/ld+json", "application/json"].include?(param_value)
      begin
        url = URI.join(@source_url, uri)
        schema = Schema.load_from_uri(url)
        if schema.instance_of? Csvlint::Csvw::TableGroup
          if schema.tables[@source_url]
            @schema = schema
          else
            warn_if_unsuccessful = true
            build_warnings(:schema_mismatch, :context, nil, nil, @source_url, schema)
          end
        end
      rescue OpenURI::HTTPError
      end
    end
  end
end

#validate_streamObject



108
109
110
111
112
113
114
115
# File 'lib/csvlint/validate.rb', line 108

def validate_stream
  @current_line = 1
  @source.each_line do |line|
    break if line_limit_reached?
    parse_line(line)
  end
  validate_line(@leading, @current_line) unless @leading == ""
end

#validate_urlObject



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/csvlint/validate.rb', line 117

def validate_url
  @current_line = 1
  request = Typhoeus::Request.new(@source, followlocation: true)
  request.on_headers do |response|
    @headers = response.headers || {}
    @content_type = begin
      response.headers["content-type"]
    rescue
      nil
    end
    @response_code = response.code
    return build_errors(:not_found) if response.code == 404
    
  end
  request.on_body do |chunk|
    chunk.force_encoding(Encoding::UTF_8) if chunk.encoding == Encoding::ASCII_8BIT
    io = StringIO.new(chunk)
    io.each_line do |line|
      break if line_limit_reached?
      parse_line(line)
    end
  end
  request.run
  # Validate the last line too
  validate_line(@leading, @current_line) unless @leading == ""
end