module SCSSLint
  class Linter::HexFormat < Linter
    include LinterRegistry

    def visit_prop(node)
      if node.value.is_a?(Sass::Script::String) &&
         node.value.type == :identifier

        node.value.value.scan(HEX_REGEX) do |match|
          add_hex_lint(node, match.first) unless valid_hex_format?(match.first)
        end
      end

      yield # Continue visiting children
    end

    def visit_script_color(node)
      return unless node.original && node.original.match(HEX_REGEX)

      unless valid_hex_format?(node.original[HEX_REGEX, 1])
        add_hex_lint(node, node.original)
      end
    end

  private

    HEX_REGEX = /(#\h{3,6})/

    def add_hex_lint(node, hex)
      add_lint(node, "Color `#{hex}` should be written as `#{shortest_hex_form(hex)}`")
    end

    def valid_hex_format?(hex)
      hex == shortest_hex_form(hex)
    end
  end
end

module SCSSLint
  class Linter::HexFormat < Linter
    include LinterRegistry

    def visit_script_color(node)
      return unless node.original && node.original.match(HEX_REGEX)

      unless valid_hex_format?(node.original[HEX_REGEX, 1])
        add_hex_lint(node, node.original)
      end
    end

    def visit_script_string(node)
      return unless node.type == :identifier

      node.value.scan(HEX_REGEX) do |match|
        add_hex_lint(node, match.first) unless valid_hex_format?(match.first)
      end
    end

  private

    HEX_REGEX = /(#\h{3,6})/

    def add_hex_lint(node, hex)
      add_lint(node, "Color `#{hex}` should be written as `#{shortest_hex_form(hex)}`")
    end

    def valid_hex_format?(hex)
      hex == shortest_hex_form(hex)
    end
  end
end

Simplify HexFormat linter string searching
Simplify HexFormat linter string searching

The `HexFormat` linter was using `visit_prop` with a manual check to see
if the value of the property was a `Sass::Script::String`, rather than
just using `visit_script_string`.

Switching to `visit_script_string` simplifies the code.

Change-Id: I84a64b97071b74d9d37ff40360f4683a2e557368
Reviewed-on: https://gerrit.causes.com/29015
Tested-by: jenkins <d95b56ce41a2e1ac4cecdd398defd7414407cc08@causes.com>
Reviewed-by: Shane da Silva <6f6e68d1df92f30cb4b3ce35260ddf94a402f33d@causes.com>
