ui.ex (2614B)
1 defmodule Credo.CLI.Output.UI do 2 @moduledoc """ 3 This module provides functions used to create the UI. 4 5 >>> alias Credo.CLI.Output.UI 6 >>> UI.puts "This is a test." 7 This is a test. 8 nil 9 10 >>> alias Credo.CLI.Output.UI 11 >>> UI.warn "This is a warning." 12 This is a warning. 13 nil 14 15 """ 16 17 @edge "┃" 18 @ellipsis "…" 19 @shell_service Credo.CLI.Output.Shell 20 21 if Mix.env() == :test do 22 def puts, do: nil 23 def puts(_), do: nil 24 def puts(_, color) when is_atom(color), do: nil 25 26 def warn(_), do: nil 27 else 28 defdelegate puts, to: @shell_service 29 defdelegate puts(v), to: @shell_service 30 31 def puts(v, color) when is_atom(color) do 32 @shell_service.puts([color, v]) 33 end 34 35 defdelegate warn(v), to: @shell_service 36 end 37 38 def edge(color, indent \\ 2) when is_integer(indent) do 39 [:reset, color, @edge |> String.pad_trailing(indent)] 40 end 41 42 @doc "Returns the edge (`┃`) which is used in much of Credo's output as a binary." 43 def edge, do: @edge 44 45 def use_colors(exec) do 46 @shell_service.use_colors(exec.color) 47 48 exec 49 end 50 51 def puts_edge(color, indent \\ 2) when is_integer(indent) do 52 color 53 |> edge(indent) 54 |> puts 55 end 56 57 def wrap_at(text, number) do 58 "(?:((?>.{1,#{number}}(?:(?<=[^\\S\\r\\n])[^\\S\\r\\n]?|(?=\\r?\\n)|$|[^\\S\\r\\n]))|.{1,#{number}})(?:\\r?\\n)?|(?:\\r?\\n|$))" 59 |> Regex.compile!("u") 60 |> Regex.scan(text) 61 |> Enum.map(&List.first/1) 62 |> List.delete_at(-1) 63 end 64 65 @doc """ 66 Truncate a line to fit within a specified maximum length. 67 Truncation is indicated by a trailing ellipsis (…), and you can override this 68 using an optional third argument. 69 70 iex> Credo.CLI.Output.UI.truncate(nil, 7) 71 "" 72 iex> Credo.CLI.Output.UI.truncate(" 7 chars\\n", 7) 73 " 7 ch…" 74 iex> Credo.CLI.Output.UI.truncate(" more than 7\\n", 7) 75 " more…" 76 iex> Credo.CLI.Output.UI.truncate(" more than 7\\n", 7, " ...") 77 " m ..." 78 """ 79 def truncate(line, max_length) when max_length <= 0 or is_nil(line), do: "" 80 81 def truncate(line, max_length) when max_length > 0 do 82 truncate(line, max_length, @ellipsis) 83 end 84 85 def truncate(_line, max_length, _ellipsis) when max_length <= 0, do: "" 86 87 def truncate(line, max_length, ellipsis) when max_length > 0 do 88 cond do 89 String.length(line) <= max_length -> 90 line 91 92 String.length(ellipsis) >= max_length -> 93 ellipsis 94 95 true -> 96 chars_to_display = max_length - String.length(ellipsis) 97 String.slice(line, 0, chars_to_display) <> ellipsis 98 end 99 end 100 end