forked from rubocop/rubocop
/
uri_regexp.rb
73 lines (61 loc) · 2.08 KB
/
uri_regexp.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# frozen_string_literal: true
module RuboCop
module Cop
module Lint
# This cop identifies places where `URI.regexp` is obsolete and should
# not be used. Instead, use `URI::DEFAULT_PARSER.make_regexp`.
#
# @example
# # bad
# URI.regexp('http://example.com')
#
# # good
# URI::DEFAULT_PARSER.make_regexp('http://example.com')
#
class UriRegexp < Cop
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
def on_send(node)
uri_regexp_with_argument?(node) do |double_colon, arg|
register_offense(
node, top_level: double_colon ? '::' : '', arg: "(#{arg.source})"
)
end
uri_regexp_without_argument?(node) do |double_colon|
register_offense(node, top_level: double_colon ? '::' : '')
end
end
def autocorrect(node)
lambda do |corrector|
if (captured_values = uri_regexp_with_argument?(node))
else
captured_values = uri_regexp_without_argument?(node)
end
double_colon, arg = captured_values
top_level = double_colon ? '::' : ''
argument = arg ? "(#{arg.source})" : ''
corrector.replace(
node,
"#{top_level}URI::DEFAULT_PARSER.make_regexp#{argument}"
)
end
end
private
def register_offense(node, top_level: '', arg: '')
format = format(MSG, top_level: top_level, arg: arg)
add_offense(node, location: :selector, message: format)
end
end
end
end
end