iostreams 2.0.0 → 2.2.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 (85) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +5 -22
  3. data/Rakefile +45 -0
  4. data/docs/CLAUDE.md +9 -0
  5. data/docs/config.md +161 -0
  6. data/docs/copy_files.md +93 -0
  7. data/docs/extensions.md +125 -0
  8. data/docs/formats.md +816 -0
  9. data/docs/index.md +388 -0
  10. data/docs/path.md +668 -0
  11. data/docs/pgp.md +436 -0
  12. data/docs/streams.md +382 -0
  13. data/docs/tutorial.md +495 -0
  14. data/docs/upgrading.md +664 -0
  15. data/lib/io_streams/builder/deprecations.rb +250 -0
  16. data/lib/io_streams/builder.rb +316 -39
  17. data/lib/io_streams/bzip2/reader.rb +41 -2
  18. data/lib/io_streams/bzip2/writer.rb +35 -2
  19. data/lib/io_streams/deprecation/methods.rb +51 -0
  20. data/lib/io_streams/deprecation/once.rb +27 -0
  21. data/lib/io_streams/deprecation/option_names.rb +26 -0
  22. data/lib/io_streams/deprecation/words.rb +42 -0
  23. data/lib/io_streams/deprecation.rb +259 -0
  24. data/lib/io_streams/encode/reader.rb +58 -3
  25. data/lib/io_streams/encode/writer.rb +23 -2
  26. data/lib/io_streams/encode.rb +99 -0
  27. data/lib/io_streams/errors.rb +55 -0
  28. data/lib/io_streams/gzip/reader.rb +15 -0
  29. data/lib/io_streams/gzip/writer.rb +11 -2
  30. data/lib/io_streams/io_streams.rb +468 -28
  31. data/lib/io_streams/line/reader.rb +9 -3
  32. data/lib/io_streams/line/utf8_reader.rb +23 -0
  33. data/lib/io_streams/path.rb +227 -28
  34. data/lib/io_streams/paths/file.rb +115 -6
  35. data/lib/io_streams/paths/http.rb +92 -5
  36. data/lib/io_streams/paths/matcher.rb +6 -3
  37. data/lib/io_streams/paths/s3.rb +242 -20
  38. data/lib/io_streams/paths/sftp/net_ssh.rb +104 -0
  39. data/lib/io_streams/paths/sftp.rb +141 -57
  40. data/lib/io_streams/paths.rb +23 -0
  41. data/lib/io_streams/pgp/reader.rb +60 -2
  42. data/lib/io_streams/pgp/writer.rb +42 -6
  43. data/lib/io_streams/pgp.rb +92 -21
  44. data/lib/io_streams/reader.rb +54 -1
  45. data/lib/io_streams/record/reader.rb +71 -10
  46. data/lib/io_streams/record/writer.rb +17 -10
  47. data/lib/io_streams/row/header_row.rb +21 -0
  48. data/lib/io_streams/row/reader.rb +52 -15
  49. data/lib/io_streams/row/writer.rb +64 -13
  50. data/lib/io_streams/schema/columns.rb +456 -0
  51. data/lib/io_streams/schema/constraints.rb +99 -0
  52. data/lib/io_streams/schema/field.rb +967 -0
  53. data/lib/io_streams/schema/json_number.rb +56 -0
  54. data/lib/io_streams/schema/keys.rb +78 -0
  55. data/lib/io_streams/schema/pattern.rb +257 -0
  56. data/lib/io_streams/schema/source.rb +31 -0
  57. data/lib/io_streams/schema.rb +616 -0
  58. data/lib/io_streams/stream.rb +843 -69
  59. data/lib/io_streams/symmetric_encryption/reader.rb +12 -0
  60. data/lib/io_streams/symmetric_encryption/writer.rb +4 -0
  61. data/lib/io_streams/tabular/header.rb +60 -4
  62. data/lib/io_streams/tabular/header_mapping.rb +332 -0
  63. data/lib/io_streams/tabular/mapping.rb +165 -0
  64. data/lib/io_streams/tabular/parser/array.rb +5 -0
  65. data/lib/io_streams/tabular/parser/base.rb +34 -0
  66. data/lib/io_streams/tabular/parser/csv.rb +5 -0
  67. data/lib/io_streams/tabular/parser/fixed.rb +200 -1
  68. data/lib/io_streams/tabular/parser/fixed_fields.rb +160 -0
  69. data/lib/io_streams/tabular/parser/hash.rb +10 -0
  70. data/lib/io_streams/tabular/parser/json.rb +17 -0
  71. data/lib/io_streams/tabular/parser/json_fields.rb +132 -0
  72. data/lib/io_streams/tabular/parser/psv.rb +6 -2
  73. data/lib/io_streams/tabular/schema_mapping.rb +361 -0
  74. data/lib/io_streams/tabular.rb +344 -30
  75. data/lib/io_streams/utils.rb +467 -1
  76. data/lib/io_streams/version.rb +1 -1
  77. data/lib/io_streams/writer.rb +37 -1
  78. data/lib/io_streams/xlsx/cells.rb +127 -0
  79. data/lib/io_streams/xlsx/reader.rb +61 -1
  80. data/lib/io_streams/xlsx/schema_reader.rb +90 -0
  81. data/lib/io_streams/xlsx/v3_writer.rb +16 -0
  82. data/lib/io_streams/zip/reader.rb +11 -0
  83. data/lib/io_streams/zip/writer.rb +28 -2
  84. data/lib/iostreams.rb +21 -17
  85. metadata +50 -7
