From 3591a52edf89f229d99ca91ea115f58b63230130 Mon Sep 17 00:00:00 2001 From: Nick Pellant Date: Tue, 11 Jan 2022 12:28:08 +0000 Subject: [PATCH] Fix Gemspec/RequiredRubyVersion version matcher Fixes a bug believed to be introduced by rubocop#10157 where the cop no longer supported multiple requirements when they were passed as a `Gem::Requirement` object instead of as an array. --- .../fix_fix_gemspecrequiredrubyversion_version.md | 1 + lib/rubocop/cop/gemspec/required_ruby_version.rb | 13 ++++++++++--- .../cop/gemspec/required_ruby_version_spec.rb | 8 ++++++++ 3 files changed, 19 insertions(+), 3 deletions(-) create mode 100644 changelog/fix_fix_gemspecrequiredrubyversion_version.md diff --git a/changelog/fix_fix_gemspecrequiredrubyversion_version.md b/changelog/fix_fix_gemspecrequiredrubyversion_version.md new file mode 100644 index 00000000000..b2a1419bfd1 --- /dev/null +++ b/changelog/fix_fix_gemspecrequiredrubyversion_version.md @@ -0,0 +1 @@ +* [#10354](https://github.com/rubocop/rubocop/pull/10354): Fix Gemspec/RequiredRubyVersion version matcher when Gem::Requirement.new is used and initialised with multiple requirements. ([@nickpellant][]) diff --git a/lib/rubocop/cop/gemspec/required_ruby_version.rb b/lib/rubocop/cop/gemspec/required_ruby_version.rb index 285be6944d4..4366269d826 100644 --- a/lib/rubocop/cop/gemspec/required_ruby_version.rb +++ b/lib/rubocop/cop/gemspec/required_ruby_version.rb @@ -68,8 +68,11 @@ class RequiredRubyVersion < Base # @!method defined_ruby_version(node) def_node_matcher :defined_ruby_version, <<~PATTERN - {$(str _) $(array (str _) (str _)) - (send (const (const nil? :Gem) :Requirement) :new $(str _))} + { + $(str _) + $(array (str _) (str _)) + (send (const (const nil? :Gem) :Requirement) :new $str+) + } PATTERN def on_new_investigation @@ -97,7 +100,11 @@ def dynamic_version?(node) def extract_ruby_version(required_ruby_version) return unless required_ruby_version - if required_ruby_version.array_type? + if required_ruby_version.is_a?(Array) + required_ruby_version = required_ruby_version.detect do |v| + /[>=]/.match?(v.str_content) + end + elsif required_ruby_version.array_type? required_ruby_version = required_ruby_version.children.detect do |v| /[>=]/.match?(v.str_content) end diff --git a/spec/rubocop/cop/gemspec/required_ruby_version_spec.rb b/spec/rubocop/cop/gemspec/required_ruby_version_spec.rb index 02879ad04fc..aab71d7e470 100644 --- a/spec/rubocop/cop/gemspec/required_ruby_version_spec.rb +++ b/spec/rubocop/cop/gemspec/required_ruby_version_spec.rb @@ -38,6 +38,14 @@ RUBY end + it 'recognizes a Gem::Requirement with multiple requirements and does not register an offense' do + expect_no_offenses(<<~RUBY) + Gem::Specification.new do |spec| + spec.required_ruby_version = Gem::Requirement.new(">= 2.7.0", "<= 2.8") + end + RUBY + end + describe 'false negatives' do it 'does not register an offense when `required_ruby_version` ' \ 'is assigned as a variable (string literal)' do