net-imap 0.5.10 → 0.6.3

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.
@@ -51,7 +51,159 @@ module Net
51
51
  end
52
52
 
53
53
  # Error raised when a response from the server is non-parsable.
54
+ #
55
+ # NOTE: Parser attributes are provided for debugging and inspection only.
56
+ # Their names and semantics may change incompatibly in any release.
54
57
  class ResponseParseError < Error
58
+ # returns "" for all highlights
59
+ ESC_NO_HL = Hash.new("").freeze
60
+ private_constant :ESC_NO_HL
61
+
62
+ # Translates hash[:"/foo"] to hash[:reset] when hash.key?(:foo), else ""
63
+ #
64
+ # TODO: DRY this up with Config::AttrTypeCoercion.safe
65
+ if defined?(::Ractor.shareable_proc)
66
+ default_highlight = Ractor.shareable_proc {|hash, key|
67
+ %r{\A/(.+)} =~ key && hash.key?($1.to_sym) ? hash[:reset] : ""
68
+ }
69
+ else
70
+ default_highlight = nil.instance_eval { Proc.new {|hash, key|
71
+ %r{\A/(.+)} =~ key && hash.key?($1.to_sym) ? hash[:reset] : ""
72
+ } }
73
+ ::Ractor.make_shareable(default_highlight) if defined?(::Ractor)
74
+ end
75
+
76
+ # ANSI highlights, but no colors
77
+ ESC_NO_COLOR = Hash.new(&default_highlight).update(
78
+ reset: "\e[m",
79
+ val: "\e[1m", # bold
80
+ alt: "\e[1;4m", # bold and underlined
81
+ sym: "\e[1m", # bold
82
+ label: "\e[1m", # bold
83
+ ).freeze
84
+ private_constant :ESC_NO_COLOR
85
+
86
+ # ANSI highlights, with color
87
+ ESC_COLORS = Hash.new(&default_highlight).update(
88
+ reset: "\e[m",
89
+ key: "\e[95m", # bright magenta
90
+ idx: "\e[34m", # blue
91
+ val: "\e[36;40m", # cyan on black (to ensure contrast)
92
+ alt: "\e[1;33;40m", # bold; yellow on black
93
+ sym: "\e[33;40m", # yellow on black
94
+ label: "\e[1m", # bold
95
+ nil: "\e[35m", # magenta
96
+ ).freeze
97
+ private_constant :ESC_COLORS
98
+
99
+ # Net::IMAP::ResponseParser, unless a custom parser produced the error.
100
+ attr_reader :parser_class
101
+
102
+ # The full raw response string which was being parsed.
103
+ attr_reader :string
104
+
105
+ # The parser's byte position in #string when the error was raised.
106
+ #
107
+ # _NOTE:_ This attribute is provided for debugging and inspection only.
108
+ # Its name and semantics may change incompatibly in any release.
109
+ attr_reader :pos
110
+
111
+ # The parser's lex state
112
+ #
113
+ # _NOTE:_ This attribute is provided for debugging and inspection only.
114
+ # Its name and semantics may change incompatibly in any release.
115
+ attr_reader :lex_state
116
+
117
+ # The last lexed token
118
+ #
119
+ # May be +nil+ when the parser has accepted the last token and peeked at
120
+ # the next byte without generating a token.
121
+ #
122
+ # _NOTE:_ This attribute is provided for debugging and inspection only.
123
+ # Its name and semantics may change incompatibly in any release.
124
+ attr_reader :token
125
+
126
+ def initialize(message = "unspecified parse error",
127
+ parser_class: Net::IMAP::ResponseParser,
128
+ parser_state: nil,
129
+ string: parser_state&.at(0), # see ParserUtils#parser_state
130
+ lex_state: parser_state&.at(1), # see ParserUtils#parser_state
131
+ pos: parser_state&.at(2), # see ParserUtils#parser_state
132
+ token: parser_state&.at(3)) # see ParserUtils#parser_state
133
+ @parser_class = parser_class
134
+ @string = string
135
+ @pos = pos
136
+ @lex_state = lex_state
137
+ @token = token
138
+ super(message)
139
+ end
140
+
141
+ # When +parser_state+ is true, debug info about the parser state is
142
+ # included. Defaults to the value of Net::IMAP.debug.
143
+ #
144
+ # When +parser_backtrace+ is true, a simplified backtrace is included,
145
+ # containing only frames for methods in parser_class (since ruby 3.4) or
146
+ # which have "net/imap/response_parser" in the path (before ruby 3.4).
147
+ # Most parser method names are based on rules in the IMAP grammar.
148
+ #
149
+ # When +highlight+ is not explicitly set, highlights may be enabled
150
+ # automatically, based on +TERM+ and +FORCE_COLOR+ environment variables.
151
+ #
152
+ # By default, +highlight+ uses colors from the basic ANSI palette. When
153
+ # +highlight_no_color+ is true or the +NO_COLOR+ environment variable is
154
+ # not empty, only monochromatic highlights are used: bold, underline, etc.
155
+ def detailed_message(parser_state: Net::IMAP.debug,
156
+ parser_backtrace: false,
157
+ highlight: default_highlight_from_env,
158
+ highlight_no_color: (ENV["NO_COLOR"] || "") != "",
159
+ **)
160
+ return super unless parser_state || parser_backtrace
161
+ msg = super.dup
162
+ esc = !highlight ? ESC_NO_HL : highlight_no_color ? ESC_NO_COLOR : ESC_COLORS
163
+ hl = ->str { str % esc }
164
+ val = ->str, val { hl[val.nil? ? "%{nil}%%p%{/nil}" : str] % val }
165
+ if parser_state && (string || pos || lex_state || token)
166
+ msg << hl["\n %{key}processed %{/key}: "] << val["%{val}%%p%{/val}", processed_string]
167
+ msg << hl["\n %{key}remaining %{/key}: "] << val["%{alt}%%p%{/alt}", remaining_string]
168
+ msg << hl["\n %{key}pos %{/key}: "] << val["%{val}%%p%{/val}", pos]
169
+ msg << hl["\n %{key}lex_state %{/key}: "] << val["%{sym}%%p%{/sym}", lex_state]
170
+ msg << hl["\n %{key}token %{/key}: "] << val[
171
+ "%{sym}%%<symbol>p%{/sym} => %{val}%%<value>p%{/val}", token&.to_h
172
+ ]
173
+ end
174
+ if parser_backtrace
175
+ backtrace_locations&.each_with_index do |loc, idx|
176
+ next if loc.base_label.include? "parse_error"
177
+ break if loc.base_label == "parse"
178
+ if loc.label.include?("#") # => Class#method, since ruby 3.4
179
+ next unless loc.label&.include?(parser_class.name)
180
+ else
181
+ next unless loc.path&.include?("net/imap/response_parser")
182
+ end
183
+ msg << "\n %s: %s (%s:%d)" % [
184
+ hl["%{key}caller[%{/key}%{idx}%%2d%{/idx}%{key}]%{/key}"] % idx,
185
+ hl["%{label}%%-30s%{/label}"] % loc.base_label,
186
+ File.basename(loc.path, ".rb"), loc.lineno
187
+ ]
188
+ end
189
+ end
190
+ msg
191
+ rescue => error
192
+ msg ||= super.dup
193
+ msg << "\n BUG in %s#%s: %s" % [self.class, __method__,
194
+ error.detailed_message]
195
+ msg
196
+ end
197
+
198
+ def processed_string = string && pos && string[...pos]
199
+ def remaining_string = string && pos && string[pos..]
200
+
201
+ private
202
+
203
+ def default_highlight_from_env
204
+ (ENV["FORCE_COLOR"] || "") !~ /\A(?:0|)\z/ ||
205
+ (ENV["TERM"] || "") !~ /\A(?:dumb|unknown|)\z/i
206
+ end
55
207
  end
