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,
    "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.



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

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.



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

def content_type
  @content_type
end

#csv_headerObject (readonly)

Returns the value of attribute csv_header.



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

def csv_header
  @csv_header
end

#current_lineObject (readonly)

Returns the value of attribute current_line.



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

def current_line
  @current_line
end

#dataObject (readonly)

Returns the value of attribute data.



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

def data
  @data
end

#dialectObject (readonly)

Returns the value of attribute dialect.



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

def dialect
  @dialect
end

#encodingObject (readonly)

Returns the value of attribute encoding.



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

def encoding
  @encoding
end

#extensionObject (readonly)

Returns the value of attribute extension.



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

def extension
  @extension
end

#headersObject (readonly)

Returns the value of attribute headers.



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

def headers
  @headers
end

Returns the value of attribute link_headers.



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

def link_headers
  @link_headers
end

#schemaObject (readonly)

Returns the value of attribute schema.



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

def schema
  @schema
end

Instance Method Details

#build_exception_messages(csvException, errChars, lineNo) ⇒ Object



337
338
339
340
341
342
343
344
345
346
# File 'lib/csvlint/validate.rb', line 337

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].kind_of?(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



389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# File 'lib/csvlint/validate.rb', line 389

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



348
349
350
# File 'lib/csvlint/validate.rb', line 348

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

#check_consistencyObject



409
410
411
412
413
414
415
416
417
418
# File 'lib/csvlint/validate.rb', line 409

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



420
421
422
423
424
425
426
# File 'lib/csvlint/validate.rb', line 420

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



321
322
323
# File 'lib/csvlint/validate.rb', line 321

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

#dialect_to_csv_options(dialect) ⇒ Object



377
378
379
380
381
382
383
384
385
386
387
# File 'lib/csvlint/validate.rb', line 377

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

#fetch_error(error) ⇒ Object



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

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

#finishObject



211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/csvlint/validate.rb', line 211

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)


267
268
269
# File 'lib/csvlint/validate.rb', line 267

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

#line_breaksObject



325
326
327
328
329
330
331
# File 'lib/csvlint/validate.rb', line 325

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

#line_breaks_reported?Boolean

Returns:

  • (Boolean)


283
284
285
# File 'lib/csvlint/validate.rb', line 283

def line_breaks_reported?
  @line_breaks_reported === true
end

#locate_schemaObject



428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
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
# File 'lib/csvlint/validate.rb', line 428

def locate_schema

  @source_url = nil
  warn_if_unsuccessful = false
  case @source
    when StringIO
      return
    when File
      @source_url = "file:#{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 @source_url =~ /^http(s)?/
    begin
      well_known_uri = URI.join(@source_url, "/.well-known/csvm")
      paths = open(well_known_uri).read.split("\n")
    rescue OpenURI::HTTPError, URI::BadURIError
    end
  end
  paths = ["{+url}-metadata.json", "csv-metadata.json"] if paths.empty?
  paths.each do |template|
    begin
      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 url.to_s =~ /^file:/
      schema = Schema.load_from_json(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
  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



173
174
175
176
177
178
179
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
# File 'lib/csvlint/validate.rb', line 173

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)
  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
      else
        build_errors(:ragged_rows, :structure, current_line, nil, stream.to_s) if !row.empty? && row.size != @expected_columns
      end
    end
  end
  @data << row
end

#parse_line(line) ⇒ Object



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/csvlint/validate.rb', line 137

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 = @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 = @current_line+1
  @reported_invalid_encoding = true
end

#report_line_breaks(line_no = nil) ⇒ Object



271
272
273
274
275
276
277
278
279
280
281
# File 'lib/csvlint/validate.rb', line 271

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



333
334
335
# File 'lib/csvlint/validate.rb', line 333

def row_count
  data.count
end

#set_dialectObject



287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# File 'lib/csvlint/validate.rb', line 287

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 = @csv_header && @dialect["header"]
  @csv_options = dialect_to_csv_options(@dialect)
end

#validateObject



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

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

  if @source.class == String
    validate_url
  else
    
    validate_stream
  end
  finish
end

#validate_encodingObject



310
311
312
313
314
315
316
317
318
319
# File 'lib/csvlint/validate.rb', line 310

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

#validate_header(header) ⇒ Object



352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'lib/csvlint/validate.rb', line 352

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
  return valid?
end

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



159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/csvlint/validate.rb', line 159

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) unless @lambda.nil?
rescue ArgumentError => ae
  build_errors(:invalid_encoding, :structure, @current_line, nil, index) unless @reported_invalid_encoding
  @reported_invalid_encoding = true
end

#validate_metadataObject



224
225
226
227
228
229
230
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
# File 'lib/csvlint/validate.rb', line 224

def 
  assumed_header = !@supplied_dialect
  unless @headers.empty?
    if @headers["content-type"] =~ /text\/csv/
      @csv_header = @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 = @headers["link"].split(",") rescue nil
  @link_headers.each do |link_header|
    match = LINK_HEADER_REGEXP.match(link_header)
    uri = match["uri"].gsub(/(^\<|\>$)/, "") rescue nil
    rel = match["rel-relationship"].gsub(/(^\"|\"$)/, "") rescue nil
    param = match["param"]
    param_value = match["param-value"].gsub(/(^\"|\"$)/, "") rescue nil
    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_json(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 if @link_headers
end

#validate_streamObject



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

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



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/csvlint/validate.rb', line 115

def validate_url
  @current_line = 1
  request = Typhoeus::Request.new(@source, followlocation: true)
  request.on_headers do |response|
    @headers = response.headers || {}
    @content_type = response.headers["content-type"] rescue nil
    @response_code = response.code
    return build_errors(:not_found) if response.code == 404
    
  end
  request.on_body do |chunk|
    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