Skip to content

Instantly share code, notes, and snippets.

@mdg
Created January 5, 2018 22:14
Show Gist options
  • Save mdg/8e2cd84baecb6d31c1e401e8d19cd816 to your computer and use it in GitHub Desktop.
Save mdg/8e2cd84baecb6d31c1e401e8d19cd816 to your computer and use it in GitHub Desktop.
use Dogma.RuleBuilder
defrule Dogma.Rule.FnParens, [] do
@moduledoc """
A rule that enforces using parens in a fn that takes parens
"""
@fn_pattern ~r/fn(\s*)(\(|->)?/
def test(rule, script) do
script.processed_lines
|> Enum.filter(fn(line) -> check_line(rule, line) end)
|> Enum.map(fn(line) -> error(rule, line) end)
end
defp check_line(rule, {pos, line}) do
@fn_pattern
|> Regex.scan(line)
|> Enum.map(&(check_matches(rule, pos, &1)))
|> Enum.reject(fn(r) -> r === :ok end)
end
defp check_matches(rule, pos, [_full, spaces]) do
error(pos, "Parens required for fn with params")
end
defp check_matches(rule, pos, [_full, " ", "->"]), do: :ok
defp check_matches(rule, pos, [_full, other_spacing, "->"]) do
error(pos, "1 space required between fn and ->")
end
defp check_matches(rule, pos, [_full, "", "("]), do: :ok
defp check_matches(rule, pos, [_full, other_spacing, "("]) do
error(pos, "No space allowed between fn and (")
end
defp check_matches(_, pos, _) do
error(pos, "Bad pattern check, halp")
end
defp error(pos, error_msg) do
%Error{
rule: __MODULE__,
message: error_msg,
line: Dogma.Script.line(15), # pos),
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment