diff --git a/lib/ex_aequo_colors/keywords.ex b/lib/ex_aequo_colors/keywords.ex new file mode 100644 index 0000000..1471ebf --- /dev/null +++ b/lib/ex_aequo_colors/keywords.ex @@ -0,0 +1,30 @@ +defmodule ExAequoColors.Keywords do + @moduledoc ~S""" + Tools to access keywords (to be moved to ExAequoBase) + """ + + @doc ~S""" + + Get first present value from a keyword list + + iex(1)> access_or([a: 1, b: 2], [:b, :a]) + 2 + + iex(2)> access_or([a: 1, b: 2], [:x, :y]) + nil + + or an explicit default + + iex(3)> access_or([a: 1, b: 2], [:x, :y], :not_found) + :not_found + + """ + def access_or(kwd, accessors, default \\ nil) do + accessors + |> Enum.reverse + |> Enum.reduce(default, fn index, result -> + Keyword.get(kwd, index, result) + end) + end +end +# SPDX-License-Identifier: AGPL-3.0-or-later diff --git a/lib/ex_aequo_colors/ui.ex b/lib/ex_aequo_colors/ui.ex new file mode 100644 index 0000000..edd6a17 --- /dev/null +++ b/lib/ex_aequo_colors/ui.ex @@ -0,0 +1,52 @@ +defmodule ExAequoColors.Ui do + @moduledoc ~S""" + Some convenience methods to output colorized messages + """ + + @doc ~S""" + + The error function, by default + + iex(1)> capture_io(fn -> error("OH NO") end) + "\e[31m\e[1mERROR: \e[0mOH NO\n" + + or to a different device + + iex(2)> capture_io(:stderr, fn -> error("OH NO", device: :stderr) end) + "\e[31m\e[1mERROR: \e[0mOH NO\n" + + changing the label? + + iex(3)> capture_io(fn -> error("OH NO", label: "BAD") end) + "\e[31m\e[1mBAD\e[0mOH NO\n" + + """ + def error(message, options \\ []) do + _message(message, :error, "ERROR: ", options) + end + + @doc ~S""" + The warning function, by default + + iex(4)> capture_io(fn -> warning("Watch out!") end) + "\e[33m\e[1mWARNING: \e[0mWatch out!\n" + + """ + def warning(message, options \\ []) do + _message(message, :warning, "WARNING: ", options) + end + + @colors %{ + error: "", + warning: "", + } + + defp _message(message, type, prefix, options) do + device = Keyword.get(options, :device, :stdio) + color = Map.fetch!(@colors, type) + label = Keyword.get(options, :label, prefix) + result = ExAequoColors.Colorizer.colorize(color <> label <> "$" <> message) + IO.puts(device, result) + end +end +# SPDX-License-Identifier: AGPL-3.0-or-later diff --git a/test/keywords_test.exs b/test/keywords_test.exs new file mode 100644 index 0000000..88fe90a --- /dev/null +++ b/test/keywords_test.exs @@ -0,0 +1,6 @@ +defmodule Test.ExAequoColors.KeywordsTest do + use ExUnit.Case + + doctest ExAequoColors.Keywords, import: true +end +# SPDX-License-Identifier: AGPL-3.0-or-later diff --git a/test/ui_test.exs b/test/ui_test.exs new file mode 100644 index 0000000..8e351d7 --- /dev/null +++ b/test/ui_test.exs @@ -0,0 +1,7 @@ +defmodule Test.ExAequoColors.UiTest do + use ExUnit.Case + import ExUnit.CaptureIO + + doctest ExAequoColors.Ui, import: true +end +# SPDX-License-Identifier: AGPL-3.0-or-later