curtilage 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +75 -0
  3. data/README.md +76 -22
  4. data/SECURITY.md +18 -3
  5. data/docs/reference.md +221 -27
  6. data/docs/schema/site-v1.json +362 -0
  7. data/docs/security.md +69 -0
  8. data/exe/curtilage +375 -82
  9. data/lib/curtilage/audit.rb +5 -5
  10. data/lib/curtilage/auto_data.rb +61 -11
  11. data/lib/curtilage/batch.rb +116 -0
  12. data/lib/curtilage/build.rb +117 -63
  13. data/lib/curtilage/candidates.rb +67 -0
  14. data/lib/curtilage/catalogue.rb +44 -16
  15. data/lib/curtilage/confidence.rb +55 -0
  16. data/lib/curtilage/config.rb +24 -2
  17. data/lib/curtilage/corrections.rb +57 -0
  18. data/lib/curtilage/diff.rb +90 -0
  19. data/lib/curtilage/doctor.rb +92 -0
  20. data/lib/curtilage/download.rb +42 -16
  21. data/lib/curtilage/duckdb.rb +170 -6
  22. data/lib/curtilage/error.rb +3 -0
  23. data/lib/curtilage/features.rb +54 -5
  24. data/lib/curtilage/formats.rb +271 -36
  25. data/lib/curtilage/generator.rb +145 -166
  26. data/lib/curtilage/generator_details.rb +22 -14
  27. data/lib/curtilage/generator_lot.rb +56 -32
  28. data/lib/curtilage/generator_pin.rb +74 -0
  29. data/lib/curtilage/generator_roads.rb +109 -0
  30. data/lib/curtilage/generator_steps.rb +54 -0
  31. data/lib/curtilage/generator_store.rb +18 -4
  32. data/lib/curtilage/generator_zones.rb +93 -0
  33. data/lib/curtilage/geometry.rb +48 -52
  34. data/lib/curtilage/lookup.rb +41 -21
  35. data/lib/curtilage/overture.rb +137 -17
  36. data/lib/curtilage/preview.rb +55 -16
  37. data/lib/curtilage/profiles.rb +62 -0
  38. data/lib/curtilage/regions.rb +4 -8
  39. data/lib/curtilage/result.rb +72 -7
  40. data/lib/curtilage/validation.rb +73 -9
  41. data/lib/curtilage/version.rb +1 -1
  42. data/lib/curtilage/zip_range.rb +81 -16
  43. data/lib/curtilage.rb +155 -17
  44. data/sql/build_from_shapefiles.sql +1 -1
  45. metadata +15 -2
@@ -1,10 +1,12 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "cgi/escape"
3
4
  require "json"
4
5
  require "strscan"
5
6
 
6
7
  module Curtilage
7
- # Pins in from CSV or GeoJSON; results out as GeoJSON, CSV or KML. Used by
8
+ # Pins in from CSV, GeoJSON or NDJSON; results out as GeoJSON, NDJSON, CSV
9
+ # or KML. Used by
8
10
  # the command line, and handy from Ruby:
9
11
  #
10
12
  # sites = Curtilage::Formats.read_pins("sites.csv")
@@ -14,35 +16,45 @@ module Curtilage
14
16
  # Plain Ruby (no csv gem): CSV is read and written per RFC 4180 (quoted
15
17
  # fields, doubled quotes, commas and newlines inside quotes).
16
18
  module Formats
17
- INPUTS = %i[csv geojson].freeze
18
- OUTPUTS = %i[geojson csv kml].freeze
19
+ INPUTS = %i[csv geojson ndjson].freeze
20
+ OUTPUTS = %i[geojson ndjson csv kml].freeze
19
21
  LNG_COLUMNS = %w[lng lon long longitude].freeze
20
22
  LAT_COLUMNS = %w[lat latitude].freeze
21
23
  ID_COLUMNS = %w[id site_id name].freeze
22
24
  # Inputs are untrusted: cap what a file can ask for.
23
25
  MAX_PINS = 100_000
24
26
  MAX_BYTES = 50 * 1024 * 1024
