From 45da59a2f17f494f38d911091b91c4542003a49d Mon Sep 17 00:00:00 2001 From: Szymon Soczewka Date: Wed, 2 Nov 2022 09:37:45 +0100 Subject: [PATCH] [Fix #11123 ] Fix auto correction bug for Style/StringLiterals --- changelog/fix_auto_correction_bug_for_string_literals.md | 1 + lib/rubocop/cop/style/quoted_symbols.rb | 2 +- lib/rubocop/cop/util.rb | 2 +- spec/rubocop/cop/style/string_literals_spec.rb | 3 +++ 4 files changed, 6 insertions(+), 2 deletions(-) create mode 100644 changelog/fix_auto_correction_bug_for_string_literals.md diff --git a/changelog/fix_auto_correction_bug_for_string_literals.md b/changelog/fix_auto_correction_bug_for_string_literals.md new file mode 100644 index 00000000000..53471eedcaa --- /dev/null +++ b/changelog/fix_auto_correction_bug_for_string_literals.md @@ -0,0 +1 @@ +* [#11123](https://github.com/rubocop/rubocop/issues/11123): Fix autocorrection bug for `Style/StringLiterals` when using multiple escape characters. ([@si-lens][]) diff --git a/lib/rubocop/cop/style/quoted_symbols.rb b/lib/rubocop/cop/style/quoted_symbols.rb index cfd9f3397bf..7dabc26e665 100644 --- a/lib/rubocop/cop/style/quoted_symbols.rb +++ b/lib/rubocop/cop/style/quoted_symbols.rb @@ -93,7 +93,7 @@ def correct_quotes(str) end # The conversion process doubles escaped slashes, so they have to be reverted - correction.gsub('\\\\', '\\') + correction.gsub('\\\\', '\\').gsub('\"', '"') end def style diff --git a/lib/rubocop/cop/util.rb b/lib/rubocop/cop/util.rb index 9b0200bd48a..0d7e7d29e4f 100644 --- a/lib/rubocop/cop/util.rb +++ b/lib/rubocop/cop/util.rb @@ -122,7 +122,7 @@ def to_string_literal(string) string.inspect else # In a single-quoted strings, double quotes don't need to be escaped - "'#{string.gsub('\"', '"').gsub('\\') { '\\\\' }}'" + "'#{string.gsub('\\') { '\\\\' }.gsub('\"', '"')}'" end end diff --git a/spec/rubocop/cop/style/string_literals_spec.rb b/spec/rubocop/cop/style/string_literals_spec.rb index c780bd8a768..c639ef4f8d6 100644 --- a/spec/rubocop/cop/style/string_literals_spec.rb +++ b/spec/rubocop/cop/style/string_literals_spec.rb @@ -14,6 +14,8 @@ ^^^^^ Prefer single-quoted strings when you don't need string interpolation or special symbols. z = "a\\" ^^^^^ Prefer single-quoted strings when you don't need string interpolation or special symbols. + t = "{\"[\\\"*\\\"]\"" + ^^^^^^^^^^^^^^^^^^ Prefer single-quoted strings when you don't need string interpolation or special symbols. RUBY expect(cop.config_to_allow_offenses).to eq('EnforcedStyle' => 'double_quotes') @@ -22,6 +24,7 @@ x = 'a\\b' y ='\\b' z = 'a\\' + t = '{"[\"*\"]"' RUBY end