@@ -160,13 +160,14 @@ module IOStreams
160
160
  end
161
161
  end
162
162
 
163
- # Delete all private and public keys for a particular email.
163
+ # Delete all private and public keys for a particular email or key id.
164
164
  #
165
165
  # Returns false if no key was found.
166
166
  # Raises an exception if it fails to delete the key.
167
+ # Raises ArgumentError when neither :email nor :key_id is supplied.
167
168
  #
168
- # email: [String] Optional email address for the key.
169
- # key_id: [String] Optional id for the key.
169
+ # email: [String] Email address for the key.
170
+ # key_id: [String] Id for the key.
170
171
  #
171
172
  # public: [true|false]
172
173
  # Whether to delete the public key
@@ -176,6 +177,8 @@ module IOStreams
176
177
  # Whether to delete the private key
177
178
  # Default: false
178
179
  def self.delete_keys(email: nil, key_id: nil, public: true, private: false)
180
+ raise(ArgumentError, "Either :email, or :key_id must be supplied") if email.nil? && key_id.nil?
181
+
179
182
  version_check
180
183
  # Version 2.1+ uses delete_public_or_private_keys
181
184
  # Version < 2.1 uses delete_public_or_private_keys_v1
@@ -207,7 +210,8 @@ module IOStreams
207
210
  def self.list_keys(email: nil, key_id: nil, private: false)
208
211
  version_check
209
212
  args = [private ? "--list-secret-keys" : "--list-keys"]
210
- args << (email || key_id).to_s if email || key_id
213
+ # `--` stops gpg from treating the email or key id as an option.
214
+ args += ["--", (email || key_id).to_s] if email || key_id
211
215
  command = gpg_command(*args)
212
216
 
213
217
  out, err, status = Open3.capture3(*command, binmode: true)
@@ -255,14 +259,30 @@ module IOStreams
255
259
  parse_list_output(out)
256
260
  end
257
261
 
258
- # Returns [String] containing all the public keys for the supplied email address.
262
+ # Returns [String] containing all the public keys for the supplied email address or key id.
263
+ #
264
+ # Raises ArgumentError when neither :email nor :key_id is supplied.
265
+ # Raises Pgp::Failure when `email: nil` is supplied without a :key_id, as before :key_id was added, which is
266
+ # deprecated, since v3.0 raises ArgumentError for it instead: it reports a deprecation warning, see
267
+ # `IOStreams::Deprecation`.
259
268
  #
260
269
  # email: [String] Email address for requested key.
261
270
  #
271
+ # key_id: [String] Id for the requested key.
272
+ #
262
273
  # ascii: [true|false]
263
274
  # Whether to export as ASCII text instead of binary format
264
275
  # Default: true
265
- def self.export(email:, ascii: true, private: false, passphrase: nil)
276
+ def self.export(email: (email_omitted = true) && nil, key_id: nil, ascii: true, private: false, passphrase: nil)
277
+ if email.nil? && key_id.nil?
278
+ raise(ArgumentError, "Either :email, or :key_id must be supplied") if email_omitted
279
+
280
+ Deprecation.warn("IOStreams::Pgp.export with email: nil and without a key_id: is deprecated, since v3.0 " \
281
+ "raises ArgumentError for it rather than IOStreams::Pgp::Failure: supply the email: or " \
282
+ "key_id: of the key")
283
+ raise(Pgp::Failure, "GPG Failed reading key: no email address or key id was supplied")
284
+ end
285
+
266
286
  version_check
267
287
 
268
288
  args = []
@@ -270,15 +290,16 @@ module IOStreams
270
290
  args << "--no-symkey-cache" if pgp_version.to_f >= 2.4
271
291
  args << "--armor" if ascii
272
292
  args += ["--no-tty", "--batch"]
273
- args += passphrase ? ["--passphrase", passphrase] : ["--passphrase-fd", "0"]
274
- args += private ? ["--export-secret-keys", email.to_s] : ["--export", email.to_s]
293
+ # Supply the passphrase on stdin so that it is not visible in the process list.
294
+ args += ["--passphrase-fd", "0"]
295
+ args << (private ? "--export-secret-keys" : "--export")
296
+ args += ["--", (email || key_id).to_s]
275
297
  command = gpg_command(*args)
276
298
 
277
- out, err, status = Open3.capture3(*command, binmode: true)
278
- # Do not log the command, it may contain the passphrase.
279
- IOStreams.logger&.debug { "IOStreams::Pgp.export: #{email}\n#{err}" }
299
+ out, err, status = Open3.capture3(*command, binmode: true, stdin_data: passphrase.to_s)
300
+ IOStreams.logger&.debug { "IOStreams::Pgp.export: #{command.shelljoin}\n#{err}" }
280
301
 
281
- raise(Pgp::Failure, "GPG Failed reading key: #{email}: #{err}") unless status.success? && out.length.positive?
302
+ raise(Pgp::Failure, "GPG Failed reading key: #{email || key_id}: #{err}") unless status.success? && out.length.positive?
282
303
 
283
304
  out
284
305
  end
@@ -424,18 +445,47 @@ module IOStreams
424
445
  # Notes:
425
446
  # - If the same email address has multiple keys then only the first is currently trusted.
426
447
  def self.import_and_trust(key:, trust_level: 5)
448
+ info = import_and_trust_key_info(key: key, trust_level: trust_level)
449
+ info[:email] || info[:key_id]
450
+ end
451
+
452
+ # Imports and trusts the supplied key, see #import_and_trust.
453
+ #
454
+ # Returns [String] the recipient to encrypt to: the key's fingerprint when gpg supplies it,
455
+ # otherwise the email address or key id returned by #import_and_trust.
456
+ #
457
+ # Encrypting to the fingerprint ensures that the imported key is used, since gpg looks up an
458
+ # email address in the keyring, where another key may have the same email address.
459
+ #
460
+ # Used internally by the PGP writer.
461
+ def self.import_and_trust_recipient(key:, trust_level: 5)
462
+ info = import_and_trust_key_info(key: key, trust_level: trust_level)
463
+ key_id = info[:key_id].to_s
464
+ # gpg v2.1 and later supply the full fingerprint: 40 hex digits for v4 keys, 64 for v5 and v6 keys.
465
+ # Earlier versions only supply a short key id, which is not unique.
466
+ return key_id if key_id.match?(/\A(\h{40}|\h{64})\z/)
467
+
468
+ info[:email] || info[:key_id]
469
+ end
470
+
471
+ # Returns [Hash] the key info for the supplied key, after importing and trusting it.
472
+ def self.import_and_trust_key_info(key:, trust_level:)
427
473
  raise(ArgumentError, "Key cannot be empty") if key.nil? || (key == "")
428
474
 
429
- key_info = key_info(key: key).last
475
+ infos = key_info(key: key)
476
+ info = infos.last&.dup || {}
477
+ # When a key has several user ids, only the entry for its first user id includes the key id.
478
+ info[:key_id] ||= infos.reverse_each.find { |entry| entry[:key_id] }&.fetch(:key_id)
430
479
 
431
- email = key_info.fetch(:email, nil)
432
- key_id = key_info.fetch(:key_id, nil)
480
+ email = info[:email]
481
+ key_id = info[:key_id]
433
482
  raise(ArgumentError, "Recipient email or key id cannot be extracted from supplied key") unless email || key_id
434
483
 
435
484
  import(key: key)
436
485
  set_trust(email: email, key_id: key_id, level: trust_level)
437
- email || key_id
486
+ info
438
487
  end
488
+ private_class_method :import_and_trust_key_info
439
489
 
440
490
  # Set the trust level for an existing key.
441
491
  #
@@ -444,6 +494,14 @@ module IOStreams
444
494
  #
445
495
  # After importing keys, they are not trusted and the relevant trust level must be set.
446
496
  #
497
+ # Without an :email or :key_id, it raises Pgp::Failure, since gpg rejects the empty user id that it is asked for,
498
+ # which is deprecated, since v3.0 raises ArgumentError instead: it reports a deprecation warning, see
499
+ # `IOStreams::Deprecation`.
500
+ #
501
+ # key_id: [String]
502
+ # The fingerprint of the key, as hexadecimal digits only.
503
+ # Raises ArgumentError when it contains any other characters.
504
+ #
447
505
  # level: [Integer]
448
506
  # The owner-trust level to assign to the key:
449
507
  # 1 : Undefined (no opinion)
@@ -461,6 +519,18 @@ module IOStreams
461
519
  # key at this level allows that attacker to impersonate other recipients.
462
520
  # When the key cannot be fully verified, supply a lower `level`.
463
521
  def self.set_trust(email: nil, key_id: nil, level: 5)
522
+ if email.nil? && key_id.nil?
523
+ Deprecation.warn("IOStreams::Pgp.set_trust without an email: or key_id: is deprecated, since v3.0 raises " \
524
+ "ArgumentError for it rather than IOStreams::Pgp::Failure: supply the email: or key_id: of " \
525
+ "the key")
526
+ end
527
+
528
+ # The key_id is written into gpg's ownertrust input, where any other character, such as a newline,
529
+ # could add trust lines for other keys.
530
+ if key_id && !key_id.to_s.match?(/\A\h+\z/)
531
+ raise(ArgumentError, "Invalid :key_id, it must only contain hexadecimal digits: #{key_id.inspect}")
532
+ end
533
+
464
534
  version_check