56
208
 
57
209
  # Superclass of all errors used to encapsulate "fail" responses
@@ -25,6 +25,12 @@ module Net
25
25
  # Some search extensions may result in the server sending ESearchResult
26
26
  # responses after the initiating command has completed. Use
27
27
  # IMAP#add_response_handler to handle these responses.
28
+ #
29
+ # ==== Compatibility with SearchResult
30
+ #
31
+ # Note that both SearchResult and ESearchResult implement +each+, +to_a+,
32
+ # and +to_sequence_set+. These methods can be used regardless of whether
33
+ # the server returns +SEARCH+ or +ESEARCH+ data (or no data).
28
34
  class ESearchResult < Data.define(:tag, :uid, :data)
29
35
  def initialize(tag: nil, uid: nil, data: nil)
30
36
  tag => String | nil; tag = -tag if tag
@@ -39,12 +45,49 @@ module Net
39
45
  # numbers or UIDs, +to_a+ returns that set as an array of integers.
40
46
  #
41
47
  # When both #all and #partial are +nil+, either because the server
42
- # returned no results or because +ALL+ and +PARTIAL+ were not included in
43
- # the IMAP#search +RETURN+ options, #to_a returns an empty array.
48
+ # returned no results or because neither +ALL+ or +PARTIAL+ were included
49
+ # in the IMAP#search +RETURN+ options, #to_a returns an empty array.
44
50
  #
