summaryrefslogtreecommitdiff
path: root/src/rebar_prv_packages.erl
blob: be51833e0bbaf2ffbe4b0f4aa255338e942a78b5 (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
-module(rebar_prv_packages).

-behaviour(provider).

-export([init/1,
         do/1,
         format_error/2]).

-include("rebar.hrl").

-define(PROVIDER, pkgs).
-define(DEPS, []).

-spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
init(State) ->
    State1 = rebar_state:add_provider(State, providers:create([{name, ?PROVIDER},
                                                               {module, ?MODULE},
                                                               {bare, false},
                                                               {deps, ?DEPS},
                                                               {example, "rebar pkgs"},
                                                               {short_desc, "List available packages."},
                                                               {desc, info("List available packages")},
                                                               {opts, []}])),
    {ok, State1}.

-spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}.
do(State) ->
    {Packages, _Graph} = rebar_packages:get_packages(State),
    print_packages(Packages),
    {ok, State}.

-spec format_error(any(), rebar_state:t()) ->  {iolist(), rebar_state:t()}.
format_error(Reason, State) ->
    {io_lib:format("~p", [Reason]), State}.

print_packages(Packages) ->
    Keys = lists:keysort(1, dict:fetch_keys(Packages)),
    Pkgs = merge(Keys),
    lists:foreach(fun({Name, Vsns}) ->
                          VsnStr = join(Vsns, <<", ">>),
                          io:format("~s:~n    Versions: ~s~n~n", [Name, VsnStr])
                  end, Pkgs).

-spec merge([{binary(), binary()}]) -> [{binary(), [binary()]}].
merge(List) ->
    merge([], List).

merge(List, []) ->
    List;
merge([{Key, Values} | T], [{Key, Value} | Rest]) ->
    merge([{Key, [Value | Values]} | T], Rest);
merge(List, [{Key, Value} | Rest]) ->
    merge([{Key, [Value]} | List], Rest).

-spec join([binary()], binary()) -> binary().
join([Bin], _Sep) ->
    <<Bin/binary>>;
join([Bin | T], Sep) ->
    <<Bin/binary, Sep/binary, (join(T, Sep))/binary>>.


info(Description) ->
    io_lib:format("~s.~n", [Description]).