465
535
  fingerprint = key_id || fingerprint(email: email)
466
536
  return unless fingerprint
@@ -479,7 +549,7 @@ module IOStreams
479
549
  # Public callers should identify keys by `key_id` (see #list_keys / #key_info).
480
550
  def self.fingerprint(email:)
481
551
  version_check
482
- command = gpg_command("--list-keys", "--fingerprint", "--with-colons", email.to_s)
552
+ command = gpg_command("--list-keys", "--fingerprint", "--with-colons", "--", email.to_s)
483
553
  Open3.popen2e(*command) do |_stdin, out, waith_thr|
484
554
  output = out.read.chomp
485
555
  if !waith_thr.value.success? && output !~ /(public key not found|No public key)/i
@@ -609,10 +679,11 @@ module IOStreams
609
679
  hash[:trust] = match[2].to_s.strip if match[1]
610
680
  results << hash
611
681
  hash = {}
612
- elsif (match = line.match(/\s+([A-Z0-9]{16,40})/))
682
+ elsif (match = line.match(/\s+([A-Z0-9]{16,64})/))
613
683
  # v2.2/v2.4 key id on separate line:
614
684
  # 18A0FC1C09C0D8AE34CE659257DC4AE323C7368C
615
685
  # Or shorter format: 7932AB23D7238F6B
686
+ # Or a 64 digit fingerprint for v5 and v6 keys.
616
687
  hash[:key_id] ||= match[1]
617
688
  end
618
689
  end
@@ -636,7 +707,7 @@ module IOStreams
636
707
  key_id = key_info[:key_id]
637
708
  next unless key_id
638
709
 
639
- command = gpg_command("--batch", "--no-tty", "--yes", "--delete-#{keys}", key_id)
710
+ command = gpg_command("--batch", "--no-tty", "--yes", "--delete-#{keys}", "--", key_id)
640
711
  out, err, status = Open3.capture3(*command, binmode: true)
641
712
  IOStreams.logger&.debug { "IOStreams::Pgp.delete_keys: #{command.shelljoin}\n#{err}#{out}" }
642
713
 
@@ -653,7 +724,7 @@ module IOStreams
653
724
 
654
725
  # List the fingerprints, then delete each one. Previously this shelled out
655
726
  # to a `for` loop, which allowed shell injection via :email / :key_id.
656
- list_command = gpg_command("--list-#{keys}", "--with-colons", "--fingerprint", (email || key_id).to_s)
727
+ list_command = gpg_command("--list-#{keys}", "--with-colons", "--fingerprint", "--", (email || key_id).to_s)
657
728
  list_out, list_err, = Open3.capture3(*list_command, binmode: true)
658
729
  IOStreams.logger&.debug { "IOStreams::Pgp.delete_keys: #{list_command.shelljoin}\n#{list_err}: #{list_out}" }
659
730
 
@@ -663,7 +734,7 @@ module IOStreams
663
734
  return false if fingerprints.empty?
664
735
 
665
736
  fingerprints.each do |fingerprint|
666
- command = gpg_command("--batch", "--no-tty", "--yes", "--delete-#{keys}", fingerprint)
737
+ command = gpg_command("--batch", "--no-tty", "--yes", "--delete-#{keys}", "--", fingerprint)
667
738
  out, err, status = Open3.capture3(*command, binmode: true)
668
739
  IOStreams.logger&.debug { "IOStreams::Pgp.delete_keys: #{command.shelljoin}\n#{err}: #{out}" }
669
740
 
@@ -1,9 +1,62 @@
1
1
  module IOStreams
2
2
  class Reader
