summaryrefslogtreecommitdiff
path: root/lib/irc/parser/numeric.ex
blob: 413f13caa3a05254f860474aa932296869844a32 (plain) (blame)
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
64
65
66
67
68
69
70
71
72
73
defmodule Irc.Parser.Numeric do
  require Logger

  @moduledoc """
  Helpers for using IRC Numerics.

  * Use macros to translate from `rpl_MOTDSTART` (a macro is generated for every numeric name).
  * Convert a numeric to its name (name_numeric())
  * Convert a name to its numeric (to_numeric())
  * Check if a numeric is an error (error_numeric?())

  """

  defmacro __using__(_) do
    quote do
      alias Irc.Parser.Numeric
      require Irc.Parser.Numeric
      import Irc.Parser.Numeric
    end
  end

  @numerics File.read!(Path.join(:code.priv_dir(:irc), "numerics.txt"))
  |> String.split("\n")
  |> Enum.map(fn(line) ->
    case String.split(String.trim(line), " ", parts: 2) do
      ["#"<>_, _] -> nil
      ["#"<>_] -> nil
      [numeric, full_name = "ERR_" <> name] -> {numeric, name, true, full_name}
      [numeric, full_name = "RPL_" <> name] -> {numeric, name, false, full_name}
      line ->
        Logger.debug "Invalid line in numeric.txt: #{inspect line}"
    end
  end)
  |> Enum.filter(fn(n) -> n end)

  for {num, name, error, full_name} <- @numerics do
    prefix = if error, do: "err_", else: "rpl_"
    fname = "#{prefix}#{name}" |> String.to_atom()

    defmacro unquote(fname)() do
      unquote(num)
    end

    def error_numeric?(unquote(num)) do
      unquote(error)
    end
    def error_numeric?(unquote(name)) do
      unquote(error)
    end
    def error_numeric?(unquote(full_name)) do
      unquote(error)
    end

    def name_numeric(unquote(num)) do
      unquote(full_name)
    end

    def to_numeric(unquote(num)) do
      unquote(num)
    end
    def to_numeric(unquote(name)) do
      unquote(num)
    end
    def to_numeric(unquote(fname)) do
      unquote(num)
    end
    def to_numeric(unquote(full_name)) do
      unquote(num)
    end

  end

end