Skip to content

Commit

Permalink
Fix a false positive for Lint/UriRegexp
Browse files Browse the repository at this point in the history
Follow rubocop#8467 (comment).

This PR fixes false positive for `Lint/UriRegexp`
when using `regexp` with variable receiver.
  • Loading branch information
koic committed Aug 6, 2020
1 parent 7acbdb8 commit f867916
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 24 deletions.
32 changes: 8 additions & 24 deletions lib/rubocop/cop/lint/uri_regexp.rb
Expand Up @@ -16,35 +16,19 @@ module Lint
class UriRegexp < Base
extend AutoCorrector

MSG = '`%<top_level>sURI.regexp%<arg>s` is obsolete and should not ' \
'be used. Instead, use `%<top_level>sURI::DEFAULT_PARSER.' \
'make_regexp%<arg>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 = '`%<current>s` is obsolete and should not be used. Instead, use `%<preferred>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
Expand Down
6 changes: 6 additions & 0 deletions spec/rubocop/cop/lint/uri_regexp_spec.rb
Expand Up @@ -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')
Expand Down

0 comments on commit f867916

Please sign in to comment.