3
+ # Answers the names of the options that this reader takes in IOStreams 3.0, and those that it replaces.
4
+ extend Deprecation::OptionNames
5
+
6
+ # Returns [Array<Symbol>] the names of the options this reader accepts,
7
+ # or [nil] when the reader does not declare them.
8
+ #
9
+ # When declared, `IOStreams::Builder` rejects any other option before the reader is opened,
10
+ # naming the direction an option belongs to when it is only valid for the other direction.
11
+ def self.option_names
12
+ nil
13
+ end
14
+
15
+ # Returns [Array<Symbol>] the names of the options whose values must not be displayed, such as a passphrase,
16
+ # so that `#inspect` on a path does not display them, see `IOStreams::Extension#redact_options`.
17
+ def self.sensitive_option_names
18
+ []
19
+ end
20
+
21
+ # Returns [Symbol|nil] the tabular format of the text that this reader turns its data into, such as `:csv` for a
22
+ # spreadsheet, otherwise nil, for a reader whose data is the text, such as gzip, see
23
+ # `IOStreams::Builder#text_format`.
24
+ def self.text_format
25
+ nil
26
+ end
27
+
28
+ # The methods of an IO that read, which every stream that v3.0 supplies to a reader block answers, see
29
+ # .v3_stream_methods.
30
+ V3_READ_METHODS = %i[read readpartial gets readline readlines each_line each eof? eof closed?].freeze
31
+
32
+ # Returns [Array<Symbol>|nil] the methods that the stream that v3.0 supplies to a reader block, in place of the one
33
+ # that this reader yields, answers, when it does not answer all of the methods of that one, such as when it is the
34
+ # reader of a gem, otherwise nil, for a reader that yields the same kind of stream in both versions, see
35
+ # `IOStreams::Builder#v3_stream`.
36
+ #
37
+ # Parameters:
38
+ # options: [Hash]
39
+ # The options that this reader is opened with, such as `verify_first: true` for PGP, see
40
+ # `IOStreams::Pgp::Reader.v3_stream_methods`.
41
+ #
42
+ # Yields, for a reader whose stream depends on it, to ask whether this reader reads a regular local file in v3.0,
43
+ # rather than another stream, an IO that is not a file, or the object of an S3 or HTTP path, which v3.0 reads without
44
+ # a temp file. The block answers true or false.
45
+ def self.v3_stream_methods(_options)
46
+ nil
47
+ end
48
+
49
+ # Returns [Hash<Symbol:String>|nil] what the application uses in place of each method of the stream that this reader
50
+ # yields that v3.0 removes, when it is not the methods that the stream of v3.0 answers, see .v3_stream_methods, such as
51
+ # a setting of the path, otherwise nil, see `IOStreams::Builder#v3_stream`.
52
+ def self.v3_stream_advice
53
+ nil
54
+ end
55
+
3
56
  # When a Reader does not support streams, we copy the stream to a local temp file
4
57
  # and then pass that filename in for this reader.
5
58
  def self.stream(input_stream, **args, &block)
6
- Utils.temp_file_name("iostreams_reader") do |file_name|
59
+ Utils.private_temp_file("iostreams_reader") do |file_name|
7
60
  ::File.open(file_name, "wb") { |target| ::IO.copy_stream(input_stream, target) }
8
61
  file(file_name, **args, &block)
9
62
  end
@@ -56,26 +56,87 @@ module IOStreams
56
56
  # #as_hash will skip these additional columns entirely as if they were not in the file at all.
57
57
  # false:
58
58
  # Raises Tabular::InvalidHeader when a column is supplied that is not in the whitelist.
59
- def initialize(line_reader, cleanse_header: true, original_file_name: nil, **args)
59
+ #
60
+ # cleanse_header: [true|false]
61
+ # Whether to cleanse the header row read, see `IOStreams::Tabular::Header#cleanse!`, which the tabular that it
62
+ # creates does, see `IOStreams::Tabular.new`.
63
+ # With a schema it raises ArgumentError, even when nil, since the fields of the schema name the keys of the
64
+ # records instead.
65
+ # Default: cleanses it.
66
+ #
67
+ # tabular: [IOStreams::Tabular]
68
+ # The tabular that parses each line, such as one with a schema, see `IOStreams::Stream#schema`, in place of the
69
+ # other options, which create it.
70
+ #
71
+ # report_repeated_key: [true|false]
72
+ # Whether to report a deprecation warning, before the first record, when two columns of the header row are the
73
+ # same key, see #warn_repeated_key, which `IOStreams::Stream#each` and `#reader` ask for, rather than another
74
+ # gem that creates a reader, which its users cannot change.
75
+ # Default: false
76
+ #
77
+ # Note:
78
+ # * `allowed_columns`, `required_columns` and `skip_unknown` only apply to every input, including JSON records,
79
+ # supplied `columns` and `cleanse_header: false`, when `IOStreams.enforce_column_restrictions?` is true.
80
+ def initialize(line_reader, original_file_name: nil, tabular: nil, report_repeated_key: false, **args)
60
81
  unless line_reader.respond_to?(:each)
61
82
  raise(ArgumentError, "Stream must be a IOStreams::Line::Reader or implement #each")
62
83
  end
63
84
 
64
- @tabular = IOStreams::Tabular.new(file_name: original_file_name, **args)
65
- @line_reader = line_reader
66
- @cleanse_header = cleanse_header
85
+ if tabular && (original_file_name || !args.empty?)
86
+ raise(ArgumentError, "Supply either tabular: or the options that create it, not both")
87
+ end
88
+
89
+ @tabular = tabular || IOStreams::Tabular.new(file_name: original_file_name, **args)
90
+ @line_reader = line_reader
91
+ @report_repeated_key = report_repeated_key
92
+
93
+ # Supplied columns take the place of a header row, so apply the allowed and required columns to them.
94
+ @tabular.restrict_columns
95
+ end
96
+
97
+ # Yields each record, after the header row, which names their keys, see `IOStreams::Tabular#read_record_line`.
98
+ def each(&block)
99
+ return each_reporting(&block) if @report_repeated_key
100
+
101
+ @line_reader.each { |line| @tabular.read_record_line(line, &block) }
102
+ end
103
+
104
+ # Writes each record to the writer, see `IOStreams::Record::Writer`, as a copy with a schema does, see
105
+ # `IOStreams::Stream#copy_from`. A blank line, or a JSON line of null, which #each yields as nil, is not a record,
106
+ # so it is not written.
107
+ #
108
+ # Returns the result of #each.
109
+ def copy_to(writer)
110
+ each { |record| writer << record unless record.nil? }
67
111
  end
