1%% -*- erlang-indent-level: 4;indent-tabs-mode: nil -*-
2%% ex: ts=4 sw=4 et
3%% -------------------------------------------------------------------
4%%
5%% rebar: Erlang Build Tools
6%%
7%% Copyright (c) 2009 Dave Smith (dizzyd@dizzyd.com)
8%%
9%% Permission is hereby granted, free of charge, to any person obtaining a copy
10%% of this software and associated documentation files (the "Software"), to deal
11%% in the Software without restriction, including without limitation the rights
12%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13%% copies of the Software, and to permit persons to whom the Software is
14%% furnished to do so, subject to the following conditions:
15%%
16%% The above copyright notice and this permission notice shall be included in
17%% all copies or substantial portions of the Software.
18%%
19%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25%% THE SOFTWARE.
26%% -------------------------------------------------------------------
27-module(rebar_otp_app).
28
29-export([compile/2,
30         format_error/1]).
31
32-include("rebar.hrl").
33-include_lib("providers/include/providers.hrl").
34
35%% ===================================================================
36%% Public API
37%% ===================================================================
38
39compile(State, App) ->
40    %% If we get an .app.src file, it needs to be pre-processed and
41    %% written out as a ebin/*.app file. That resulting file will then
42    %% be validated as usual.
43    App1 = case rebar_app_info:app_file_src_script(App) of
44               undefined ->
45                   case rebar_app_info:app_file_src(App) of
46                       undefined ->
47                           App;
48                       AppFileSrc ->
49                           preprocess(State, App, AppFileSrc)
50                   end;
51               AppFileSrcScript ->
52                   preprocess(State, App, AppFileSrcScript)
53           end,
54
55    %% Load the app file and validate it.
56    validate_app(State, App1).
57
58format_error({missing_app_file, Filename}) ->
59    io_lib:format("App file is missing: ~ts", [Filename]);
60format_error({file_read, AppName, File, Reason}) ->
61    io_lib:format("Failed to read required ~ts file for processing the application '~ts': ~ts",
62                  [File, AppName, file:format_error(Reason)]);
63format_error({invalid_name, File, AppName}) ->
64    io_lib:format("Invalid ~ts: name of application (~p) must match filename.", [File, AppName]).
65
66%% ===================================================================
67%% Internal functions
68%% ===================================================================
69
70validate_app(State, App) ->
71    AppFile = rebar_app_info:app_file(App),
72    case consult_app_file(AppFile) of
73        {ok, [{application, AppName, AppData}]} ->
74            case validate_name(AppName, AppFile) of
75                ok ->
76                    validate_app_modules(State, App, AppData);
77                Error ->
78                    Error
79            end;
80        {error, Reason} ->
81            ?PRV_ERROR({file_read, rebar_app_info:name(App), ".app", Reason})
82    end.
83
84validate_app_modules(State, App, AppData) ->
85    %% In general, the list of modules is an important thing to validate
86    %% for compliance with OTP guidelines and upgrade procedures.
87    %% However, some people prefer not to validate this list.
88    AppVsn = proplists:get_value(vsn, AppData),
89    case rebar_state:get(State, validate_app_modules, true) of
90        true ->
91            case rebar_app_utils:validate_application_info(App, AppData) of
92                true ->
93                    {ok, ensure_vsn(App, AppVsn)};
94                Error ->
95                    Error
96            end;
97        false ->
98            {ok, ensure_vsn(App, AppVsn)}
99    end.
100
101%% If a version hasn't been set yet, then set it both for the
102%% original and regular version attributes.
103ensure_vsn(App, Vsn) ->
104    ensure_vsn(original_vsn, ensure_vsn(vsn, App, Vsn), Vsn).
105
106ensure_vsn(F, App, AppVsn) ->
107    case rebar_app_info:F(App) of
108        Vsn when Vsn =:= undefined; Vsn =:= [] ->
109            rebar_app_info:F(App, AppVsn);
110        _ ->
111            App
112    end.
113
114preprocess(State, AppInfo, AppSrcFile) ->
115    case consult_app_file(AppSrcFile) of
116        {ok, [{application, AppName, AppData}]} ->
117            %% Look for a configuration file with vars we want to
118            %% substitute. Note that we include the list of modules available in
119            %% ebin/ and update the app data accordingly.
120            OutDir = rebar_app_info:out_dir(AppInfo),
121            AppVars = load_app_vars(State) ++ [{modules, ebin_modules(AppInfo, OutDir)}],
122            A1 = apply_app_vars(AppVars, AppData),
123
124            %% AppSrcFile may contain instructions for generating a vsn number
125            Vsn = app_vsn(AppInfo, AppData, AppSrcFile, State),
126            A2 = lists:keystore(vsn, 1, A1, {vsn, Vsn}),
127
128            %% systools:make_relup/4 fails with {missing_param, registered}
129            %% without a 'registered' value.
130            A3 = ensure_registered(A2),
131
132            %% some tools complain if a description is not present.
133            A4 = ensure_description(A3),
134
135            %% Build the final spec as a string
136            Spec = io_lib:format("~p.\n", [{application, AppName, A4}]),
137
138            %% Setup file .app filename and write new contents
139            EbinDir = rebar_app_info:ebin_dir(AppInfo),
140            rebar_file_utils:ensure_dir(EbinDir),
141            AppFile = rebar_app_utils:app_src_to_app(OutDir, AppSrcFile, State),
142            ok = rebar_file_utils:write_file_if_contents_differ(AppFile, Spec, utf8),
143
144            rebar_app_info:app_file(rebar_app_info:vsn(AppInfo, Vsn), AppFile);
145        {error, Reason} ->
146            throw(?PRV_ERROR({file_read, rebar_app_info:name(AppInfo), ".app.src", Reason}))
147    end.
148
149load_app_vars(State) ->
150    case rebar_state:get(State, app_vars_file, undefined) of
151        undefined ->
152            [];
153        Filename ->
154            ?INFO("Loading app vars from ~p", [Filename]),
155            {ok, Vars} = file:consult(Filename),
156            Vars
157    end.
158
159apply_app_vars([], AppData) ->
160    AppData;
161apply_app_vars([{Key, Value} | Rest], AppData) ->
162    AppData2 = lists:keystore(Key, 1, AppData, {Key, Value}),
163    apply_app_vars(Rest, AppData2).
164
165validate_name(AppName, File) ->
166    %% Convert the .app file name to an atom -- check it against the
167    %% identifier within the file
168    ExpApp = list_to_atom(filename:basename(File, ".app")),
169    case ExpApp == AppName of
170        true ->
171            ok;
172        false ->
173            ?PRV_ERROR({invalid_name, File, AppName})
174    end.
175
176ebin_modules(AppInfo, Dir) ->
177    Beams = lists:sort(rebar_utils:beams(filename:join(Dir, "ebin"))),
178    ExtraDirs = extra_dirs(AppInfo),
179    F = fun(Beam) -> not in_extra_dir(AppInfo, Beam, ExtraDirs) end,
180    Filtered = lists:filter(F, Beams),
181    [rebar_utils:beam_to_mod(N) || N <- Filtered].
182
183extra_dirs(State) ->
184    Extras = rebar_dir:extra_src_dirs(rebar_app_info:opts(State)),
185    SrcDirs = rebar_dir:src_dirs(rebar_app_info:opts(State), ["src"]),
186    %% remove any dirs that are defined in `src_dirs` from `extra_src_dirs`
187    Extras -- SrcDirs.
188
189in_extra_dir(AppInfo, Beam, Dirs) ->
190    lists:any(fun(Dir) -> lists:prefix(filename:join([rebar_app_info:out_dir(AppInfo), Dir]),
191                                       beam_src(Beam)) end,
192              Dirs).
193
194beam_src(Beam) ->
195    case beam_lib:chunks(Beam, [compile_info]) of
196        {ok, {_mod, Chunks}} ->
197            CompileInfo = proplists:get_value(compile_info, Chunks, []),
198            proplists:get_value(source, CompileInfo, []);
199        {error, beam_lib, Reason} ->
200            ?WARN("Couldn't read debug info from ~p for reason: ~p", [Beam, Reason]),
201            []
202    end.
203
204ensure_registered(AppData) ->
205    case lists:keyfind(registered, 1, AppData) of
206        false ->
207            [{registered, []} | AppData];
208        {registered, _} ->
209            %% We could further check whether the value is a list of atoms.
210            AppData
211    end.
212
213ensure_description(AppData) ->
214    case lists:keyfind(description, 1, AppData) of
215        false ->
216            %% Required for releases to work.
217            [{description, ""} | AppData];
218        {description, _} ->
219            AppData
220    end.
221
222%% In the case of *.app.src we want to give the user the ability to
223%% dynamically script the application resource file (think dynamic version
224%% string, etc.), in a way similar to what can be done with the rebar
225%% config. However, in the case of *.app, rebar should not manipulate
226%% that file. This enforces that dichotomy between app and app.src.
227consult_app_file(Filename) ->
228    case filelib:is_file(Filename) of
229        false ->
230            {error, enoent};
231        true ->
232            case lists:suffix(".app.src", Filename)
233                orelse lists:suffix(".app.src.script", Filename) of
234                false ->
235                    file:consult(Filename);
236                true ->
237                    {ok, rebar_config:consult_app_file(Filename)}
238            end
239    end.
240
241app_vsn(AppInfo, AppData, AppFile, State) ->
242    rebar_utils:vcs_vsn(AppInfo, get_value(vsn, AppData, AppFile), State).
243
244get_value(Key, AppInfo, AppFile) ->
245    case proplists:get_value(Key, AppInfo) of
246        undefined ->
247            ?ABORT("Failed to get app value '~p' from '~ts'~n", [Key, AppFile]);
248        Value ->
249            Value
250    end.
251