Skip to content

Commit

Permalink
handle autocorrect exception in Style/BlockComments
Browse files Browse the repository at this point in the history
When a file ends with `=end` and does not have a final newline, the
autocorrect code of Style/BlockComments was producing an exception.
This change handles the exception and adds a final newline.
  • Loading branch information
ericsullivan committed Mar 22, 2019
1 parent 2df1e20 commit 1537862
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -4,6 +4,7 @@

### Bug fixes
* [#6855](https://github.com/rubocop-hq/rubocop/pull/6855): Fix an exception in `Rails/RedundantReceiverInWithOptions` when the body is empty. ([@ericsullivan][])
* [#6856](https://github.com/rubocop-hq/rubocop/pull/6856): Fix auto-correction for `Style/BlockComments` when the file is missing a trailing blank line. ([@ericsullivan][])

### Changes

Expand Down
10 changes: 9 additions & 1 deletion lib/rubocop/cop/style/block_comments.rb
Expand Up @@ -52,10 +52,18 @@ def autocorrect(comment)
def parts(comment)
expr = comment.loc.expression
eq_begin = expr.resize(BEGIN_LENGTH)
eq_end = range_between(expr.end_pos - END_LENGTH, expr.end_pos)
eq_end = eq_end_part(comment, expr)
contents = range_between(eq_begin.end_pos, eq_end.begin_pos)
[eq_begin, eq_end, contents]
end

def eq_end_part(comment, expr)
if comment.text.chomp == comment.text
range_between(expr.end_pos - END_LENGTH - 1, expr.end_pos - 2)
else
range_between(expr.end_pos - END_LENGTH, expr.end_pos)
end
end
end
end
end
Expand Down
21 changes: 21 additions & 0 deletions spec/rubocop/cop/style/block_comments_spec.rb
Expand Up @@ -47,4 +47,25 @@ def foo
end
RUBY
end

it 'auto-corrects a block comment into a regular comment (without trailing' \
'newline)' do
source = <<-RUBY.strip_indent
=begin
comment line 1
comment line 2
=end
RUBY

new_source = autocorrect_source(source.chomp)

expected_source = <<-RUBY.strip_indent
# comment line 1
#
# comment line 2
RUBY

expect(new_source).to eq(expected_source)
end
end

0 comments on commit 1537862

Please sign in to comment.