From 3c97e4aeb51970659b4e89f63c66e3c804954152 Mon Sep 17 00:00:00 2001 From: Daniel Vandersluis Date: Mon, 16 Aug 2021 16:34:56 -0400 Subject: [PATCH] [Fix #10016] Fix conflict between `Style/SoleNestedConditional` and `Style/NegatedIf`/`Style/NegatedUnless`. --- changelog/fix_fix_conflict_between.md | 1 + .../cop/style/sole_nested_conditional.rb | 4 +++ spec/rubocop/cli/autocorrect_spec.rb | 34 +++++++++++++++++++ 3 files changed, 39 insertions(+) create mode 100644 changelog/fix_fix_conflict_between.md diff --git a/changelog/fix_fix_conflict_between.md b/changelog/fix_fix_conflict_between.md new file mode 100644 index 00000000000..fb317aa442a --- /dev/null +++ b/changelog/fix_fix_conflict_between.md @@ -0,0 +1 @@ +* [#10016](https://github.com/rubocop/rubocop/issues/10016): Fix conflict between `Style/SoleNestedConditional` and `Style/NegatedIf`/`Style/NegatedUnless`. ([@dvandersluis][]) diff --git a/lib/rubocop/cop/style/sole_nested_conditional.rb b/lib/rubocop/cop/style/sole_nested_conditional.rb index fe40a9eea35..e1cdf4fcf55 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, Style::NegatedUnless] + 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..543e9698b8c 100644 --- a/spec/rubocop/cli/autocorrect_spec.rb +++ b/spec/rubocop/cli/autocorrect_spec.rb @@ -2192,4 +2192,38 @@ def foo(a) end RUBY end + + it 'properly corrects when `Style/SoleNestedConditional` and one of '\ + '`Style/NegatedIf` or `Style/NegatedUnless` detect offenses' do + source_file = Pathname('example.rb') + create_file(source_file, <<~RUBY) + if !foo? + if bar? + do_something + end + end + + unless !foo? + if bar? + do_something + end + end + RUBY + + status = cli.run( + %w[--auto-correct --only] << %w[ + NegatedIf NegatedUnless SoleNestedConditional + ].join(',') + ) + expect(status).to eq(0) + expect(source_file.read).to eq(<<~RUBY) + if !foo? && bar? + do_something + end + + if !!foo? && bar? + do_something + end + RUBY + end end