Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ jobs:
experimental: [false]
include:
- { ruby: truffleruby, os: ubuntu-latest, experimental: true }
- { ruby: jruby-head, os: ubuntu-latest, experimental: true }
runs-on: ${{ matrix.os }}
continue-on-error: ${{ matrix.experimental }}
timeout-minutes: 15
Expand Down
3 changes: 3 additions & 0 deletions lib/net/imap.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4072,6 +4072,9 @@ def self.saslprep(string, **opts)
end
end

# TODO: remove after TruffleRuby and JRuby bugs are fixed
require_relative "imap/data_polyfill"

require_relative "imap/errors"
require_relative "imap/config"
require_relative "imap/command_data"
Expand Down
244 changes: 244 additions & 0 deletions lib/net/imap/data_polyfill.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,244 @@
# frozen_string_literal: true

# Some of the code in this file was copied from the polyfill-data gem.
#
# MIT License
#
# Copyright (c) 2023 Jim Gay, Joel Drapper, Nicholas Evans
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

# simplecov:disable -- Skip test coverage for this file

unless RUBY_ENGINE in "jruby" | "truffleruby"
Net::IMAP::Data = ::Data
return # don't load the rest of the file
end
begin
module TestData
Incompatible = Class.new(StandardError)

class Abstract < ::Data
def self.class_method = :ok
def deconstruct = [:ok, *super]
end

class Inherits < Abstract.define(:foo)
end

errors = []
begin
data = Inherits.new(1)
data.foo.nil? and errors << "member attribute"
data.deconstruct in :ok, 1 or errors << "inherited #deconstruct"
Inherits.class_method rescue errors << "inherited class method"
rescue => error
errors << error.detailed_message(highlight: false, did_you_mean: false)
end
raise Incompatible, errors.join(", ") if errors.any?
end
rescue TestData::Incompatible => err
warn "Detected incompatible Data implementation: #{err}."
else
Net::IMAP::Data = ::Data
return # don't load the rest of the file
ensure
Object.module_exec do remove_const :TestData end if defined?(TestData)
end

warn "Using Net::IMAP::Data polyfill."

module Net
class IMAP
# DataPolyfill is a temporary substitute for ruby 3.2's +Data+ class, but it
# is only loaded by JRuby and TruffleRuby. The core +Data+ class is
# tested, and when it is sufficiently compatible with CRuby, DataPolyfill
# won't be loaded.
#
# DataPolyfill is aliased as Net::IMAP::Data, so that Net::IMAP code can use
# it as +Data+.
#
# See {ruby 3.2's documentation for Data}[https://docs.ruby-lang.org/en/3.2/Data.html].
#
# Some of the code in this class was copied or adapted from the
# {polyfill-data gem}[https://rubygems.org/gems/polyfill-data], by Jim Gay
# and Joel Drapper, under the MIT license terms.
class DataPolyfill
singleton_class.undef_method :new

TYPE_ERROR = "%p is not a symbol nor a string"
ATTRSET_ERROR = "invalid data member: %p"
DUP_ERROR = "duplicate member: %p"
ARITY_ERROR = "wrong number of arguments (given %d, expected %s)"
private_constant :TYPE_ERROR, :ATTRSET_ERROR, :DUP_ERROR, :ARITY_ERROR

# Defines a new Data class.
#
# _NOTE:_ Unlike ruby 3.2's +Data.define+, DataPolyfill.define only
# supports member names which are valid local variable names. Member
# names can't be keywords (e.g: +next+ or +class+) or start with capital
# letters, "@", etc.
def self.define(*args, &block)
members = args.each_with_object({}) do |arg, members|
arg = arg.to_str unless arg in Symbol | String if arg.respond_to?(:to_str)
arg = arg.to_sym if arg in String
arg in Symbol or raise TypeError, TYPE_ERROR % [arg]
arg in %r{=} and raise ArgumentError, ATTRSET_ERROR % [arg]
members.key?(arg) and raise ArgumentError, DUP_ERROR % [arg]
members[arg] = true
end
members = members.keys.freeze

