| 1 |
|
defmodule Log do |
| 2 |
|
import IO, only: [puts: 1] |
| 3 |
|
import Path, only: [join: 2] |
| 4 |
|
import String, only: [contains?: 2] |
| 5 |
|
import System, only: [pid: 0, get_env: 2] |
| 6 |
|
import Utils.Yaml, only: [yaml: 1] |
| 7 |
|
import File, only: [mkdir_p!: 1, write: 3] |
| 8 |
|
|
| 9 |
|
@colors %{ |
| 10 |
|
green: 82, |
| 11 |
|
white: 255, |
| 12 |
|
blue: 33, |
| 13 |
|
yellow: 226, |
| 14 |
|
red: 196 |
| 15 |
|
} |
| 16 |
|
|
| 17 |
93 |
def log(emoji, head, neck, body, color) do |
| 18 |
93 |
msg = message(head, neck, yaml(body)) |
| 19 |
93 |
emit(emoji, msg, color) |
| 20 |
|
rescue |
| 21 |
93 |
_ in [File.Error, ErlangError] -> :ok |
| 22 |
|
end |
| 23 |
|
|
| 24 |
|
defp emit(emoji, msg, color) do |
| 25 |
93 |
puts("\e[38;5;#{@colors[color]}m#{emoji} #{msg}\e[0m") |
| 26 |
:-( |
dir() |> mkdir_p!() |> append("#{emoji} #{msg}") |
| 27 |
|
end |
| 28 |
|
|
| 29 |
|
defp emit(emoji, msg, color, agent) do |
| 30 |
245 |
puts("\e[38;5;#{@colors[color]}m#{emoji} #{msg}\e[0m") |
| 31 |
4 |
dir() |> mkdir_p!() |
| 32 |
4 |
write(path(agent), "#{emoji} #{msg}\n", [:append]) |
| 33 |
|
end |
| 34 |
|
|
| 35 |
|
defp message(head, neck, body) do |
| 36 |
338 |
"#{head}#{neck <> eol(body)}#{body}" |
| 37 |
|
end |
| 38 |
|
|
| 39 |
245 |
def agent(emoji, head, neck, body, config) when is_map(config) do |
| 40 |
245 |
msg = message(head, neck, yaml(body)) |
| 41 |
245 |
emit(emoji, msg, Map.get(config, :color, :green), Map.get(config, :name)) |
| 42 |
|
rescue |
| 43 |
241 |
_ in [File.Error, ErlangError] -> :ok |
| 44 |
|
end |
| 45 |
|
|
| 46 |
135 |
def write(message) do |
| 47 |
135 |
dir() |> mkdir_p!() |> ensure(message) |
| 48 |
|
rescue |
| 49 |
131 |
_ in [File.Error, ErlangError] -> :ok |
| 50 |
|
end |
| 51 |
|
|
| 52 |
135 |
def trace(message) do |
| 53 |
135 |
dir() |> mkdir_p!() |
| 54 |
135 |
write(target(), message <> "\n", [:append]) |
| 55 |
|
rescue |
| 56 |
:-( |
_ in [File.Error, ErlangError] -> :ok |
| 57 |
|
end |
| 58 |
|
|
| 59 |
|
defp ensure(_dir, message) do |
| 60 |
135 |
write(path("elita"), message, [:append]) |
| 61 |
135 |
puts(message) |
| 62 |
|
end |
| 63 |
|
|
| 64 |
|
defp append(_dir, message) do |
| 65 |
:-( |
write(path("elita"), message <> "\n", [:append]) |
| 66 |
|
end |
| 67 |
|
|
| 68 |
|
defp eol(body) do |
| 69 |
338 |
body |> newline() |> char() |
| 70 |
|
end |
| 71 |
|
|
| 72 |
|
defp newline(body) do |
| 73 |
338 |
contains?(body, "\n") |
| 74 |
|
end |
| 75 |
|
|
| 76 |
148 |
defp char(true), do: "\n" |
| 77 |
190 |
defp char(false), do: "" |
| 78 |
|
|
| 79 |
|
defp path(name) do |
| 80 |
139 |
join(dir(), "#{name}_#{pid()}.log") |
| 81 |
|
end |
| 82 |
|
|
| 83 |
|
defp target do |
| 84 |
135 |
join(dir(), "elita_#{pid()}.trace") |
| 85 |
|
end |
| 86 |
|
|
| 87 |
|
defp dir do |
| 88 |
548 |
join(get_env("HOME", "~"), ".elita/sessions") |
| 89 |
|
end |
| 90 |
|
end |