diff --git a/CHANGELOG.md b/CHANGELOG.md index fc579ec8c99..dfd32261b11 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ * [#8213](https://github.com/rubocop-hq/rubocop/pull/8213): Permit to specify TargetRubyVersion 2.8 (experimental). ([@koic][]) * [#8164](https://github.com/rubocop-hq/rubocop/pull/8164): Support auto-correction for `Lint/InterpolationCheck`. ([@koic][]) * [#8223](https://github.com/rubocop-hq/rubocop/pull/8223): Support auto-correction for `Style/IfUnlessModifierOfIfUnless`. ([@koic][]) +* [#8172](https://github.com/rubocop-hq/rubocop/pull/8172): Support auto-correction for `Lint/SafeNavigationWithEmpty`. ([@koic][]) ### Bug fixes diff --git a/config/default.yml b/config/default.yml index 34a2b52e190..7fe860a2748 100644 --- a/config/default.yml +++ b/config/default.yml @@ -1738,6 +1738,7 @@ Lint/SafeNavigationWithEmpty: Description: 'Avoid `foo&.empty?` in conditionals.' Enabled: true VersionAdded: '0.62' + VersionChanged: '0.87' Lint/ScriptPermission: Description: 'Grant script file execute permission.' diff --git a/docs/modules/ROOT/pages/cops_lint.adoc b/docs/modules/ROOT/pages/cops_lint.adoc index 27ca12df0e8..12aacc889de 100644 --- a/docs/modules/ROOT/pages/cops_lint.adoc +++ b/docs/modules/ROOT/pages/cops_lint.adoc @@ -2826,9 +2826,9 @@ foo&.bar && (foobar.baz || foo&.baz) | Enabled | Yes -| No +| Yes | 0.62 -| - +| 0.87 |=== This cop checks to make sure safe navigation isn't used with `empty?` in diff --git a/lib/rubocop/cop/lint/safe_navigation_with_empty.rb b/lib/rubocop/cop/lint/safe_navigation_with_empty.rb index 530684492ad..ca9053c3bbb 100644 --- a/lib/rubocop/cop/lint/safe_navigation_with_empty.rb +++ b/lib/rubocop/cop/lint/safe_navigation_with_empty.rb @@ -32,6 +32,14 @@ def on_if(node) add_offense(node.condition) end + + def autocorrect(node) + lambda do |corrector| + receiver = node.receiver.source + + corrector.replace(node, "#{receiver} && #{receiver}.#{node.method_name}") + end + end end end end diff --git a/spec/rubocop/cop/lint/safe_navigation_with_empty_spec.rb b/spec/rubocop/cop/lint/safe_navigation_with_empty_spec.rb index 2f7688fbc07..691e4fbad2b 100644 --- a/spec/rubocop/cop/lint/safe_navigation_with_empty_spec.rb +++ b/spec/rubocop/cop/lint/safe_navigation_with_empty_spec.rb @@ -4,11 +4,15 @@ subject(:cop) { described_class.new } context 'in a conditional' do - it 'registers an offense on `&.empty?`' do + it 'registers an offense and corrects on `&.empty?`' do expect_offense(<<~RUBY) return unless foo&.empty? ^^^^^^^^^^^ Avoid calling `empty?` with the safe navigation operator in conditionals. RUBY + + expect_correction(<<~RUBY) + return unless foo && foo.empty? + RUBY end it 'does not register an offense on `.empty?`' do