forked from rubocop/rubocop-performance
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdelete_prefix.rb
91 lines (80 loc) · 2.77 KB
/
delete_prefix.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# frozen_string_literal: true
module RuboCop
module Cop
module Performance
# In Ruby 2.5, `String#delete_prefix` has been added.
#
# This cop identifies places where `gsub(/\Aprefix/, '')` and `sub(/\Aprefix/, '')`
# can be replaced by `delete_prefix('prefix')`.
#
# This cop has `SafeMultiline` configuration option that `true` by default because
# `^prefix` is unsafe as it will behave incompatible with `delete_prefix`
# for receiver is multiline string.
#
# The `delete_prefix('prefix')` method is faster than `gsub(/\Aprefix/, '')`.
#
# @safety
# This cop is unsafe because `Pathname` has `sub` but not `delete_prefix`.
#
# @example
#
# # bad
# str.gsub(/\Aprefix/, '')
# str.gsub!(/\Aprefix/, '')
#
# str.sub(/\Aprefix/, '')
# str.sub!(/\Aprefix/, '')
#
# # good
# str.delete_prefix('prefix')
# str.delete_prefix!('prefix')
#
# @example SafeMultiline: true (default)
#
# # good
# str.gsub(/^prefix/, '')
# str.gsub!(/^prefix/, '')
# str.sub(/^prefix/, '')
# str.sub!(/^prefix/, '')
#
# @example SafeMultiline: false
#
# # bad
# str.gsub(/^prefix/, '')
# str.gsub!(/^prefix/, '')
# str.sub(/^prefix/, '')
# str.sub!(/^prefix/, '')
#
class DeletePrefix < Base
include RegexpMetacharacter
extend AutoCorrector
extend TargetRubyVersion
minimum_target_ruby_version 2.5
MSG = 'Use `%<prefer>s` instead of `%<current>s`.'
RESTRICT_ON_SEND = %i[gsub gsub! sub sub!].freeze
PREFERRED_METHODS = {
gsub: :delete_prefix,
gsub!: :delete_prefix!,
sub: :delete_prefix,
sub!: :delete_prefix!
}.freeze
def_node_matcher :delete_prefix_candidate?, <<~PATTERN
(send $!nil? ${:gsub :gsub! :sub :sub!} (regexp (str $#literal_at_start?) (regopt)) (str $_))
PATTERN
def on_send(node)
return unless (receiver, bad_method, regexp_str, replace_string = delete_prefix_candidate?(node))
return unless replace_string.empty?
good_method = PREFERRED_METHODS[bad_method]
message = format(MSG, current: bad_method, prefer: good_method)
add_offense(node.loc.selector, message: message) do |corrector|
regexp_str = drop_start_metacharacter(regexp_str)
regexp_str = interpret_string_escapes(regexp_str)
string_literal = to_string_literal(regexp_str)
new_code = "#{receiver.source}.#{good_method}(#{string_literal})"
corrector.replace(node, new_code)
end
end
end
end
end
end