Skip to content

Commit

Permalink
Fix a false positive for Style/StringLiterals
Browse files Browse the repository at this point in the history
Follow up to rubocop#10166 (comment).

This PR fixes a false positive for `Style/StringLiterals` when `EnforcedStyle: double_quotes`
and using single quoted string with backslash.
It has moved a separate implementation for `Style/QuotedSymbols` to resolve rubocop#10152 to
`Style/QuotedSymbols` to prevent impact on `Style/StringLiterals`'s false positives.
  • Loading branch information
koic committed Nov 2, 2021
1 parent 48e163d commit b2fe007
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 6 deletions.
@@ -0,0 +1 @@
* [#10229](https://github.com/rubocop/rubocop/pull/10229): Fix a false positive for `Style/StringLiterals` when `EnforcedStyle: double_quotes` and using single quoted string with backslash. ([@koic][])
6 changes: 1 addition & 5 deletions lib/rubocop/cop/mixin/string_literals_help.rb
Expand Up @@ -13,11 +13,7 @@ def wrong_quotes?(src_or_node)
if style == :single_quotes
!double_quotes_required?(src)
else
# The string needs single quotes if:
# 1. It contains a double quote
# 2. It contains text that would become an escape sequence with double quotes
# 3. It contains text that would become an interpolation with double quotes
!/" | (?<!\\)\\[aAbcdefkMnprsStuUxzZ0-7] | \#[@{$]/x.match?(src)
!/" | \\[^'\\] | \#[@{$]/x.match?(src)
end
end
end
Expand Down
12 changes: 11 additions & 1 deletion lib/rubocop/cop/style/quoted_symbols.rb
Expand Up @@ -46,7 +46,7 @@ def on_sym(node)

message = style == :single_quotes ? MSG_SINGLE : MSG_DOUBLE

if wrong_quotes?(node)
if wrong_quotes?(node) || invalid_double_quotes?(node.source)
add_offense(node, message: message) do |corrector|
opposite_style_detected
autocorrect(corrector, node)
Expand All @@ -58,6 +58,16 @@ def on_sym(node)

private

def invalid_double_quotes?(source)
return false unless style == :double_quotes

# The string needs single quotes if:
# 1. It contains a double quote
# 2. It contains text that would become an escape sequence with double quotes
# 3. It contains text that would become an interpolation with double quotes
!/" | (?<!\\)\\[aAbcdefkMnprsStuUxzZ0-7] | \#[@{$]/x.match?(source)
end

def autocorrect(corrector, node)
str = if hash_colon_key?(node)
# strip quotes
Expand Down
8 changes: 8 additions & 0 deletions spec/rubocop/cop/style/string_literals_spec.rb
Expand Up @@ -254,6 +254,14 @@
expect_no_offenses('a = %(x)')
end

it 'accepts single quoted string with backslash' do
expect_no_offenses(<<~'RUBY')
'\,'
'100\%'
'(\)'
RUBY
end

it 'accepts heredocs' do
expect_no_offenses(<<~RUBY)
execute <<-SQL
Expand Down

0 comments on commit b2fe007

Please sign in to comment.