Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix a false positive for Style/StringLiterals #10229

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -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