27
+ MAX_FIELD_CHARS = 10_000
28
+ MAX_COLUMNS = 1_000
29
+ # Rings read back from result files: generated ones have at most 200.
30
+ MAX_RESULT_VERTICES = 1_000
25
31
 
26
32
  CSV_COLUMNS = %w[id lng lat ok problem method flags errors building building_area_m2 parking_area_m2
27
- parking_spaces_estimate frontage_m premises_area_m2 premises_wkt store_wkt].freeze
33
+ parking_spaces_estimate frontage_m premises_area_m2 premises_wkt store_wkt attribution
34
+ gem_version data_source data_release features_sha256 confidence approach_wkt pickup_wkt
35
+ staging_wkt pin_quality candidates].freeze
28
36
 
29
37
  module_function
30
38
 
31
- # The format a path's extension names (.csv, .geojson/.json, .kml), or nil.
39
+ # The format a path's extension names (.csv, .geojson/.json,
40
+ # .ndjson/.jsonl, .kml), or nil.
32
41
  def format_of(path)
33
42
  case File.extname(path.to_s).downcase
34
43
  when ".csv" then :csv
35
44
  when ".geojson", ".json" then :geojson
45
+ when ".ndjson", ".jsonl" then :ndjson
36
46
  when ".kml" then :kml
37
47
  end
38
48
  end
39
49
 
40
50
  # [{ id:, pin: [lng, lat] }, ...] from a CSV (a header row with lng/lon/
41
- # longitude and lat/latitude columns, and optionally id/site_id/name) or
51
+ # longitude and lat/latitude columns, and optionally id/site_id/name),
42
52
  # GeoJSON (Point features; id from the feature's id or properties id or
43
- # name). Rows without an id are numbered from 1.
53
+ # name) or NDJSON (one site per line, see ndjson_pins). Rows without an
54
+ # id are numbered from 1.
44
55
  def read_pins(path, format: nil)
45
- format ||= format_of(path) or raise ArgumentError, "can't tell the format of #{path}: use .csv or .geojson"
56
+ format ||= format_of(path) or
57
+ raise ArgumentError, "can't tell the format of #{path}: use .csv, .geojson or .ndjson"
46
58
  raise ArgumentError, "#{path} is over #{MAX_BYTES / 1024 / 1024} MB" if File.size(path) > MAX_BYTES
47
59
 
48
60
  text = File.read(path, encoding: "bom|utf-8")
@@ -50,14 +62,31 @@ module Curtilage
50
62
  end
51
63
 
52
64
  def parse_pins(text, format)
65
+ text = checked_text(text)
53
66
  sites = case format
54
67
  when :csv then csv_pins(text)
55
68
  when :geojson then geojson_pins(text)
69
+ when :ndjson then ndjson_pins(text)
56
70
  else raise ArgumentError, "unknown input format #{format.inspect} (have: #{INPUTS.join(", ")})"
57
71
  end
58
72
  raise ArgumentError, "more than #{MAX_PINS} pins" if sites.size > MAX_PINS
59
73
 
60
- sites.each.with_index(1) { |site, i| site[:id] ||= i.to_s }
74
+ sites.each.with_index(1) do |site, i|
75
+ site[:id] ||= i.to_s
76
+ raise ArgumentError, "#{site[:id]}: a pin is LNG,LAT (longitude first)" unless pin?(site[:pin])
77
+ end
78
+ end
79
+
80
+ # The text as valid UTF-8 without a byte-order mark, refused up front if
81
+ # it's too big, isn't UTF-8 or holds NUL bytes (a binary file, usually).
82
+ def checked_text(text)
83
+ raise ArgumentError, "the input is over #{MAX_BYTES / 1024 / 1024} MB" if text.bytesize > MAX_BYTES
84
+
85
+ text = text.dup.force_encoding(Encoding::UTF_8) unless text.encoding == Encoding::UTF_8
86
+ raise ArgumentError, "the input isn't valid UTF-8" unless text.valid_encoding?
87
+ raise ArgumentError, "the input contains a NUL byte: is it a text file?" if text.include?("\0")
88
+
89
+ text.delete_prefix("\uFEFF")
61
90
  end
62
91
 
63
92
  def csv_pins(text)
