Skip to content

Commit

Permalink
[rubocop#1117] Correct indentation around block comments
Browse files Browse the repository at this point in the history
The earlier solution simply avoided auto-correcting every node that
contains a block comment. This solution indents as usual but leaves
block comments untouched.
  • Loading branch information
buehmann committed Jul 6, 2019
1 parent 4038ff5 commit 154dacb
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 14 deletions.
15 changes: 10 additions & 5 deletions lib/rubocop/cop/correctors/alignment_corrector.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ def correct(processed_source, node, column_delta)

@processed_source = processed_source
expr = node.respond_to?(:loc) ? node.loc.expression : node
return if block_comment_within?(expr)

taboo_ranges = inside_string_ranges(node)
taboo_ranges = inside_string_ranges(node) +
block_comment_ranges

lambda do |corrector|
each_line(expr) do |line_begin_pos|
Expand Down Expand Up @@ -79,9 +79,14 @@ def inside_regular_string_range(node)
loc.begin.end.join(loc.end.begin)
end

def block_comment_within?(expr)
processed_source.comments.select(&:document?).any? do |c|
within?(c.loc.expression, expr)
def block_comment_ranges
processed_source.comments.select(&:document?).map do |c|
range = c.loc.expression
if range.source.end_with?("\n")
range.adjust(end_pos: -1)
else
range
end
end
end

Expand Down
26 changes: 26 additions & 0 deletions spec/rubocop/cop/alignment_corrector_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -115,5 +115,31 @@
OUTPUT
end
end

context 'with block comments' do
it 'does not indent block comments' do
expect(autocorrect_source(<<~INPUT)).to eq(<<~OUTPUT)
# >> 2
begin
bar
=begin
Ancient
comment
=end
baz
end
INPUT
# >> 2
begin
bar
=begin
Ancient
comment
=end
baz
end
OUTPUT
end
end
end
end
25 changes: 16 additions & 9 deletions spec/rubocop/cop/layout/indentation_width_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -248,27 +248,34 @@ class Test
RUBY
end

it 'does not correct in scopes that contain block comments' do
it 'does not indent block comments' do
source = <<~RUBY
module Foo
# The class has a block comment within, so it's not corrected.
class Bar
=begin
This is a nice long
comment
which spans a few lines
and must not be indented
=end
# The method has no block comment inside,
# but it's within a class that has a block
# comment, so it's not corrected either.
def baz
do_something
end
do_something # indented
end
end
RUBY

expect(autocorrect_source(source)).to eq source
expect(autocorrect_source(source)).to eq <<~RUBY
module Foo
class Bar
=begin
This is a nice long
comment
which spans a few lines
and must not be indented
=end
do_something # indented
end
end
RUBY
end

it 'does not indent heredoc strings' do
Expand Down

0 comments on commit 154dacb

Please sign in to comment.