45
51
  # Note that SearchResult also implements +to_a+, so it can be used without
46
52
  # checking if the server returned +SEARCH+ or +ESEARCH+ data.
47
- def to_a; all&.numbers || partial&.to_a || [] end
53
+ #
54
+ # Related: #each, #to_sequence_set, #all, #partial
55
+ def to_a; to_sequence_set.numbers end
56
+
57
+ # :call-seq: to_sequence_set -> SequenceSet or nil
58
+ #
59
+ # When either #all or #partial contains a SequenceSet of message sequence
60
+ # numbers or UIDs, +to_sequence_set+ returns that sequence set.
61
+ #
62
+ # When both #all and #partial are +nil+, either because the server
63
+ # returned no results or because neither +ALL+ or +PARTIAL+ were included
64
+ # in the IMAP#search +RETURN+ options, #to_sequence_set returns
65
+ # SequenceSet.empty.
66
+ #
67
+ # Note that SearchResult also implements +to_sequence_set+, so it can be
68
+ # used without checking if the server returned +SEARCH+ or +ESEARCH+ data.
69
+ #
70
+ # Related: #each, #to_a, #all, #partial
71
+ def to_sequence_set
72
+ all || partial&.to_sequence_set || SequenceSet.empty
73
+ end
74
+
75
+ # When either #all or #partial contains a SequenceSet of message sequence
76
+ # numbers or UIDs, +each+ yields each integer in the set.
77
+ #
78
+ # When both #all and #partial are +nil+, either because the server
79
+ # returned no results or because +ALL+ and +PARTIAL+ were not included in
80
+ # the IMAP#search +RETURN+ options, #each does not yield.
81
+ #
82
+ # Note that SearchResult also implements +#each+, so it can be used
83
+ # without checking if the server returned +SEARCH+ or +ESEARCH+ data.
84
+ #
85
+ # Related: #to_sequence_set, #to_a, #all, #partial
86
+ def each(&)
87
+ return to_enum(__callee__) unless block_given?
88
+ to_sequence_set.each_number(&)
89
+ self
90
+ end
48
91
 
49
92
  ##
50
93
  # attr_reader: tag
@@ -161,6 +204,8 @@ module Net
161
204
  #
162
205
  # See also: ESearchResult#to_a.
163
206
  def to_a; results&.numbers || [] end
207
+
208
+ alias to_sequence_set results
164
209
  end
165
210
 
166
211
  # :call-seq: partial -> PartialResult or nil
@@ -6,7 +6,6 @@ module Net
6
6
  autoload :FetchData, "#{__dir__}/fetch_data"
7
7
  autoload :UIDFetchData, "#{__dir__}/fetch_data"