68
112
 
69
- def each
113
+ private
114
+
115
+ # Yields each record, as #each does, after reporting a deprecation warning before the first one when two columns
116
+ # of the header row are the same key, see #warn_repeated_key.
117
+ def each_reporting
70
118
  @line_reader.each do |line|
71
- if @tabular.header?
72
- @tabular.parse_header(line)
73
- @tabular.cleanse_header! if @cleanse_header
74
- else
75
- yield @tabular.record_parse(line)
119
+ @tabular.read_record_line(line) do |record|
120
+ warn_repeated_key if @report_repeated_key
121
+ yield record
76
122
  end
77
123
  end
78
124
  end
125
+
126
+ # Reports a deprecation warning, once, when two columns of the header row are the same key, see
127
+ # `IOStreams::Tabular#repeated_key`, such as a header row of `a,a,b`, or of `A` and `a`, which are cleansed to the
128
+ # same key, since each record holds the value of only the last of them, while IOStreams v3.0 raises
129
+ # `IOStreams::Errors::InvalidHeader` for them, rather than lose the others.
130
+ def warn_repeated_key
131
+ @report_repeated_key = false
132
+ key = @tabular.repeated_key
133
+ return if key.nil?
134
+
135
+ Deprecation.warn("records read from a header row whose columns are the same key, #{key.inspect}, are " \
136
+ "deprecated, since each record holds the value of only the last of them, and v3.0 raises " \
137
+ "IOStreams::Errors::InvalidHeader for them: rename the columns, or read the rows with " \
138
+ "each(:array), which holds every column")
139
+ end
79
140
  end
80
141
  end
81
142
  end
@@ -58,25 +58,32 @@ module IOStreams
58
58
  # #as_hash will skip these additional columns entirely as if they were not in the file at all.
59
59
  # false:
60
60
  # Raises Tabular::InvalidHeader when a column is supplied that is not in the whitelist.
61
- def initialize(line_writer, columns: nil, original_file_name: nil, **args)
61
+ #
62
+ # tabular: [IOStreams::Tabular]
63
+ # The tabular that renders each record, such as one with a schema, see `IOStreams::Stream#schema`, in place of
64
+ # the other options, which create it.
65
+ def initialize(line_writer, columns: nil, original_file_name: nil, tabular: nil, **args)
62
66
  raise(ArgumentError, "Stream must be a IOStreams::Line::Writer or implement #<<") unless line_writer.respond_to?(:<<)
63
67
 
64
- @tabular = IOStreams::Tabular.new(columns: columns, file_name: original_file_name, **args)
68
+ if tabular && (columns || original_file_name || !args.empty?)
69
+ raise(ArgumentError, "Supply either tabular: or the options that create it, not both")
70
+ end
71
+
72
+ IOStreams::Tabular.check_write_options(args)
73
+ @tabular = tabular || IOStreams::Tabular.new(columns: columns, file_name: original_file_name, **args)
65
74
  @line_writer = line_writer
66
75
 
67
- # Render header line when `columns` is supplied.
68
- @line_writer << @tabular.render_header if columns && @tabular.requires_header?
76
+ # Render header line when `columns` is supplied, or with a schema the names of its fields, see
77
+ # `IOStreams::Tabular#start_records`.
78
+ @tabular.start_records { |line| @line_writer << line }
69
79
  end
70
80
 
81
+ # Writes the record, after the header line that the keys of the first record give, when neither the columns
82
+ # supplied nor a schema give it, see `IOStreams::Tabular#render_record`.
71
83
  def <<(hash)
72
84
  raise(ArgumentError, "#<< only accepts a Hash argument") unless hash.is_a?(Hash)
73
85
 
74
- if @tabular.header?
75
- # Extract header from the keys from the first row when not supplied above.
76
- @tabular.header.columns = hash.keys
77
- @line_writer << @tabular.render_header
78
- end
79
- @line_writer << @tabular.render(hash)
86
+ @tabular.render_record(hash) { |line| @line_writer << line }
80
87
  end
81
88
  end
82
89
  end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module IOStreams
