This repository has been archived by the owner on Mar 4, 2022. It is now read-only.
forked from Shopify/erb_lint
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfinal_newline.rb
63 lines (55 loc) · 1.93 KB
/
final_newline.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# frozen_string_literal: true
module ERBLint
module Linters
# Checks for final newlines at the end of a file.
class FinalNewline < Linter
include LinterRegistry
class ConfigSchema < LinterConfig
property :present, accepts: [true, false], default: true, reader: :present?
end
self.config_schema = ConfigSchema
def initialize(file_loader, config)
super
@new_lines_should_be_present = @config.present?
end
def run(processed_source)
file_content = processed_source.file_content
return if file_content.empty?
match = file_content.match(/(\n+)\z/)
final_newline = match&.captures&.first || ""
if @new_lines_should_be_present && final_newline.size != 1
if final_newline.empty?
add_offense(
processed_source.to_source_range(file_content.size...file_content.size),
'Missing a trailing newline at the end of the file.',
:insert
)
else
add_offense(
processed_source.to_source_range(
(file_content.size - final_newline.size + 1)...file_content.size
),
'Remove multiple trailing newline at the end of the file.',
:remove
)
end
elsif !@new_lines_should_be_present && !final_newline.empty?
add_offense(
processed_source.to_source_range(match.begin(0)...match.end(0)),
"Remove #{final_newline.size} trailing newline at the end of the file.",
:remove
)
end
end
def autocorrect(_processed_source, offense)
lambda do |corrector|
if offense.context == :insert
corrector.insert_after(offense.source_range, "\n")
else
corrector.remove_trailing(offense.source_range, offense.source_range.size)
end
end
end
end
end
end