Class: ERBLint::Linters::SelfClosingTag

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

Overview

Warns when a tag is not self-closed properly.

Defined Under Namespace

Classes: ConfigSchema

Constant Summary collapse

SELF_CLOSING_TAGS =
[
  "area",
  "base",
  "br",
  "col",
  "command",
  "embed",
  "hr",
  "input",
  "keygen",
  "link",
  "menuitem",
  "meta",
  "param",
  "source",
  "track",
  "wbr",
  "img",
]

Constants included from ERBLint::LinterRegistry

ERBLint::LinterRegistry::CUSTOM_LINTERS_DIR, ERBLint::LinterRegistry::DEPRECATED_CUSTOM_LINTERS_DIR

Instance Attribute Summary

Attributes inherited from ERBLint::Linter

#config, #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, #initialize, #run_and_update_offense_status, support_autocorrect?

Constructor Details

This class inherits a constructor from ERBLint::Linter

Instance Method Details

#autocorrect(_processed_source, offense) ⇒ Object



67
68
69
70
71
# File 'lib/erb_lint/linters/self_closing_tag.rb', line 67

def autocorrect(_processed_source, offense)
  lambda do |corrector|
    corrector.replace(offense.source_range, offense.context)
  end
end

#run(processed_source) ⇒ Object



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
64
65
# File 'lib/erb_lint/linters/self_closing_tag.rb', line 34

def run(processed_source)
  processed_source.ast.descendants(:tag).each do |tag_node|
    tag = BetterHtml::Tree::Tag.from_node(tag_node)
    next unless SELF_CLOSING_TAGS.include?(tag.name)

    if tag.closing?
      start_solidus = tag_node.children.first
      add_offense(
        start_solidus.loc,
        "Tag `#{tag.name}` is a void element, it must not start with `</`.",
        "",
      )
    end

    if @config.enforced_style == :always && !tag.self_closing?
      add_offense(
        tag_node.loc.end.offset(-1),
        "Tag `#{tag.name}` is self-closing, it must end with `/>`.",
        "/",
      )
    end

    next unless @config.enforced_style == :never && tag.self_closing?

    end_solidus = tag_node.children.last
    add_offense(
      end_solidus.loc,
      "Tag `#{tag.name}` is a void element, it must end with `>` and not `/>`.",
      "",
    )
  end
end