@@ -77,63 +106,236 @@ module Curtilage
77
106
  doc = JSON.parse(text, max_nesting: 20)
78
107
  features = doc.is_a?(Hash) && doc["type"] == "FeatureCollection" ? doc["features"] : [doc]
79
108
  raise ArgumentError, "expected GeoJSON Point features" unless features.is_a?(Array)
109
+ raise ArgumentError, "more than #{MAX_PINS} pins" if features.size > MAX_PINS
80
110
 
81
111
  features.each_with_index.map { |f, i| geojson_pin(f, "feature #{i + 1}") }
82
112
  rescue JSON::ParserError => e
83
113
  raise ArgumentError, "not valid GeoJSON: #{e.message[0, 200]}"
84
114
  end
85
115
 
86
- # The results as text in format (:geojson, :csv or :kml). ids: one per
87
- # result (default 1, 2, ...). store: include the store zones.
116
+ # One site per line: a GeoJSON Point Feature, {"id", "pin": [lng, lat]}
117
+ # or {"id", "lng", "lat"} (any of the CSV column names). Blank lines are
118
+ # skipped.
119
+ def ndjson_pins(text)
120
+ lines = text.each_line.with_index(1).reject { |line, _| line.strip.empty? }
121
+ raise ArgumentError, "more than #{MAX_PINS} pins" if lines.size > MAX_PINS
122
+
123
+ lines.map { |line, n| ndjson_pin(line, "line #{n}") }
124
+ end
125
+
126
+ def ndjson_pin(line, where)
127
+ row = JSON.parse(line, max_nesting: 20)
128
+ raise ArgumentError, "#{where} isn't a JSON object" unless row.is_a?(Hash)
129
+ return geojson_pin(row, where) if row["type"] == "Feature"
130
+
131
+ coords = row["pin"] || [row.values_at(*LNG_COLUMNS).compact.first, row.values_at(*LAT_COLUMNS).compact.first]
132
+ unless coords.is_a?(Array) && coords.size == 2 && coords.none?(&:nil?)
133
+ raise ArgumentError, "#{where} needs pin: [lng, lat] or lng and lat"
134
+ end
135
+
136
+ id = row["id"] || row["site_id"] || row["name"]
137
+ { id: present(id), pin: coords.map { |v| number(v, where) } }
138
+ rescue JSON::ParserError => e
139
+ raise ArgumentError, "#{where} isn't valid JSON: #{e.message[0, 200]}"
140
+ end
141
+
142
+ # Premises read back from a GeoJSON or NDJSON file of results (this
143
+ # gem's output, edited or not, or any polygons with an id): { id =>
144
+ # { ring:, store_ring:, properties: } }. A feature's id is its
145
+ # properties.id or its id; properties.role picks premises (the default)
146
+ # or store, and other zones are skipped. ring is nil where the file has
147
+ # no premises. Rings aren't validated here (Corrections and Diff do).
148
+ def read_results(path, format: nil)
149
+ format ||= format_of(path)
150
+ raise ArgumentError, "results are .geojson or .ndjson: #{path}" unless %i[geojson ndjson].include?(format)
151
+ raise ArgumentError, "#{path} is over #{MAX_BYTES / 1024 / 1024} MB" if File.size(path) > MAX_BYTES
152
+
153
+ parse_results(File.read(path, encoding: "bom|utf-8"), format)
154
+ rescue SystemCallError => e
155
+ raise ArgumentError, "can't read #{path}: #{e.message}"
156
+ end
157
+
158
+ def parse_results(text, format)
159
+ text = checked_text(text)
160
+ features = if format == :ndjson
161
+ text.each_line.reject { |l| l.strip.empty? }.map { |l| JSON.parse(l, max_nesting: 30) }
162
+ else
163
+ doc = JSON.parse(text, max_nesting: 30)
164
+ doc.is_a?(Hash) && doc["type"] == "FeatureCollection" ? doc["features"] : [doc]
165
+ end
166
+ raise ArgumentError, "expected GeoJSON Features" unless features.is_a?(Array)
167
+ raise ArgumentError, "more than #{MAX_PINS * 10} features" if features.size > MAX_PINS * 10
168
+
169
+ features.each_with_index.with_object({}) { |(f, i), out| add_result(out, f, "feature #{i + 1}") }
170
+ rescue JSON::ParserError => e
171
+ raise ArgumentError, "not valid GeoJSON: #{e.message[0, 200]}"
172
+ end
173
+
174
+ def add_result(out, feature, where)
175
+ raise ArgumentError, "#{where} isn't a Feature" unless feature.is_a?(Hash) && feature["type"] == "Feature"
176
+
177
+ props = feature["properties"].is_a?(Hash) ? feature["properties"] : {}
178
+ id = present(props["id"] || feature["id"]) or raise ArgumentError, "#{where} has no id"
179
+ entry = out[id] ||= { ring: nil, store_ring: nil, properties: {} }
180
+ case props.fetch("role", "premises")
181
+ when "premises"
182
+ entry.merge!(ring: polygon_ring(feature["geometry"], where), properties: props)
183
+ entry[:store_ring] ||= polygon_ring(props["store"], where) if props["store"]
184
+ when "store" then entry[:store_ring] = polygon_ring(feature["geometry"], where)
185
+ end
186
+ end
187
+
188
+ def polygon_ring(geometry, where)
189
+ return nil if geometry.nil?
190
+ unless geometry.is_a?(Hash) && geometry["type"] == "Polygon" && geometry["coordinates"].is_a?(Array)
191
+ raise ArgumentError, "#{where} isn't a Polygon"
192
+ end
193
+
194
+ ring = geometry["coordinates"][0]
195
+ unless ring.is_a?(Array) && ring.size <= MAX_RESULT_VERTICES
196
+ raise ArgumentError, "#{where} has more than #{MAX_RESULT_VERTICES} vertices"
197
+ end
198
+
199
+ ring
200
+ end
201
+
202
+ PLACE_COLUMNS = %w[id lng lat name brand category place_confidence place_sources place_licences].freeze
203
+
204
+ # Places (Curtilage.places) as pins to generate from, in :csv, :ndjson
205
+ # or :geojson: id, lng and lat, which read_pins reads back, plus the
206
+ # place's name, brand, category, Overture confidence, sources and
207
+ # licences.
208
+ def write_places(places, format)
209
+ rows = places.map do |p|
210
+ [p[:id], *p[:pin], p[:name], p[:brand], p[:category], p[:confidence], p[:sources].join(";"),
211
+ p[:licences].join(";")]
212
+ end
213
+ case format.to_sym
214
+ when :csv then csv_text([PLACE_COLUMNS] + rows)
215
+ when :ndjson then rows.map { |row| "#{JSON.generate(PLACE_COLUMNS.zip(row).to_h)}\n" }.join
216
+ when :geojson then JSON.pretty_generate(places_geojson(places, rows))
217
+ else raise ArgumentError, "unknown places format #{format.inspect} (have: csv, ndjson, geojson)"
218
+ end
219
+ end
220
+
221
+ def places_geojson(places, rows)
222
+ features = places.zip(rows).map do |place, row|
223
+ { type: "Feature", id: place[:id], geometry: { type: "Point", coordinates: place[:pin] },
224
+ properties: PLACE_COLUMNS.zip(row).to_h.except("lng", "lat") }
225
+ end
226
+ { type: "FeatureCollection", features: features }
227
+ end
228
+
229
+ # The results as text in format (:geojson, :ndjson, :csv or :kml). ids:
230
+ # one per result (default 1, 2, ...). store: include the store zones.
88
231
  def write(results, format, ids: nil, store: true)