8
8
  autoload :SearchResult, "#{__dir__}/search_result"
9
- autoload :UIDPlusData, "#{__dir__}/uidplus_data"
10
9
  autoload :AppendUIDData, "#{__dir__}/uidplus_data"
11
10
  autoload :CopyUIDData, "#{__dir__}/uidplus_data"
12
11
  autoload :VanishedData, "#{__dir__}/vanished_data"
@@ -260,8 +259,8 @@ module Net
260
259
  #
261
260
  # === +UIDPLUS+ extension
262
261
  # See {[RFC4315 §3]}[https://www.rfc-editor.org/rfc/rfc4315#section-3].
263
- # * +APPENDUID+, #data is UIDPlusData. See IMAP#append.
264
- # * +COPYUID+, #data is UIDPlusData. See IMAP#copy.
262
+ # * +APPENDUID+, #data is AppendUIDData. See IMAP#append.
263
+ # * +COPYUID+, #data is CopyUIDData. See IMAP#copy.
265
264
  # * +UIDNOTSTICKY+, #data is +nil+. See IMAP#select.
266
265
  #
267
266
  # === +SEARCHRES+ extension
@@ -215,29 +215,20 @@ module Net
215
215
  @token = nil
216
216
  end
217
217
 
218
- def parse_error(fmt, *args)
219
- msg = format(fmt, *args)
220
- if config.debug?
221
- local_path = File.dirname(__dir__)
222
- tok = @token ? "%s: %p" % [@token.symbol, @token.value] : "nil"
223
- warn "%s %s: %s" % [self.class, __method__, msg]
224
- warn " tokenized : %s" % [@str[...@pos].dump]
225
- warn " remaining : %s" % [@str[@pos..].dump]
226
- warn " @lex_state: %s" % [@lex_state]
227
- warn " @pos : %d" % [@pos]
228
- warn " @token : %s" % [tok]
229
- caller_locations(1..20).each_with_index do |cloc, idx|
230
- next unless cloc.path&.start_with?(local_path)
231
- warn " caller[%2d]: %-30s (%s:%d)" % [
232
- idx,
233
- cloc.base_label,
234
- File.basename(cloc.path, ".rb"),
235
- cloc.lineno
236
- ]
237
- end
238
- end
239
- raise ResponseParseError, msg
240
- end
218
+ def parse_error(fmt, *args) = raise exception format(fmt, *args)
219
+
220
+ def exception(message) = ResponseParseError.new(
221
+ message, parser_state:, parser_class: self.class
222
+ )
223
+
224
+ # This can be used to backtrack after a parse error, and re-attempt to
225
+ # parse using a fallback.
226
+ #
227
+ # NOTE: Reckless backtracking could lead to O(n²) situations, so this
228
+ # should very rarely be used. Ideally, fallbacks should not backtrack.
229
+ def restore_state(state) = (@lex_state, @pos, @token = state)
230
+ def current_state = [@lex_state, @pos, @token]
231
+ def parser_state = [@str, *current_state]
241
232
 
242
233
  end
243
234
  end
@@ -38,6 +38,11 @@ module Net
38
38
  @lex_state = EXPR_BEG
39
39
  @token = nil
40
40
  return response
41
+ rescue ResponseParseError => error
42
+ if config.debug?
43
+ warn error.detailed_message(parser_state: true, parser_backtrace: true)
44
+ end
45
+ raise
41
46
  end
42
47
 
43
48
  private
@@ -1883,12 +1888,17 @@ module Net
1883
1888
  # We leniently re-interpret this as
1884
1889
  # resp-text = ["[" resp-text-code "]" [SP [text]] / [text]
1885
1890
  def resp_text
1886
- if lbra?
1887
- code = resp_text_code; rbra
1888
- ResponseText.new(code, SP? && text? || "")
1889
- else
1890
- ResponseText.new(nil, text? || "")
1891
+ begin
1892
+ state = current_state
1893
+ if lbra?
1894
+ code = resp_text_code; rbra
1895
+ return ResponseText.new(code, SP? && text? || "")
1896
+ end
1897
+ rescue ResponseParseError => error
1898
+ raise if /\buid-set\b/i.match? error.message
1899
+ restore_state state
1891
1900
  end
