Autocorrect Layout/TrailingBlankLines partially

This commit is contained in:
fn ⌃ ⌥ 2021-10-24 11:58:51 -07:00
parent e5fb0526e0
commit 573881cb8a
2 changed files with 17 additions and 13 deletions

View file

@ -5,28 +5,26 @@ module Ameba::Rule::Layout
describe TrailingBlankLines do
it "passes if there is a blank line at the end of a source" do
source = Source.new "a = 1\n", normalize: false
subject.catch(source).should be_valid
expect_no_issues subject, "a = 1\n", normalize: false
end
it "passes if source is empty" do
source = Source.new ""
subject.catch(source).should be_valid
expect_no_issues subject, ""
end
it "fails if there is no blank lines at the end" do
source = Source.new "no-blankline"
subject.catch(source).should_not be_valid
expect_issue subject, "no-blankline # error: Trailing newline missing"
expect_correction "no-blankline\n"
end
it "fails if there more then one blank line at the end of a source" do
source = Source.new "a = 1\n \n", normalize: false
subject.catch(source).should_not be_valid
expect_issue subject, "a = 1\n \n # error: Excessive trailing newline detected", normalize: false
expect_no_corrections
end
it "fails if last line is not blank" do
source = Source.new "\n\n\n puts 22", normalize: false
subject.catch(source).should_not be_valid
expect_issue subject, "\n\n\n puts 22 # error: Trailing newline missing", normalize: false
expect_correction "\n\n\n puts 22\n"
end
context "when unnecessary blank line has been detected" do
@ -36,7 +34,7 @@ module Ameba::Rule::Layout
issue = source.issues.first
issue.rule.should_not be_nil
issue.location.to_s.should eq "source.cr:2:1"
issue.location.to_s.should eq "source.cr:3:1"
issue.end_location.should be_nil
issue.message.should eq "Excessive trailing newline detected"
end
@ -49,7 +47,7 @@ module Ameba::Rule::Layout
issue = source.issues.first
issue.rule.should_not be_nil
issue.location.to_s.should eq "source.cr:0:1"
issue.location.to_s.should eq "source.cr:1:1"
issue.end_location.should be_nil
issue.message.should eq "Trailing newline missing"
end

View file

@ -25,7 +25,13 @@ module Ameba::Rule::Layout
last_line_empty = last_source_line.empty?
if source_lines_size >= 1 && (source_lines.last(2).join.blank? || !last_line_empty)
issue_for({source_lines_size - 1, 1}, last_line_empty ? MSG : MSG_FINAL_NEWLINE)
if last_line_empty
issue_for({source_lines_size, 1}, MSG)
else
issue_for({source_lines_size, 1}, MSG_FINAL_NEWLINE) do |corrector|
corrector.insert_before({source_lines_size + 1, 1}, '\n')
end
end
end
end
end