From f867916c40d63b782925b1bfcc220a9680fce89c Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Fri, 7 Aug 2020 01:48:26 +0900 Subject: [PATCH] Fix a false positive for `Lint/UriRegexp` Follow https://github.com/rubocop-hq/rubocop/pull/8467#issuecomment-669996714. This PR fixes false positive for `Lint/UriRegexp` when using `regexp` with variable receiver. --- lib/rubocop/cop/lint/uri_regexp.rb | 32 ++++++------------------ spec/rubocop/cop/lint/uri_regexp_spec.rb | 6 +++++ 2 files changed, 14 insertions(+), 24 deletions(-) diff --git a/lib/rubocop/cop/lint/uri_regexp.rb b/lib/rubocop/cop/lint/uri_regexp.rb index 905387c1125..4340f34b9a9 100644 --- a/lib/rubocop/cop/lint/uri_regexp.rb +++ b/lib/rubocop/cop/lint/uri_regexp.rb @@ -16,35 +16,19 @@ module Lint class UriRegexp < Base extend AutoCorrector - MSG = '`%sURI.regexp%s` is obsolete and should not ' \ - 'be used. Instead, use `%sURI::DEFAULT_PARSER.' \ - 'make_regexp%s`.' - - def_node_matcher :uri_regexp_with_argument?, <<~PATTERN - (send - (const ${nil? cbase} :URI) :regexp - ${(str _) (array ...)}) - PATTERN - - def_node_matcher :uri_regexp_without_argument?, <<~PATTERN - (send - (const ${nil? cbase} :URI) :regexp) - PATTERN + MSG = '`%s` is obsolete and should not be used. Instead, use `%s`.' + URI_CONSTANTS = ['URI', '::URI'].freeze def on_send(node) return unless node.method?(:regexp) && node.receiver + return unless URI_CONSTANTS.include?(node.receiver.source) - captured_values = uri_regexp_with_argument?(node) || uri_regexp_without_argument?(node) - - double_colon, arg = captured_values - - top_level = double_colon ? '::' : '' - argument = arg ? "(#{arg.source})" : '' - - format = format(MSG, top_level: top_level, arg: argument) + argument = node.first_argument ? "(#{node.first_argument.source})" : '' + preferred_method = "#{node.receiver.source}::DEFAULT_PARSER.make_regexp#{argument}" + message = format(MSG, current: node.source, preferred: preferred_method) - add_offense(node.loc.selector, message: format) do |corrector| - corrector.replace(node, "#{top_level}URI::DEFAULT_PARSER.make_regexp#{argument}") + add_offense(node.loc.selector, message: message) do |corrector| + corrector.replace(node, preferred_method) end end end diff --git a/spec/rubocop/cop/lint/uri_regexp_spec.rb b/spec/rubocop/cop/lint/uri_regexp_spec.rb index 8d7d2aaff61..feafc064e1f 100644 --- a/spec/rubocop/cop/lint/uri_regexp_spec.rb +++ b/spec/rubocop/cop/lint/uri_regexp_spec.rb @@ -11,6 +11,12 @@ RUBY end + it 'does not register an offense when using `regexp` with variable receiver' do + expect_no_offenses(<<~RUBY) + m.regexp('http://example.com') + RUBY + end + it 'registers an offense and corrects using `URI.regexp` with argument' do expect_offense(<<~RUBY) URI.regexp('http://example.com')