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

-behaviour(rebar_compiler).

-export([context/1,
         needed_files/3,
         dependencies/3,
         compile/4,
         clean/2]).

-include("rebar.hrl").
-include_lib("stdlib/include/erl_compile.hrl").

context(AppInfo) ->
    Dir = rebar_app_info:dir(AppInfo),
    Mappings = [{".bin", filename:join([Dir, "priv", "mibs"])},
               {".hrl", filename:join(Dir, "include")}],

    #{src_dirs => ["mibs"],
      include_dirs => [],
      src_ext => ".mib",
      out_mappings => Mappings}.

needed_files(_, FoundFiles, AppInfo) ->
    FirstFiles = [],

    %% Remove first files from found files
    RestFiles = [Source || Source <- FoundFiles, not lists:member(Source, FirstFiles)],

    Opts = rebar_opts:get(rebar_app_info:opts(AppInfo), mib_opts, []),
    {{FirstFiles, Opts}, {RestFiles, Opts}}.

dependencies(_, _, _) ->
    [].

compile(Source, OutDirs, _, Opts) ->
    {_, BinOut} = lists:keyfind(".bin", 1, OutDirs),
    {_, HrlOut} = lists:keyfind(".hrl", 1, OutDirs),

    ok = rebar_file_utils:ensure_dir(BinOut),
    ok = rebar_file_utils:ensure_dir(HrlOut),
    Mib = filename:join(BinOut, filename:basename(Source, ".mib")),
    HrlFilename = Mib ++ ".hrl",

    AllOpts = [{outdir, BinOut}, {i, [BinOut]}] ++ Opts,

    case snmpc:compile(Source, AllOpts) of
        {ok, _} ->
            MibToHrlOpts =
                case proplists:get_value(verbosity, AllOpts, undefined) of
                    undefined ->
                        #options{specific = [],
                                 cwd = rebar_dir:get_cwd()};
                    Verbosity ->
                        #options{specific = [{verbosity, Verbosity}],
                                 cwd = rebar_dir:get_cwd()}
                end,
            ok = snmpc:mib_to_hrl(Mib, Mib, MibToHrlOpts),
            rebar_file_utils:mv(HrlFilename, HrlOut),
            ok;
        {error, compilation_failed} ->
            ?FAIL
    end.

clean(MibFiles, AppInfo) ->
    AppDir = rebar_app_info:dir(AppInfo),
    MIBs = [filename:rootname(filename:basename(MIB)) || MIB <- MibFiles],
    rebar_file_utils:delete_each(
      [filename:join([AppDir, "include", MIB++".hrl"]) || MIB <- MIBs]),
    ok = rebar_file_utils:rm_rf(filename:join([AppDir, "priv/mibs/*.bin"])).