Class: ERBLint::Linters::FinalNewline

Inherits:
ERBLint::Linter show all
Includes:
ERBLint::LinterRegistry
Defined in:
lib/erb_lint/linters/final_newline.rb

Overview

Checks for final newlines at the end of a file.

Defined Under Namespace

Classes: ConfigSchema

Constant Summary

Constants included from ERBLint::LinterRegistry

ERBLint::LinterRegistry::CUSTOM_LINTERS_DIR

Instance Attribute Summary

Attributes inherited from ERBLint::Linter

#offenses

Instance Method Summary collapse

Methods included from ERBLint::LinterRegistry

clear, find_by_name, included, linters, load_custom_linters

Methods inherited from ERBLint::Linter

#add_offense, #clear_offenses, #enabled?, #excludes_file?, inherited, support_autocorrect?

Constructor Details

#initialize(file_loader, config) ⇒ FinalNewline

Returns a new instance of FinalNewline.



14
15
16
17
# File 'lib/erb_lint/linters/final_newline.rb', line 14

def initialize(file_loader, config)
  super
  @new_lines_should_be_present = @config.present?
end

Instance Method Details

#autocorrect(_processed_source, offense) ⇒ Object



52
53
54
55
56
57
58
59
60
# File 'lib/erb_lint/linters/final_newline.rb', line 52

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

#run(processed_source) ⇒ Object



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
# File 'lib/erb_lint/linters/final_newline.rb', line 19

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