Class: Csvlint::Validator

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

Constant Summary collapse

ERROR_MATCHERS =
{
  "Missing or stray quote" => :stray_quote,
  "Illegal quoting" => :whitespace,
  "Unclosed quoted field" => :unclosed_quote,
}

Constants included from Types

Types::SIMPLE_FORMATS, Types::TYPE_VALIDATIONS

Constants included from ErrorCollector

ErrorCollector::MESSAGE_LEVELS

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Types

date_format, included

Methods included from ErrorCollector

#build_message, #reset, #valid?

Constructor Details

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

Returns a new instance of Validator.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/csvlint/validate.rb', line 18

def initialize(source, dialect = nil, schema = nil)      
  @source = source
  @formats = []
  @schema = schema
  
  @assumed_header = true
  @supplied_dialect = dialect != nil
  
  if dialect
    @assumed_header = false
  end
  
  @dialect = dialect_defaults = {
    "header" => true,
    "delimiter" => ",",
    "skipInitialSpace" => true,
    "lineTerminator" => :auto,
    "quoteChar" => '"'
  }.merge(dialect || {})
        
  @csv_header = @dialect["header"]
    
  @csv_options = dialect_to_csv_options(@dialect)
  @extension = parse_extension(source)
  reset
  validate
end

Instance Attribute Details

#content_typeObject (readonly)

Returns the value of attribute content_type.



10
11
12
# File 'lib/csvlint/validate.rb', line 10

def content_type
  @content_type
end

#csv_headerObject (readonly)

Returns the value of attribute csv_header.



10
11
12
# File 'lib/csvlint/validate.rb', line 10

def csv_header
  @csv_header
end

#dataObject (readonly)

Returns the value of attribute data.



10
11
12
# File 'lib/csvlint/validate.rb', line 10

def data
  @data
end

#dialectObject (readonly)

Returns the value of attribute dialect.



10
11
12
# File 'lib/csvlint/validate.rb', line 10

def dialect
  @dialect
end

#encodingObject (readonly)

Returns the value of attribute encoding.



10
11
12
# File 'lib/csvlint/validate.rb', line 10

def encoding
  @encoding
end

#extensionObject (readonly)

Returns the value of attribute extension.



10
11
12
# File 'lib/csvlint/validate.rb', line 10

def extension
  @extension
end

#headersObject (readonly)

Returns the value of attribute headers.



10
11
12
# File 'lib/csvlint/validate.rb', line 10

def headers
  @headers
end

#line_breaksObject (readonly)

Returns the value of attribute line_breaks.



10
11
12
# File 'lib/csvlint/validate.rb', line 10

def line_breaks
  @line_breaks
end

#schemaObject (readonly)

Returns the value of attribute schema.



10
11
12
# File 'lib/csvlint/validate.rb', line 10

def schema
  @schema
end

Instance Method Details

#build_formats(row, line) ⇒ Object



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/csvlint/validate.rb', line 196

def build_formats(row, line) 
  row.each_with_index do |col, i|
    next if col.blank?
    @formats[i] ||= []
    
    SIMPLE_FORMATS.each do |type, lambda|
      begin
        lambda.call(col, {})
        @format = type
      rescue => e
        nil
      end
    end
    
    @formats[i] << @format
  end
end

#check_consistencyObject



214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/csvlint/validate.rb', line 214