89
232
  ids ||= (1..results.size).map(&:to_s)
90
233
  case format.to_sym
91
234
  when :geojson then JSON.pretty_generate(geojson(results, ids, store))
235
+ when :ndjson then ndjson(results, ids, store)
92
236
  when :csv then csv(results, ids)
93
237
  when :kml then kml(results, ids, store)
94
238
  else raise ArgumentError, "unknown output format #{format.inspect} (have: #{OUTPUTS.join(", ")})"
95
239
  end
96
240
  end
97
241
 
98
- # One FeatureCollection: each result's premises (and store zone), with
99
- # its id in properties.
242
+ # One FeatureCollection: each result's premises (and store zone, and
243
+ # any zones asked for), with its id in properties.
100
244
  def geojson(results, ids, store)
101
245
  features = results.zip(ids).flat_map do |result, id|
102
246
  list = result.geojson_features(properties: { id: id })
103
- store ? list : list.first(1)
247
+ store ? list : list.reject { |f| f[:properties][:role] == "store" }
104
248
  end
105
249
  { type: "FeatureCollection", features: features }
106
250
  end
107
251
 
252
+ # One GeoJSON Feature per line (docs/schema/site-v1.json): the premises,
253
+ # with the store zone's geometry in properties.store.
254
+ def ndjson(results, ids, store)
255
+ results.zip(ids).map do |result, id|
256
+ premises, store_zone = result.geojson_features(properties: { id: id })
257
+ premises[:properties][:store] = store_zone[:geometry] if store
258
+ premises[:properties][:approach] = Result.polygon(result.approach_ring) if result.approach_ring
259
+ premises[:properties][:pickup] = Result.polygon(result.pickup_ring) if result.pickup_ring
260
+ premises[:properties][:staging] = Result.point(result.staging_point) if result.staging_point
261
+ premises[:properties][:candidates] = result.candidate_summaries if result.candidates
262
+ "#{JSON.generate(premises)}\n"
263
+ end.join
264
+ end
265
+
108
266
  def csv(results, ids)
