Skip to content

Commit

Permalink
Make Style/RedundantPercentQ handle multiline source safely
Browse files Browse the repository at this point in the history
  • Loading branch information
boardfish committed Mar 13, 2024
1 parent e93a1f0 commit fe704f3
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

* [#12780](https://github.com/rubocop/rubocop/pulls/12784): Mark `Style/RedundantPercentQ` as unsafe autocorrect ([@boardfish][])
6 changes: 5 additions & 1 deletion lib/rubocop/cop/style/redundant_percent_q.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,17 @@ def check(node)
return if interpolated_quotes?(node) || allowed_percent_q?(node)

add_offense(node) do |corrector|
delimiter = /^%Q[^"]+$|'/.match?(node.source) ? QUOTE : SINGLE_QUOTE
delimiter = delimiter_for(node.source)

corrector.replace(node.loc.begin, delimiter)
corrector.replace(node.loc.end, delimiter)
end
end

def delimiter_for(source)
/\A%Q[^"]+\z|'/.match?(source) ? QUOTE : SINGLE_QUOTE
end

def interpolated_quotes?(node)
node.source.include?(SINGLE_QUOTE) && node.source.include?(QUOTE)
end
Expand Down
15 changes: 15 additions & 0 deletions spec/rubocop/cop/style/redundant_percent_q_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,21 @@
'boogers'
RUBY
end

it 'autocorrects safely for strings containing Ruby 1.6 hash syntax' do
expect_offense(<<~'RUBY')
%Q(
^^^ Use `%Q` only for strings that contain both single [...]
{ "foo" => "bar" }
)
RUBY

expect_correction(<<~'RUBY')
'
{ "foo" => "bar" }
'
RUBY
end
end

it 'accepts a heredoc string that contains %q' do
Expand Down

0 comments on commit fe704f3

Please sign in to comment.