-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
format_string_token.rb
215 lines (188 loc) · 6.81 KB
/
format_string_token.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# frozen_string_literal: true
module RuboCop
module Cop
module Style
# Use a consistent style for named format string tokens.
#
# NOTE: `unannotated` style cop only works for strings
# which are passed as arguments to those methods:
# `printf`, `sprintf`, `format`, `%`.
# The reason is that _unannotated_ format is very similar
# to encoded URLs or Date/Time formatting strings.
#
# This cop can be customized ignored methods with `IgnoredMethods`.
# By default, there are no methods to ignored.
#
# @example EnforcedStyle: annotated (default)
#
# # bad
# format('%{greeting}', greeting: 'Hello')
# format('%s', 'Hello')
#
# # good
# format('%<greeting>s', greeting: 'Hello')
#
# @example EnforcedStyle: template
#
# # bad
# format('%<greeting>s', greeting: 'Hello')
# format('%s', 'Hello')
#
# # good
# format('%{greeting}', greeting: 'Hello')
#
# @example EnforcedStyle: unannotated
#
# # bad
# format('%<greeting>s', greeting: 'Hello')
# format('%{greeting}', greeting: 'Hello')
#
# # good
# format('%s', 'Hello')
#
# It is allowed to contain unannotated token
# if the number of them is less than or equals to
# `MaxUnannotatedPlaceholdersAllowed`.
#
# @example MaxUnannotatedPlaceholdersAllowed: 0
#
# # bad
# format('%06d', 10)
# format('%s %s.', 'Hello', 'world')
#
# # good
# format('%<number>06d', number: 10)
#
# @example MaxUnannotatedPlaceholdersAllowed: 1 (default)
#
# # bad
# format('%s %s.', 'Hello', 'world')
#
# # good
# format('%06d', 10)
#
# @example IgnoredMethods: [] (default)
#
# # bad
# redirect('foo/%{bar_id}')
#
# @example IgnoredMethods: [redirect]
#
# # good
# redirect('foo/%{bar_id}')
#
class FormatStringToken < Base
include ConfigurableEnforcedStyle
include IgnoredMethods
extend AutoCorrector
def on_str(node)
return if format_string_token?(node) || use_ignored_method?(node)
detections = collect_detections(node)
return if detections.empty?
return if allowed_unannotated?(detections)
detections.each do |detected_sequence, token_range|
check_sequence(detected_sequence, token_range)
end
end
private
# @!method format_string_in_typical_context?(node)
def_node_matcher :format_string_in_typical_context?, <<~PATTERN
{
^(send _ {:format :sprintf :printf} %0 ...)
^(send %0 :% _)
}
PATTERN
def format_string_token?(node)
!node.value.include?('%') || node.each_ancestor(:xstr, :regexp).any?
end
def use_ignored_method?(node)
send_parent = node.each_ancestor(:send).first
send_parent && ignored_method?(send_parent.method_name)
end
def check_sequence(detected_sequence, token_range)
if detected_sequence.style == style
correct_style_detected
elsif correctable_sequence?(detected_sequence.type)
style_detected(detected_sequence.style)
add_offense(token_range, message: message(detected_sequence.style)) do |corrector|
autocorrect_sequence(corrector, detected_sequence, token_range)
end
end
end
def correctable_sequence?(detected_type)
detected_type == 's' || style == :annotated || style == :unannotated
end
def autocorrect_sequence(corrector, detected_sequence, token_range)
return if style == :unannotated
name = detected_sequence.name
return if name.nil?
flags = detected_sequence.flags
width = detected_sequence.width
precision = detected_sequence.precision
type = detected_sequence.style == :template ? 's' : detected_sequence.type
correction = case style
when :annotated then "%<#{name}>#{flags}#{width}#{precision}#{type}"
when :template then "%#{flags}#{width}#{precision}{#{name}}"
end
corrector.replace(token_range, correction)
end
def unannotated_format?(node, detected_style)
detected_style == :unannotated && !format_string_in_typical_context?(node)
end
def message(detected_style)
"Prefer #{message_text(style)} over #{message_text(detected_style)}."
end
# rubocop:disable Style/FormatStringToken
def message_text(style)
{
annotated: 'annotated tokens (like `%<foo>s`)',
template: 'template tokens (like `%{foo}`)',
unannotated: 'unannotated tokens (like `%s`)'
}[style]
end
# rubocop:enable Style/FormatStringToken
def tokens(str_node, &block)
return if str_node.source == '__FILE__'
token_ranges(str_contents(str_node.loc), &block)
end
def str_contents(source_map)
if source_map.is_a?(Parser::Source::Map::Heredoc)
source_map.heredoc_body
elsif source_map.begin
source_map.expression.adjust(begin_pos: +1, end_pos: -1)
else
source_map.expression
end
end
def token_ranges(contents)
format_string = RuboCop::Cop::Utils::FormatString.new(contents.source)
format_string.format_sequences.each do |detected_sequence|
next if detected_sequence.percent?
token = contents.begin.adjust(begin_pos: detected_sequence.begin_pos,
end_pos: detected_sequence.end_pos)
yield(detected_sequence, token)
end
end
def collect_detections(node)
detections = []
tokens(node) do |detected_sequence, token_range|
unless unannotated_format?(node, detected_sequence.style)
detections << [detected_sequence, token_range]
end
end
detections
end
def allowed_unannotated?(detections)
return false unless detections.all? do |detected_sequence,|
detected_sequence.style == :unannotated
end
return true if detections.size <= max_unannotated_placeholders_allowed
detections.any? { |detected_sequence,| !correctable_sequence?(detected_sequence.type) }
end
def max_unannotated_placeholders_allowed
cop_config['MaxUnannotatedPlaceholdersAllowed']
end
end
end
end
end