diff --git a/changelog/fix_fix_gem_comment_restrictive_version_parsing.md b/changelog/fix_fix_gem_comment_restrictive_version_parsing.md new file mode 100644 index 00000000000..45f70e2dcbb --- /dev/null +++ b/changelog/fix_fix_gem_comment_restrictive_version_parsing.md @@ -0,0 +1 @@ +* [#10149](https://github.com/rubocop/rubocop/pull/10149): Fix `Bundler/GemComment` where it would not detect an offense in some cases when `OnlyFor` is set to `restrictive_version_specifiers`. ([@Drowze][]) diff --git a/lib/rubocop/cop/bundler/gem_comment.rb b/lib/rubocop/cop/bundler/gem_comment.rb index 747276c9ad5..c87a3ce87ec 100644 --- a/lib/rubocop/cop/bundler/gem_comment.rb +++ b/lib/rubocop/cop/bundler/gem_comment.rb @@ -88,7 +88,7 @@ class GemComment < Base CHECKED_OPTIONS_CONFIG = 'OnlyFor' VERSION_SPECIFIERS_OPTION = 'version_specifiers' RESTRICTIVE_VERSION_SPECIFIERS_OPTION = 'restrictive_version_specifiers' - RESTRICTIVE_VERSION_PATTERN = /<|~>/.freeze + RESTRICTIVE_VERSION_PATTERN = /\A\s*(?:<|~>|\d|=)/.freeze RESTRICT_ON_SEND = %i[gem].freeze def on_send(node) @@ -152,8 +152,8 @@ def version_specified_gem?(node) def restrictive_version_specified_gem?(node) return unless version_specified_gem?(node) - node.arguments - .any? { |arg| arg&.str_type? && RESTRICTIVE_VERSION_PATTERN.match?(arg.to_s) } + node.arguments[1..-1] + .any? { |arg| arg&.str_type? && RESTRICTIVE_VERSION_PATTERN.match?(arg.value) } end def contains_checked_options?(node) diff --git a/spec/rubocop/cop/bundler/gem_comment_spec.rb b/spec/rubocop/cop/bundler/gem_comment_spec.rb index 5741058c089..14398c88b26 100644 --- a/spec/rubocop/cop/bundler/gem_comment_spec.rb +++ b/spec/rubocop/cop/bundler/gem_comment_spec.rb @@ -166,7 +166,34 @@ end end - context 'when a gem is uncommented and has a version specifier' do + context 'when a gem is uncommented and has a non-minimum version specifier with a leading space' do + it 'registers an offense' do + expect_offense(<<-GEM, 'Gemfile') + gem 'rubocop', ' ~> 12.0' + ^^^^^^^^^^^^^^^^^^^^^^^^^ Missing gem description comment. + GEM + end + end + + context 'when a gem is uncommented and has a version specifier without operator' do + it 'registers an offense' do + expect_offense(<<-GEM, 'Gemfile') + gem 'rubocop', '12.0' + ^^^^^^^^^^^^^^^^^^^^^ Missing gem description comment. + GEM + end + end + + context 'when a gem is uncommented and has a frozen version specifier' do + it 'registers an offense' do + expect_offense(<<-GEM, 'Gemfile') + gem 'rubocop', '= 12.0' + ^^^^^^^^^^^^^^^^^^^^^^^ Missing gem description comment. + GEM + end + end + + context 'when a gem is uncommented and has a pessimistic version specifier' do it 'registers an offense' do expect_offense(<<-GEM, 'Gemfile') gem 'rubocop', '~> 12.0'