def check_consistency
  percentages = []
            
  formats = SIMPLE_FORMATS.map {|type, lambda| type }
        
  formats.each do |type, regex|
    @formats.count.times do |i|
      percentages[i] ||= {}
      unless @formats[i].nil?
        percentages[i][type] = @formats[i].grep(/^#{type}$/).count.to_f / @formats[i].count.to_f
      end
    end
  end
        
  percentages.each_with_index do |col, i|
    next if col.values.blank?
    build_warnings(:inconsistent_values, :schema, nil, i+1) if col.values.max < 0.9
  end
end

#dialect_to_csv_options(dialect) ⇒ Object



184
185
186
187
188
189
190
191
192
193
194
# File 'lib/csvlint/validate.rb', line 184

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



178
179
180
181
182
# File 'lib/csvlint/validate.rb', line 178

def fetch_error(error)
  e = error.message.match(/^([a-z ]+) (i|o)n line ([0-9]+)\.?$/i)
  message = e[1] rescue nil
  ERROR_MATCHERS.fetch(message, :unknown_error)
end

#header?Boolean

Returns:

  • (Boolean)


174
175
176
# File 'lib/csvlint/validate.rb', line 174

def header?
  return @csv_header
end

#parse_csv(io) ⇒ Object



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
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
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/csvlint/validate.rb', line 92

def parse_csv(io)
  @expected_columns = 0
  current_line = 0
  reported_invalid_encoding = false
  @col_counts = []
  
  @csv_options[:encoding] = @encoding  
  
  begin
    wrapper = WrappedIO.new( io )
    csv = CSV.new( wrapper, @csv_options )
    @data = []
    @line_breaks = csv.row_sep
    if @line_breaks != "\r\n"
      build_info_messages(:nonrfc_line_breaks, :structure)
    end
    row = nil
    loop do
     current_line = current_line + 1
     begin
       row = csv.shift
       @data << row
       wrapper.finished
       if row             
         if header? && current_line == 1
           row = row.reject {|r| r.blank? }
           validate_header(row)
           @col_counts << row.count
         else               
           build_formats(row, current_line)
           @col_counts << row.reject {|r| r.blank? }.count
           @expected_columns = row.count unless @expected_columns != 0
           
           build_errors(:blank_rows, :structure, current_line, nil, wrapper.line) if row.reject{ |c| c.nil? || c.empty? }.count == 0
           
           if @schema
             @schema.validate_row(row, current_line)
             @errors += @schema.errors
             @warnings += @schema.warnings
           else
             build_errors(:ragged_rows, :structure, current_line, nil, wrapper.line) if !row.empty? && row.count != @expected_columns
           end
           
         end
       else             
         break
       end         
     rescue CSV::MalformedCSVError => e
       wrapper.finished
       type = fetch_error(e)
       if type == :stray_quote && !wrapper.line.match(csv.row_sep)
         build_errors(:line_breaks, :structure)
       else
         build_errors(type, :structure, current_line, nil, wrapper.line)
       end
     end
  end
  rescue ArgumentError => ae
    wrapper.finished           
    build_errors(:invalid_encoding, :structure, current_line, wrapper.line) unless reported_invalid_encoding
    reported_invalid_encoding = true
  end
end

#validateObject



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/csvlint/validate.rb', line 46

def validate
  single_col = false   
  io = nil   
  begin
    io = @source.respond_to?(:gets) ? @source : open(@source, :allow_redirections=>:all)
    (io)
    parse_csv(io)
    unless @col_counts.inject(:+).nil?
      build_warnings(:title_row, :structure) if @col_counts.first < (@col_counts.inject(:+) / @col_counts.count)
    end
    build_warnings(:check_options, :structure) if @expected_columns == 1        
    check_consistency      
  rescue OpenURI::HTTPError, Errno::ENOENT
    build_errors(:not_found)
  ensure
    io.close if io && io.respond_to?(:close)
  end
end

#validate_header(header) ⇒ Object



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

def validate_header(header)
  names = Set.new
  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)
    @errors += @schema.errors
    @warnings += @schema.warnings
  end
  return valid?
end

#validate_metadata(io) ⇒ Object



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
90
# File 'lib/csvlint/validate.rb', line 65

def (io)
  @encoding = io.charset rescue nil
  @content_type = io.content_type rescue nil
  @headers = io.meta rescue nil    
  if @headers
    if @headers["content-type"] =~ /header=(present|absent)/
      @csv_header = true if $1 == "present"
      @csv_header = false if $1 == "absent"
      @assumed_header = false
    end
    if @headers["content-type"] !~ /charset=/
      build_warnings(:no_encoding, :context) 
    else
      build_warnings(:encoding, :context) if @encoding != "utf-8"
    end
    build_warnings(:no_content_type, :context) if @content_type == nil
    build_warnings(:excel, :context) if @content_type == nil && @extension =~ /.xls(x)?/
    build_errors(:wrong_content_type, :context) unless (@content_type && @content_type =~ /text\/csv/)
    
    if @assumed_header && !@supplied_dialect && (@content_type == nil || @headers["content-type"] !~ /header=(present|absent)/ )
      build_errors(:undeclared_header, :structure)
    end
    
  end
  build_info_messages(:assumed_header, :structure) if @assumed_header
end