4
+ module Row
5
+ # The header row that `IOStreams::Stream#each(:array)` yields before the rows of a file, which names the column of
6
+ # each value of the rows after it. It is an Array, as every other row is, whose class says that it is the header
7
+ # row, so that a writer of rows takes it as the header row of the rows written after it, rather than as a row of
8
+ # values, see `IOStreams::Row::Writer#<<`, and so that code that reads the rows can tell it apart:
9
+ #
10
+ # path.each(:array) do |row|
11
+ # next if row.is_a?(IOStreams::Row::HeaderRow)
12
+ #
13
+ # process(row)
14
+ # end
15
+ #
16
+ # It is equal to an Array of the same columns, and the methods of an Array that return a new Array, such as `map`,
17
+ # return an Array rather than a header row, so that a row made from it is a row of values.
18
+ class HeaderRow < ::Array
19
+ end
20
+ end
21
+ end
@@ -28,27 +28,64 @@ module IOStreams
28
28
  # format: [Symbol]
29
29
  # :csv, :hash, :array, :json, :psv, :fixed
30
30
  #
31
- # For all other parameters, see Tabular::Header.new
32
- def initialize(line_reader, cleanse_header: true, original_file_name: nil, **args)
31
+ # cleanse_header: [true|false]
32
+ # Whether to cleanse the header row read, see `IOStreams::Tabular::Header#cleanse!`, which the tabular that it
33
+ # creates does, see `IOStreams::Tabular.new`.
34
+ # With a schema it raises ArgumentError, even when nil, since the fields of the schema name the keys of the
35
+ # records instead.
36
+ # Default: cleanses it.
37
+ #
38
+ # tabular: [IOStreams::Tabular]
39
+ # The tabular that parses each line, such as one with a schema, see `IOStreams::Stream#schema`, in place of the
40
+ # other options, which create it.
41
+ #
42
+ # For all other parameters, see IOStreams::Tabular.new
43
+ def initialize(line_reader, original_file_name: nil, tabular: nil, **args)
33
44
  unless line_reader.respond_to?(:each)
34
45
  raise(ArgumentError, "Stream must be a IOStreams::Line::Reader or implement #each")
35
46
  end
36
47
 
37
- @tabular = IOStreams::Tabular.new(file_name: original_file_name, **args)
38
- @line_reader = line_reader
39
- @cleanse_header = cleanse_header
48
+ if tabular && (original_file_name || !args.empty?)
49
+ raise(ArgumentError, "Supply either tabular: or the options that create it, not both")
50
+ end
51
+
52
+ @tabular = tabular || IOStreams::Tabular.new(file_name: original_file_name, **args)
53
+ @line_reader = line_reader
40
54
  end
41
55
 
42
- def each
43
- @line_reader.each do |line|
44
- if @tabular.header?
45
- columns = @tabular.parse_header(line)
46
- @tabular.cleanse_header! if @cleanse_header
47
- yield columns
48
- else
49
- yield @tabular.row_parse(line)
50
- end
51
- end
56
+ # Returns [true|false] whether the first row that #each yields is a header row, which names the column of each
57
+ # value of the rows after it, see `IOStreams::Tabular#rows_header?`: the header row of the file, or with a schema,
58
+ # the names of its fields, of a file without one, such as fixed width or JSON. False when the columns were
59
+ # supplied, which name the values of the rows instead. Asked before #each.
60
+ def header?
61
+ @tabular.rows_header?
62
+ end
63
+
64
+ # Returns [true|false] whether the rows that #each yields are the records of the file, Hashes rather than Arrays,
65
+ # see `IOStreams::Tabular#record_rows?`, such as those of JSON without a schema.
66
+ def record_rows?
67
+ @tabular.record_rows?
68
+ end
69
+
70
+ # Yields each row, an Array, after the header row of a file with one, which it yields first, see
71
+ # `IOStreams::Tabular#read_row`. With a schema, the header row is an `IOStreams::Row::HeaderRow` of the names of
72
+ # the fields, also for a file without a header row, such as fixed width or JSON.
73
+ def each(&block)
74
+ @line_reader.each { |line| @tabular.read_row(line, &block) }
75
+ end
76
+
77
+ # Writes each row to the writer, see `IOStreams::Row::Writer`, as a copy with a schema does, see
78
+ # `IOStreams::Stream#copy_from`, telling it the column of each value of the rows: the header row of the file, or
79
+ # for a file without one, the names of the fields of its schema, is an `IOStreams::Row::HeaderRow`, which the writer
80
+ # takes as the header row of the rows after it, see `IOStreams::Row::Writer#<<`, so that a target with a schema
81
+ # matches its columns to the fields, rather than write it as a row of values. Tabular decides which row is the
82
+ # header row, see `IOStreams::Tabular#start_copy` and `IOStreams::Tabular#copy_row`. A blank line, which is not a
83
+ # row, is not written.
84
+ #
85
+ # Returns the result of the #each of the line reader.
86
+ def copy_to(writer)
87
+ @tabular.start_copy { |columns| writer << columns }
88
+ @line_reader.each { |line| @tabular.copy_row(line) { |row| writer << row unless row.nil? } }
52
89
  end
53
90
  end
54
91
  end
@@ -35,28 +35,79 @@ module IOStreams
35
35
  # format: [Symbol]
36
36
  # :csv, :hash, :array, :json, :psv, :fixed
37
37
  #