109
- rows = results.zip(ids).map { |result, id| csv_row(result, id) }
110
- ([CSV_COLUMNS] + rows).map { |row| row.map { |v| csv_field(v) }.join(",") }.join("\r\n") << "\r\n"
267
+ csv_text([CSV_COLUMNS] + results.zip(ids).map { |result, id| csv_row(result, id) })
111
268
  end
112
269
 
270
+ # Every cell guarded (csv_field), CRLF line ends.
271
+ def csv_text(rows) = rows.map { |row| row.map { |v| csv_field(v) }.join(",") }.join("\r\n") << "\r\n"
272
+
113
273
  def csv_row(result, id)
114
274
  d = result.details || {}
115
275
  [id, *result.pin, result.ok?, result.problem, result.method_name, result.flags.join(";"),
116
276
  result.validation.errors.join(";"), result.building, d.dig(:building, :area_m2), d[:parking_area_m2],
117
277
  d[:parking_spaces_estimate],
118
- d[:frontage_m], result.validation.metrics[:area_m2]&.round, result.to_wkt, result.store_wkt]
278
+ d[:frontage_m], result.validation.metrics[:area_m2]&.round, result.to_wkt, result.store_wkt,
279
+ credits(result).join("; "), *provenance_columns(result), *later_columns(result)]
280
+ end
281
+
282
+ # Columns added after the first release, in order.
283
+ def later_columns(result)
284
+ [result.confidence, result.approach_wkt, result.pickup_wkt, result.staging_wkt,
285
+ result.pin_quality&.dig(:quality), result.candidates&.size]
286
+ end
287
+
288
+ # gem_version, data_source, data_release, features_sha256 (the full
289
+ # record, options included, is in the GeoJSON).
290
+ def provenance_columns(result)
291
+ prov = result.provenance || {}
292
+ [prov[:gem_version], prov.dig(:data, :source), release(prov[:data]), prov[:features_sha256]]
293
+ end
294
+
295
+ # The Overture release, or the Geofabrik extract date(s).
296
+ def release(data)
297
+ return nil unless data
298
+
299
+ data[:release] || data[:regions]&.flat_map { |r| r[:extract_dates] || [] }&.uniq&.join(";")
119
300
  end
120
301
 
121
302
  def kml(results, ids, store)
122
- marks = results.zip(ids).flat_map do |result, id|
123
- [placemark("#{id} premises", result.ring, kml_description(result), "premises"),
124
- (placemark("#{id} store", result.store_ring, nil, "store") if store)].compact
125
- end
303
+ marks = results.zip(ids).flat_map { |result, id| kml_marks(result, id, store) }
126
304
  <<~KML
127
305
  <?xml version="1.0" encoding="UTF-8"?>