1901
+ ResponseText.new(nil, text? || "")
1892
1902
  end
1893
1903
 
1894
1904
  # RFC3501 (See https://www.rfc-editor.org/errata/rfc3501):
@@ -2017,24 +2027,24 @@ module Net
2017
2027
  CopyUID(validity, src_uids, dst_uids)
2018
2028
  end
2019
2029
 
2020
- def AppendUID(...) DeprecatedUIDPlus(...) || AppendUIDData.new(...) end
2021
- def CopyUID(...) DeprecatedUIDPlus(...) || CopyUIDData.new(...) end
2030
+ PARSER_PATH = File.expand_path(__FILE__).delete_suffix(".rb")
2022
2031
 
2023
2032
  # TODO: remove this code in the v0.6.0 release
2024
2033
  def DeprecatedUIDPlus(validity, src_uids = nil, dst_uids)
2025
2034
  return unless config.parser_use_deprecated_uidplus_data
2026
- compact_uid_sets = [src_uids, dst_uids].compact
2027
- count = compact_uid_sets.map { _1.count_with_duplicates }.max
2028
- max = config.parser_max_deprecated_uidplus_data_size
2029
- if count <= max
2030
- src_uids &&= src_uids.each_ordered_number.to_a
2031
- dst_uids = dst_uids.each_ordered_number.to_a
2032
- UIDPlusData.new(validity, src_uids, dst_uids)
2033
- elsif config.parser_use_deprecated_uidplus_data != :up_to_max_size
2034
- parse_error("uid-set is too large: %d > %d", count, max)
2035
- end
2035
+ uplevel = caller_locations
2036
+ .find_index { !_1.path.start_with?(PARSER_PATH) }
2037
+ &.succ
2038
+ warn("#{Config}#parser_use_deprecated_uidplus_data is ignored " \
2039
+ "since v0.6.0. Disable this warning by setting " \
2040
+ "config.parser_use_deprecated_uidplus_data = false.",
2041
+ category: :deprecated, uplevel:)
2042
+ nil
2036
2043
  end
2037
2044
 
2045
+ def AppendUID(...) DeprecatedUIDPlus(...) || AppendUIDData.new(...) end
2046
+ def CopyUID(...) DeprecatedUIDPlus(...) || CopyUIDData.new(...) end
2047
+
2038
2048
  ADDRESS_REGEXP = /\G
2039
2049
  \( (?: NIL | #{Patterns::QUOTED_rev2} ) # 1: NAME
2040
2050
  \s (?: NIL | #{Patterns::QUOTED_rev2} ) # 2: ROUTE
@@ -7,6 +7,12 @@ module Net
7
7
  # identifiers returned by Net::IMAP#uid_search.
8
8
  #
9
9
  # For backward compatibility, SearchResult inherits from Array.
10
+ #
11
+ # ==== Compatibility with ESearchResult
12
+ #
13
+ # Note that both SearchResult and ESearchResult implement +each+, +to_a+,
14
+ # and +to_sequence_set+. These methods can be used regardless of whether
15
+ # the server returns +SEARCH+ or +ESEARCH+ data (or no data).
10
16
  class SearchResult < Array
11
17
 
12
18
  # Returns a SearchResult populated with the given +seq_nums+.
@@ -60,9 +66,8 @@ module Net
60
66
  # [3, 5, 7] == Net::IMAP::SearchResult[3, 5, 7, modseq: 99] # => true
61
67
  #
62
68
  def ==(other)
63
- (modseq ?
64
- other.is_a?(self.class) && modseq == other.modseq :
65
- other.is_a?(Array)) &&
69
+ other.is_a?(Array) &&
70
+ modseq == (other.modseq if other.respond_to?(:modseq)) &&
66
71
  size == other.size &&
67
72
  sort == other.sort
68
73
  end