38
+ # tabular: [IOStreams::Tabular]
39
+ # The tabular that renders each row, such as one with a schema, see `IOStreams::Stream#schema`, in place of the
40
+ # other options, which create it.
41
+ #
42
+ # report_repeated_key: [true|false]
43
+ # Whether to report a deprecation warning when the header row of the rows written to a format whose rows are
44
+ # records, such as JSON, has two columns of the same key, see #warn_repeated_key, which
45
+ # `IOStreams::Stream#writer` asks for, rather than another gem that creates a writer, which its users cannot
46
+ # change.
47
+ # Default: false
48
+ #
38
49
  # For all other parameters, see Tabular::Header.new
39
- def initialize(line_writer, columns: nil, original_file_name: nil, **args)
50
+ def initialize(line_writer, columns: nil, original_file_name: nil, tabular: nil, report_repeated_key: false, **args)
40
51
  raise(ArgumentError, "Stream must be a IOStreams::Line::Writer or implement #<<") unless line_writer.respond_to?(:<<)
41
52
 
42
- @tabular = IOStreams::Tabular.new(columns: columns, file_name: original_file_name, **args)
43
- @line_writer = line_writer
53
+ if tabular && (columns || original_file_name || !args.empty?)
54
+ raise(ArgumentError, "Supply either tabular: or the options that create it, not both")
55
+ end
56
+
57
+ IOStreams::Tabular.check_write_options(args)
58
+ @tabular = tabular || IOStreams::Tabular.new(columns: columns, file_name: original_file_name, **args)
59
+ @line_writer = line_writer
60
+ @report_repeated_key = report_repeated_key
44
61
 
45
- # Render header line when `columns` is supplied.
46
- line_writer << @tabular.render_header if columns && @tabular.requires_header?
62
+ # Render header line when `columns` is supplied, or with a schema the names of its fields, see
63
+ # `IOStreams::Tabular#start_rows`.
64
+ @tabular.start_rows { |line| @line_writer << line }
47
65
  end
48
66
 
49
- # Supply a hash or an array to render
67
+ # Supply an array to render, otherwise it raises ArgumentError.
68
+ #
69
+ # Without a schema, the first row is the header row, unless the columns were supplied. With a schema, the header
70
+ # row of a file with one is the names of its fields, which is written before the rows, so every row written is
71
+ # the values of the fields, in order. A header row that `IOStreams::Stream#each(:array)` yields with a schema, an
72
+ # `IOStreams::Row::HeaderRow`, is written as the header row of the rows after it, see #write_header.
50
73
  def <<(array)
51
74
  raise(ArgumentError, "Must supply an Array") unless array.is_a?(Array)
75
+ return write_header(array) if array.is_a?(HeaderRow)
52
76
 
53
- if @tabular.header?
54
- # If header (columns) was not supplied as an argument, assume first line is the header.
55
- @tabular.header.columns = array
56
- @line_writer << @tabular.render_header
57
- else
58
- @line_writer << @tabular.render(array)
59
- end
77
+ @tabular.render_row(array) { |line| @line_writer << line }
78
+ end
79
+
80
+ # Writes the header row of the rows after it, such as that of the file that is copied, see
81
+ # `IOStreams::Row::Reader#copy_to`, so that the value of each column of the rows after it is written to its
82
+ # column, or to its field with a schema, whose columns it matches to the fields, without a line. Without a schema,
83
+ # as the first row, see #<<, unless the format has no header row, such as JSON, and the columns are not known,
84
+ # when it gives the columns of the rows after it, or the columns were supplied, which name them instead, see
85
+ # `IOStreams::Tabular#render_header_row`.
86
+ #
87
+ # Returns self, so that calls can be chained.
88
+ def write_header(columns)
89
+ @tabular.render_header_row(columns) { |line| @line_writer << line }
90
+ warn_repeated_key if @report_repeated_key
91
+ self
92
+ end
93
+
94
+ private
95
+
96
+ # Reports a deprecation warning when two columns of the header row are the same key, see
97
+ # `IOStreams::Tabular#repeated_key`, such as a header row of `a,a,b`, and the format writes each row as a record,
98
+ # see `IOStreams::Tabular#record_rows?`, such as JSON, since each record holds the value of only the last of them,
99
+ # while IOStreams v3.0 raises `IOStreams::Errors::InvalidHeader` for them, rather than lose the others. A format
100
+ # whose rows are Arrays, such as CSV, writes every column.
101
+ def warn_repeated_key
102
+ return unless @tabular.record_rows?
103
+
104
+ key = @tabular.repeated_key
105
+ return if key.nil?
106
+
107
+ Deprecation.warn("rows written to a format whose rows are records, such as JSON, under a header row whose " \
108
+ "columns are the same key, #{key.inspect}, are deprecated, since each record holds the value " \
109
+ "of only the last of them, and v3.0 raises IOStreams::Errors::InvalidHeader for them: rename " \
110
+ "the columns")
60
111
  end
61
112
  end
62
113
  end