128
306
  <kml xmlns="http://www.opengis.net/kml/2.2"><Document>
129
307
  <name>curtilage</name>
308
+ <description>#{xml("Map data: #{results.flat_map { |r| credits(r) }.uniq.join("; ")}")}</description>
130
309
  <Style id="premises"><LineStyle><color>ff4a9a1a</color><width>2</width></LineStyle><PolyStyle><color>334a9a1a</color></PolyStyle></Style>
131
310
  <Style id="store"><LineStyle><color>ff111111</color><width>2</width></LineStyle><PolyStyle><fill>0</fill></PolyStyle></Style>
311
+ <Style id="approach"><LineStyle><color>ffc06515</color><width>1</width></LineStyle><PolyStyle><fill>0</fill></PolyStyle></Style>
312
+ <Style id="candidate"><LineStyle><color>ff2090ff</color><width>1</width></LineStyle><PolyStyle><fill>0</fill></PolyStyle></Style>
313
+ <Style id="pickup"><LineStyle><color>ff0080ff</color><width>2</width></LineStyle><PolyStyle><color>440080ff</color></PolyStyle></Style>
132
314
  #{marks.join("\n")}
133
315
  </Document></kml>
134
316
  KML
135
317
  end
136
318
 
319
+ # Every placemark for one result: its polygons, then its points.
320
+ def kml_marks(result, id, store)
321
+ polygons = [placemark("#{id} premises", result.ring, kml_description(result), "premises"),
322
+ (placemark("#{id} store", result.store_ring, nil, "store") if store),
323
+ placemark("#{id} approach", result.approach_ring, nil, "approach"),
324
+ placemark("#{id} pickup (estimated)", result.pickup_ring, nil, "pickup")]
325
+ entrances = result.entrances.map do |e|
326
+ point_mark("#{id} entrance from #{e[:street] || e[:street_class]}", e[:point])
327
+ end
328
+ points = [point_mark("#{id} staging (estimated)", result.staging_point)] + entrances
329
+ (polygons + candidate_marks(result, id) + points).compact
330
+ end
331
+
332
+ def candidate_marks(result, id)
333
+ result.candidate_summaries.map do |c|
334
+ placemark("#{id} candidate #{c[:rank]}", c[:geometry][:coordinates][0],
335
+ "confidence #{c[:confidence]}; flags: #{c[:flags].join(", ")}", "candidate")
336
+ end
337
+ end
338
+
137
339
  def placemark(name, ring, description, style)
138
340
  return nil unless ring
139
341
 
@@ -144,49 +346,74 @@ module Curtilage
144
346
  "</Polygon></Placemark>"
145
347
  end
146
348
 
349
+ def point_mark(name, lnglat)
350
+ lnglat && "<Placemark><name>#{xml(name)}</name><Point><coordinates>#{lnglat.join(",")},0</coordinates></Point>" \
351
+ "</Placemark>"
352
+ end
353
+
147
354
  def kml_description(result)
148
- parts = [result.problem || "ok"]
355
+ parts = [result.problem || "ok", "confidence #{result.confidence}"]
149
356
  parts << "flags: #{result.flags.join(", ")}" if result.flags.any?
150
- parts << (result.attribution || Result::OSM_ATTRIBUTION).join("; ")
357
+ parts << credits(result).join("; ")
358
+ gem, source, release = provenance_columns(result)
359
+ parts << "curtilage #{gem}; data: #{[source, release].compact.join(" ")}" if gem
151
360
  parts.join("\n")
152
361
  end
153
362
 
154
- def xml(text)
155
- text.to_s.gsub("&", "&amp;").gsub("<", "&lt;").gsub(">", "&gt;").gsub('"', "&quot;")
156
- end
363
+ def xml(text) = CGI.escapeHTML(text.to_s)
157
364
 
