aboutsummaryrefslogtreecommitdiff
path: root/aoc2023/build/packages/snag/src/snag.erl
blob: a07f2420e5d9c8c62d99394dd5dad148b6426873 (plain)
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
74
-module(snag).
-compile([no_auto_import, nowarn_unused_vars]).

-export([new/1, error/1, layer/2, context/2, pretty_print/1, line_print/1]).
-export_type([snag/0]).

-type snag() :: {snag, binary(), list(binary())}.

-spec new(binary()) -> snag().
new(Issue) ->
    {snag, Issue, []}.

-spec error(binary()) -> {ok, any()} | {error, snag()}.
error(Issue) ->
    {error, new(Issue)}.

-spec layer(snag(), binary()) -> snag().
layer(Snag, Issue) ->
    {snag, Issue, [erlang:element(2, Snag) | erlang:element(3, Snag)]}.

-spec context({ok, EXX} | {error, snag()}, binary()) -> {ok, EXX} |
    {error, snag()}.
context(Result, Issue) ->
    case Result of
        {ok, _} ->
            Result;

        {error, Snag} ->
            {error, layer(Snag, Issue)}
    end.

-spec pretty_print_cause(list(binary())) -> gleam@string_builder:string_builder().
pretty_print_cause(Cause) ->
    _pipe = Cause,
    _pipe@1 = gleam@list:index_map(
        _pipe,
        fun(Index, Line) ->
            gleam@string:concat(
                [<<"  "/utf8>>,
                    gleam@int:to_string(Index),
                    <<": "/utf8>>,
                    Line,
                    <<"\n"/utf8>>]
            )
        end
    ),
    gleam@string_builder:from_strings(_pipe@1).

-spec pretty_print(snag()) -> binary().
pretty_print(Snag) ->
    Builder = gleam@string_builder:from_strings(
        [<<"error: "/utf8>>, erlang:element(2, Snag), <<"\n"/utf8>>]
    ),
    gleam@string_builder:to_string(case erlang:element(3, Snag) of
            [] ->
                Builder;

            Cause ->
                _pipe = Builder,
                _pipe@1 = gleam@string_builder:append(
                    _pipe,
                    <<"\ncause:\n"/utf8>>
                ),
                gleam@string_builder:append_builder(
                    _pipe@1,
                    pretty_print_cause(Cause)
                )
        end).

-spec line_print(snag()) -> binary().
line_print(Snag) ->
    _pipe = [gleam@string:append(<<"error: "/utf8>>, erlang:element(2, Snag)) |
        erlang:element(3, Snag)],
    gleam@string:join(_pipe, <<" <- "/utf8>>).