Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't assume first and last comments are aligned #12366

Merged
merged 1 commit into from
Nov 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/fix_false_negative_for_layout_extra_spacing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12366](https://github.com/rubocop/rubocop/pull/12366): Fix a false negative for `Layout/ExtraSpacing` when a file has exactly two comments. ([@eugeneius][])
14 changes: 4 additions & 10 deletions lib/rubocop/cop/layout/extra_spacing.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,19 +49,13 @@ def on_new_investigation

private

def aligned_locations(locs) # rubocop:disable Metrics/AbcSize
def aligned_locations(locs)
return [] if locs.empty?

aligned = Set[locs.first.line, locs.last.line]
locs.each_cons(3) do |before, loc, after|
col = loc.column
aligned << loc.line if col == before.column || col == after.column
aligned = Set.new
locs.each_cons(2) do |loc1, loc2|
aligned << loc1.line << loc2.line if loc1.column == loc2.column
end

# if locs.size > 2 and the size of variable `aligned`
# has not increased from its initial value, there are not aligned lines.
return [] if locs.size > 2 && aligned.size == 2

aligned
end

Expand Down
27 changes: 27 additions & 0 deletions spec/rubocop/cop/layout/extra_spacing_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,33 @@ def method(arg = 1)
end
end

context 'when exactly two comments have extra spaces' do
context 'and they are aligned' do
it 'does not register an offense' do
expect_no_offenses(<<~RUBY)
one # comment one
two # comment two
RUBY
end
end

context 'and they are not aligned' do
it 'registers an offense' do
expect_offense(<<~RUBY)
one # comment one
^ Unnecessary spacing detected.
two # comment two
^^ Unnecessary spacing detected.
RUBY

expect_correction(<<~RUBY)
one # comment one
two # comment two
RUBY
end
end
end

context 'when multiple comments have extra spaces' do
it 'registers offenses for all comments' do
expect_offense(<<~RUBY)
Expand Down