diff --git a/changelog/fix_incorrect_autocorrect_for_style_sole_nested_conditional.md b/changelog/fix_incorrect_autocorrect_for_style_sole_nested_conditional.md new file mode 100644 index 00000000000..52a3120b41a --- /dev/null +++ b/changelog/fix_incorrect_autocorrect_for_style_sole_nested_conditional.md @@ -0,0 +1 @@ +* [#10016](https://github.com/rubocop/rubocop/issues/10016): Fix an incorrect auto-correct for `Style/SoleNestedConditional` with `Style/NegatedIf`. ([@koic][]) diff --git a/lib/rubocop/cop/style/sole_nested_conditional.rb b/lib/rubocop/cop/style/sole_nested_conditional.rb index fe40a9eea35..f29f34285f5 100644 --- a/lib/rubocop/cop/style/sole_nested_conditional.rb +++ b/lib/rubocop/cop/style/sole_nested_conditional.rb @@ -38,6 +38,10 @@ class SoleNestedConditional < Base MSG = 'Consider merging nested conditions into outer `%s` conditions.' + def self.autocorrect_incompatible_with + [Style::NegatedIf] + end + def on_if(node) return if node.ternary? || node.else? || node.elsif? diff --git a/spec/rubocop/cli/autocorrect_spec.rb b/spec/rubocop/cli/autocorrect_spec.rb index cea9a62801e..045e32840f4 100644 --- a/spec/rubocop/cli/autocorrect_spec.rb +++ b/spec/rubocop/cli/autocorrect_spec.rb @@ -326,6 +326,26 @@ def foo RUBY end + it 'corrects `Style/SoleNestedConditional` with `Style/NegatedIf`' do + source = <<~RUBY + if !foo.nil? + if foo.do_something == bar + baz + end + end + RUBY + create_file('example.rb', source) + expect(cli.run([ + '--auto-correct-all', + '--only', 'Style/NegatedIf,Style/SoleNestedConditional' + ])).to eq(0) + expect(File.read('example.rb')).to eq(<<~RUBY) + if !foo.nil? && (foo.do_something == bar) + baz + end + RUBY + end + it 'corrects `Style/SoleNestedConditional` with `Style/InverseMethods` and `Style/IfUnlessModifier`' do source = <<~RUBY unless foo.to_s == 'foo'