Skip to content

Commit

Permalink
[Fix rubocop#11069] Fix an incorrect autocorrect for `Lint/RedundantC…
Browse files Browse the repository at this point in the history
…opDisableDirective`

Fix rubocop#11069.

This PR fixes an incorrect autocorrect for `Lint/RedundantCopDisableDirective`
when disable directive contains free comment.
  • Loading branch information
koic committed Oct 13, 2022
1 parent f7d18fd commit 972d810
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#11069](https://github.com/rubocop/rubocop/issues/11069): Fix an incorrect autocorrect for `Lint/RedundantCopDisableDirective` when disable directive contains free comment. ([@koic][])
13 changes: 12 additions & 1 deletion lib/rubocop/cop/lint/redundant_cop_disable_directive.rb
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,12 @@ def add_offense_for_entire_comment(comment, cops)

add_offense(location, message: message(cop_names)) do |corrector|
range = comment_range_with_surrounding_space(location, comment.loc.expression)
corrector.remove(range)

if leave_free_comment?(comment, range)
corrector.replace(range, ' # ')
else
corrector.remove(range)
end
end
end

Expand All @@ -227,6 +232,12 @@ def add_offense_for_some_cops(comment, cops)
end
end

def leave_free_comment?(comment, range)
free_comment = comment.text.gsub(range.source.strip, '')

!free_comment.empty? && !free_comment.start_with?('#')
end

def cop_range(comment, cop)
cop = remove_department_marker(cop)
matching_range(comment.loc.expression, cop) ||
Expand Down
17 changes: 17 additions & 0 deletions spec/rubocop/cop/lint/redundant_cop_disable_directive_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,23 @@ def bar
RUBY
end

it 'removes cop duplicated by department and leaves free text as a comment' do
expect_offense(<<~RUBY)
# rubocop:disable Metrics
def bar
do_something # rubocop:disable Metrics/ClassLength - note
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Unnecessary disabling of `Metrics/ClassLength`.
end
RUBY

expect_correction(<<~RUBY)
# rubocop:disable Metrics
def bar
do_something # - note
end
RUBY
end

it 'does not remove correct department' do
expect_no_offenses(<<~RUBY)
# rubocop:disable Metrics
Expand Down

0 comments on commit 972d810

Please sign in to comment.