From 15378621d578384fd11201ad218251648252afc3 Mon Sep 17 00:00:00 2001 From: Eric Sullivan Date: Thu, 21 Mar 2019 10:31:21 -0400 Subject: [PATCH] handle autocorrect exception in Style/BlockComments 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. --- CHANGELOG.md | 1 + lib/rubocop/cop/style/block_comments.rb | 10 ++++++++- spec/rubocop/cop/style/block_comments_spec.rb | 21 +++++++++++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c1e9a5e5194..4fa4c46fe2f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/lib/rubocop/cop/style/block_comments.rb b/lib/rubocop/cop/style/block_comments.rb index 64b5a9a02f5..c54a402f7a1 100644 --- a/lib/rubocop/cop/style/block_comments.rb +++ b/lib/rubocop/cop/style/block_comments.rb @@ -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 diff --git a/spec/rubocop/cop/style/block_comments_spec.rb b/spec/rubocop/cop/style/block_comments_spec.rb index b4943a6f40a..c5f811885e2 100644 --- a/spec/rubocop/cop/style/block_comments_spec.rb +++ b/spec/rubocop/cop/style/block_comments_spec.rb @@ -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