158
- # A field that a spreadsheet would run as a formula (=, +, -, @) gets a
159
- # leading quote, unless it's a number.
365
+ # What to credit wherever this result is shown.
366
+ def credits(result) = result.attribution || Result::OSM_ATTRIBUTION
367
+
368
+ # What a spreadsheet may run as a formula: =, +, -, @, | (DDE) or %, or
369
+ # their full-width forms, after any leading whitespace; or a leading tab
370
+ # or carriage return.
371
+ FORMULA = /\A(?:[\s\u3000]*[=+\-@|%\uFF1D\uFF0B\uFF0D\uFF20\uFF5C\uFF05]|[\t\r])/
372
+ PLAIN_NUMBER = /\A[+-]?\d+(\.\d+)?\z/
373
+
374
+ # Every CSV cell goes through here: one a spreadsheet would run as a
375
+ # formula gets a leading quote, unless it's a plain number.
160
376
  def csv_field(value)
161
377
  text = value.to_s
162
- text = "'#{text}" if text.match?(/\A[=+\-@\t\r]/) && !text.match?(/\A[+-]?\d+(\.\d+)?\z/)
378
+ text = "'#{text}" if text.match?(FORMULA) && !text.match?(PLAIN_NUMBER)
163
379
  text.match?(/[",\r\n]/) ? "\"#{text.gsub('"', '""')}\"" : text
164
380
  end
165
381
 
166
382
  # RFC 4180: rows of fields; quoted fields may hold commas, quotes ("")
167
- # and newlines. Blank lines are skipped.
168
- def parse_csv(text)
383
+ # and newlines. Blank lines are skipped. Rows, columns and field length
384
+ # are capped as it reads, so an oversized file fails early.
385
+ def parse_csv(text, max_rows: MAX_PINS + 1)
169
386
  scanner = StringScanner.new(text)
170
387
  rows = []
171
388
  until scanner.eos?
172
389
  row = [csv_cell(scanner)]
173
- row << csv_cell(scanner) while scanner.scan(",")
390
+ row << csv_cell(scanner) while scanner.scan(",") && row.size <= MAX_COLUMNS
391
+ raise ArgumentError, "line #{rows.size + 1} has more than #{MAX_COLUMNS} columns" if row.size > MAX_COLUMNS
392
+
174
393
  scanner.scan(/\r\n|\n|\r/)
175
394
  rows << row unless row == [""]
395
+ raise ArgumentError, "more than #{max_rows - 1} rows" if rows.size > max_rows
176
396
  end
177
397
  rows
178
398
  end
179
399
 
180
400
  def csv_cell(scanner)
181
- return scanner.scan(/[^,\r\n]*/) unless scanner.scan('"')
401
+ value = if scanner.scan('"')
402
+ quoted = scanner.scan(/(?:[^"]|"")*/).gsub('""', '"')
403
+ scanner.scan('"') or raise ArgumentError, "a quoted CSV field is never closed"
404
+ quoted
405
+ else
406
+ scanner.scan(/[^,\r\n]*/)
407
+ end
408
+ raise ArgumentError, "a CSV field is over #{MAX_FIELD_CHARS} characters" if value.size > MAX_FIELD_CHARS
182
409
 
183
- value = scanner.scan(/(?:[^"]|"")*/).gsub('""', '"')
184
- scanner.scan('"') or raise ArgumentError, "a quoted CSV field is never closed"
185
410
  value
186
411
  end
187
412
 
188
413
  def present(value)
189
414
  text = value.to_s.strip
415
+ raise ArgumentError, "an id is over #{MAX_FIELD_CHARS} characters" if text.size > MAX_FIELD_CHARS
416
+
190
417
  text.empty? ? nil : text
191
418
  end
192
419
 
@@ -205,9 +432,17 @@ module Curtilage
205
432
  end
206
433
 
207
434
  def number(value, where)
208
- Float(value.to_s.strip)
435
+ Validation.coordinate(value, [value])
209
436
  rescue ArgumentError
210
437
  raise ArgumentError, "#{where}: #{value.inspect} isn't a number"
211
438
  end
439
+
440
+ # A pin from "LNG,LAT" text (the command line's --pin).
441
+ def pin_from_text(text, where = "--pin #{text}")
442
+ parts = text.to_s.split(",")
443
+ raise ArgumentError, "#{where}: a pin is LNG,LAT" unless parts.size == 2
444
+
445
+ parts.map { |v| number(v, where) }
446
+ end
212
447
  end
213
448
  end