diff --git a/CHANGELOG.md b/CHANGELOG.md index 7878f11ff78..c40ce950cd4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ * [#8323](https://github.com/rubocop-hq/rubocop/issues/8323): Fix a false positive for `Style/HashAsLastArrayItem` when hash is not a last array item. ([@fatkodima][]) * [#8299](https://github.com/rubocop-hq/rubocop/issues/8299): Fix an incorrect auto-correct for `Style/RedundantCondition` when using `raise`, `rescue`, or `and` without argument parentheses in `else`. ([@koic][]) * [#8335](https://github.com/rubocop-hq/rubocop/issues/8335): Fix incorrect character class detection for nested or POSIX bracket character classes in `Style/RedundantRegexpEscape`. ([@owst][]) +* [#8347](https://github.com/rubocop-hq/rubocop/issues/8347): Fix an incorrect auto-correct for `EnforcedStyle: hash_rockets` of `Style/HashSyntax` with `Layout/HashAlignment`. ([@koic][]) ### Changes diff --git a/lib/rubocop/cop/style/hash_syntax.rb b/lib/rubocop/cop/style/hash_syntax.rb index 65d6fbf661d..a28b2adf389 100644 --- a/lib/rubocop/cop/style/hash_syntax.rb +++ b/lib/rubocop/cop/style/hash_syntax.rb @@ -199,7 +199,8 @@ def argument_without_space?(node) def autocorrect_hash_rockets(corrector, pair_node) op = pair_node.loc.operator - corrector.wrap(pair_node.key, ':', pair_node.inverse_delimiter(true)) + key_with_hash_rocket = ":#{pair_node.key.source}#{pair_node.inverse_delimiter(true)}" + corrector.replace(pair_node.key, key_with_hash_rocket) corrector.remove(range_with_surrounding_space(range: op)) end diff --git a/spec/rubocop/cli/cli_autocorrect_spec.rb b/spec/rubocop/cli/cli_autocorrect_spec.rb index 410a83b08fb..ac17ceaf361 100644 --- a/spec/rubocop/cli/cli_autocorrect_spec.rb +++ b/spec/rubocop/cli/cli_autocorrect_spec.rb @@ -174,6 +174,28 @@ def batch RUBY end + it 'corrects `EnforcedStyle: hash_rockets` of `Style/HashSyntax` with `Layout/HashAlignment`' do + create_file('.rubocop.yml', <<~YAML) + Style/HashSyntax: + EnforcedStyle: hash_rockets + YAML + source = <<~RUBY + some_method(a: 'abc', b: 'abc', + c: 'abc', d: 'abc' + ) + RUBY + create_file('example.rb', source) + expect(cli.run([ + '--auto-correct-all', + '--only', 'Style/HashSyntax,Style/HashAlignment' + ])).to eq(0) + expect(IO.read('example.rb')).to eq(<<~RUBY) + some_method(:a => 'abc', :b => 'abc', + :c => 'abc', :d => 'abc' + ) + RUBY + end + describe 'trailing comma cops' do let(:source) do <<~RUBY