klass = ::Class.new(self)

klass.singleton_class.undef_method :define
klass.define_singleton_method(:members) { members }

def klass.new(*args, **kwargs, &block)
if kwargs.size.positive?
if args.size.positive?
raise ArgumentError, ARITY_ERROR % [args.size, 0]
end
elsif members.size < args.size
expected = members.size.zero? ? 0 : 0..members.size
raise ArgumentError, ARITY_ERROR % [args.size, expected]
else
kwargs = Hash[members.take(args.size).zip(args)]
end
allocate.tap do |instance|
instance.__send__(:initialize, **kwargs, &block)
end.freeze
end

klass.singleton_class.alias_method :[], :new
klass.attr_reader(*members)

# Dynamically defined initializer methods are in an included module,
# rather than directly on DataPolyfill (like in ruby 3.2+):
# * simpler to handle required kwarg ArgumentErrors
# * easier to ensure consistent ivar assignment order (object shape)
# * faster than instance_variable_set
klass.include(Module.new do
if members.any?
kwargs = members.map{"#{_1.name}:"}.join(", ")
params = members.map(&:name).join(", ")
ivars = members.map{"@#{_1.name}"}.join(", ")
attrs = members.map{"attrs[:#{_1.name}]"}.join(", ")
module_eval <<~RUBY, __FILE__, __LINE__ + 1
protected
def initialize(#{kwargs}) #{ivars} = #{params}; freeze end
def marshal_load(attrs) #{ivars} = #{attrs}; freeze end
RUBY
end
end)

klass.module_eval do _1.module_eval(&block) end if block_given?

klass
end

##
# singleton-method: new
# call-seq:
# new(*args) -> instance
# new(**kwargs) -> instance
#
# Constuctor for classes defined with ::define.
#
# Aliased as ::[].

##
# singleton-method: []
# call-seq:
# ::[](*args) -> instance
# ::[](**kwargs) -> instance
#
# Constuctor for classes defined with ::define.
#
# Alias for ::new

##
def members; self.class.members end
def to_h(&block) block ? __to_h__.to_h(&block) : __to_h__ end
def hash; [self.class, __to_h__].hash end
def ==(other) self.class == other.class && to_h == other.to_h end
def eql?(other) self.class == other.class && hash == other.hash end
def deconstruct; __to_h__.values end

def deconstruct_keys(keys)
raise TypeError unless keys.is_a?(Array) || keys.nil?
return __to_h__ if keys&.first.nil?
__to_h__.slice(*keys)
end

def with(**kwargs)
return self if kwargs.empty?
self.class.new(**__to_h__.merge(kwargs))
end

def inspect
__inspect_guard__(self) do |seen|
return "#<data #{self.class}:...>" if seen
attrs = __to_h__.map {|kv| "%s=%p" % kv }.join(", ")
display = ["data", self.class.name, attrs].compact.join(" ")
"#<#{display}>"
end
end
alias_method :to_s, :inspect

private

def initialize_copy(source) super.freeze end
def marshal_dump; __to_h__ end

def __to_h__; Hash[members.map {|m| [m, send(m)] }] end

# Yields +true+ if +obj+ has been seen already, +false+ if it hasn't.
# Marks +obj+ as seen inside the block, so circuler references don't
# recursively trigger a SystemStackError (stack level too deep).
#
# Making circular references inside a Data object _should_ be very
# uncommon, but we'll support them for the sake of completeness.
def __inspect_guard__(obj)
preexisting = Thread.current[:__net_imap_data__inspect__]
Thread.current[:__net_imap_data__inspect__] ||= {}.compare_by_identity
inspect_guard = Thread.current[:__net_imap_data__inspect__]
if inspect_guard.include?(obj)
yield true
else
begin
inspect_guard[obj] = true
yield false
ensure
inspect_guard.delete(obj)
end
end
ensure
unless preexisting.equal?(inspect_guard)
Thread.current[:__net_imap_data__inspect__] = preexisting
end
end

end

Data = DataPolyfill
end
end

# simplecov:enable
2 changes: 1 addition & 1 deletion lib/net/imap/errors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ def initialize(state, response:, command: nil)
@state, @command, @response = state, command, response
cmd_desc = name ? "#{state} #{name}" : state
super "Received tagged #{status} to #{cmd_desc} command (tag=#{tag})"
rescue NoMatchingPatternError => err
rescue NoMatchingPatternError, NoMatchingPatternKeyError => err
raise ArgumentError, err.message
end

Expand Down
4 changes: 3 additions & 1 deletion test/lib/helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,9 @@ def assert_local_raise(expected, message = nil)
assert_raise(expected, &block)
end
stack = caller
assert_equal stack, error.backtrace&.last(stack.size)
pend_if_jruby("stack traces don't match in JRuby 10.0.1.0") do
assert_equal stack, error.backtrace&.last(stack.size)
end
error
end

Expand Down
10 changes: 10 additions & 0 deletions test/net/imap/net_imap_test_helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,16 @@ module TestFixtureGenerators
def load_fixture_data(*test_fixture_path)
dir = self::TEST_FIXTURE_PATH
YAML.unsafe_load_file File.join(dir, *test_fixture_path)
rescue TypeError => err
case err.message
in /bind argument must be an instance of Data/
raise unless defined?(Net::IMAP::DataPolyfill)
file = test_fixture_path.last
warn "⚠️ Can't load test fixture #{file}: #{err.detailed_message}"
{tests: []}
else
raise
end
end

def generate_tests_from(fixture_data: nil, fixture_file: nil)
Expand Down
28 changes: 12 additions & 16 deletions test/net/imap/test_connection_state.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,25 +25,21 @@ class ConnectionStateTest < Net::IMAP::TestCase
end

test "#deconstruct" do
pend_if_truffleruby "TruffleRuby bug overriding ::Data methods" do
assert_equal [:not_authenticated], NotAuthenticated[].deconstruct
assert_equal [:authenticated], Authenticated[] .deconstruct
assert_equal [:selected], Selected[] .deconstruct
assert_equal [:logout], Logout[] .deconstruct
end
assert_equal [:not_authenticated], NotAuthenticated[].deconstruct
assert_equal [:authenticated], Authenticated[] .deconstruct
assert_equal [:selected], Selected[] .deconstruct
assert_equal [:logout], Logout[] .deconstruct
end

test "#deconstruct_keys" do
pend_if_truffleruby "TruffleRuby bug overriding ::Data methods" do
assert_equal({symbol: :not_authenticated}, NotAuthenticated[].deconstruct_keys([:symbol]))
assert_equal({symbol: :authenticated}, Authenticated[] .deconstruct_keys([:symbol]))
assert_equal({symbol: :selected}, Selected[] .deconstruct_keys([:symbol]))
assert_equal({symbol: :logout}, Logout[] .deconstruct_keys([:symbol]))
assert_equal({name: "not_authenticated"}, NotAuthenticated[].deconstruct_keys([:name]))
assert_equal({name: "authenticated"}, Authenticated[] .deconstruct_keys([:name]))
assert_equal({name: "selected"}, Selected[] .deconstruct_keys([:name]))
assert_equal({name: "logout"}, Logout[] .deconstruct_keys([:name]))
end
assert_equal({symbol: :not_authenticated}, NotAuthenticated[].deconstruct_keys([:symbol]))
assert_equal({symbol: :authenticated}, Authenticated[] .deconstruct_keys([:symbol]))
assert_equal({symbol: :selected}, Selected[] .deconstruct_keys([:symbol]))
assert_equal({symbol: :logout}, Logout[] .deconstruct_keys([:symbol]))
assert_equal({name: "not_authenticated"}, NotAuthenticated[].deconstruct_keys([:name]))
assert_equal({name: "authenticated"}, Authenticated[] .deconstruct_keys([:name]))
assert_equal({name: "selected"}, Selected[] .deconstruct_keys([:name]))
assert_equal({name: "logout"}, Logout[] .deconstruct_keys([:name]))
end

test "#not_authenticated?" do
Expand Down
Loading
Loading