You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

221 lines
8.1 KiB

  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_prv_escriptize).
  28. -behaviour(provider).
  29. -export([init/1, do/1, format_error/1]).
  30. -define(PROVIDER, escriptize).
  31. -define(DEPS, [compile]).
  32. -include("rebar.hrl").
  33. -include_lib("providers/include/providers.hrl").
  34. -include_lib("kernel/include/file.hrl").
  35. %%%=============================================================================
  36. %%% API
  37. %%%=============================================================================
  38. -spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
  39. init(State) ->
  40. Provider = providers:create([
  41. {name, ?PROVIDER},
  42. {module, ?MODULE},
  43. {bare, false},
  44. {deps, ?DEPS},
  45. {example, "rebar3 escriptize"},
  46. {opts, []},
  47. {short_desc, "Generate escript archive"},
  48. {desc, desc()}
  49. ]),
  50. {ok, rebar_state:add_provider(State, Provider)}.
  51. desc() ->
  52. "Generate an escript executable containing "
  53. "the project's and its dependencies' BEAM files.".
  54. do(State) ->
  55. escriptize(State).
  56. escriptize(State0) ->
  57. App1 = case rebar_state:project_apps(State0) of
  58. [App] ->
  59. App;
  60. Apps ->
  61. case rebar_state:get(escript_main_app, State0, undefined) of
  62. undefined ->
  63. ?PRV_ERROR(no_main_app);
  64. Name ->
  65. rebar_app_utils:find(Name, Apps)
  66. end
  67. end,
  68. AppName = rebar_app_info:name(App1),
  69. AppNameStr = ec_cnv:to_list(AppName),
  70. %% Get the output filename for the escript -- this may include dirs
  71. Filename = filename:join([rebar_dir:base_dir(State0), "bin",
  72. rebar_state:get(State0, escript_name, AppName)]),
  73. ok = filelib:ensure_dir(Filename),
  74. State = rebar_state:escript_path(State0, Filename),
  75. %% Look for a list of other applications (dependencies) to include
  76. %% in the output file. We then use the .app files for each of these
  77. %% to pull in all the .beam files.
  78. InclApps = lists:usort(rebar_state:get(State, escript_incl_apps, [])
  79. ++ all_deps(State)),
  80. InclBeams = get_app_beams(InclApps),
  81. %% Look for a list of extra files to include in the output file.
  82. %% For internal rebar-private use only. Do not use outside rebar.
  83. InclExtra = get_extra(State),
  84. %% Construct the archive of everything in ebin/ dir -- put it on the
  85. %% top-level of the zip file so that code loading works properly.
  86. EbinPrefix = filename:join(AppNameStr, "ebin"),
  87. EbinFiles = usort(load_files(EbinPrefix, "*", "ebin")),
  88. ExtraFiles = usort(InclBeams ++ InclExtra),
  89. Files = get_nonempty(EbinFiles ++ ExtraFiles),
  90. DefaultEmuArgs = ?FMT("%%! -escript main ~s -pa ~s/~s/ebin\n",
  91. [AppNameStr, AppNameStr, AppNameStr]),
  92. EscriptSections =
  93. [ {shebang,
  94. def("#!", State, escript_shebang, "#!/usr/bin/env escript\n")}
  95. , {comment, def("%%", State, escript_comment, "%%\n")}
  96. , {emu_args, def("%%!", State, escript_emu_args, DefaultEmuArgs)}
  97. , {archive, Files, []} ],
  98. case escript:create(Filename, EscriptSections) of
  99. ok -> ok;
  100. {error, EscriptError} ->
  101. throw(?PRV_ERROR({escript_creation_failed, AppName, EscriptError}))
  102. end,
  103. %% Finally, update executable perms for our script
  104. {ok, #file_info{mode = Mode}} = file:read_file_info(Filename),
  105. ok = file:change_mode(Filename, Mode bor 8#00111),
  106. {ok, State}.
  107. -spec format_error(any()) -> iolist().
  108. format_error({write_failed, AppName, WriteError}) ->
  109. io_lib:format("Failed to write ~p script: ~p", [AppName, WriteError]);
  110. format_error({zip_error, AppName, ZipError}) ->
  111. io_lib:format("Failed to construct ~p escript: ~p", [AppName, ZipError]);
  112. format_error({bad_name, App}) ->
  113. io_lib:format("Failed to get ebin/ directory for "
  114. "escript_incl_app: ~p", [App]);
  115. format_error(no_main_app) ->
  116. io_lib:format("Multiple project apps and {rebar_escript_plugin, [{main_app, atom()}]}."
  117. " not set in rebar.config", []).
  118. %% ===================================================================
  119. %% Internal functions
  120. %% ===================================================================
  121. get_app_beams(Apps) ->
  122. get_app_beams(Apps, []).
  123. get_app_beams([], Acc) ->
  124. Acc;
  125. get_app_beams([App | Rest], Acc) ->
  126. case code:lib_dir(App, ebin) of
  127. {error, bad_name} ->
  128. throw(?PRV_ERROR({bad_name, App}));
  129. Path ->
  130. Prefix = filename:join(atom_to_list(App), "ebin"),
  131. Acc2 = load_files(Prefix, "*.beam", Path),
  132. get_app_beams(Rest, Acc2 ++ Acc)
  133. end.
  134. get_extra(State) ->
  135. Extra = rebar_state:get(State, escript_incl_extra, []),
  136. lists:foldl(fun({Wildcard, Dir}, Files) ->
  137. load_files(Wildcard, Dir) ++ Files
  138. end, [], Extra).
  139. load_files(Wildcard, Dir) ->
  140. load_files("", Wildcard, Dir).
  141. load_files(Prefix, Wildcard, Dir) ->
  142. [read_file(Prefix, Filename, Dir)
  143. || Filename <- filelib:wildcard(Wildcard, Dir)].
  144. read_file(Prefix, Filename, Dir) ->
  145. Filename1 = case Prefix of
  146. "" ->
  147. Filename;
  148. _ ->
  149. filename:join([Prefix, Filename])
  150. end,
  151. [dir_entries(filename:dirname(Filename1)),
  152. {Filename1, file_contents(filename:join(Dir, Filename))}].
  153. file_contents(Filename) ->
  154. {ok, Bin} = file:read_file(Filename),
  155. Bin.
  156. %% Given a filename, return zip archive dir entries for each sub-dir.
  157. %% Required to work around issues fixed in OTP-10071.
  158. dir_entries(File) ->
  159. Dirs = dirs(File),
  160. [{Dir ++ "/", <<>>} || Dir <- Dirs].
  161. %% Given "foo/bar/baz", return ["foo", "foo/bar", "foo/bar/baz"].
  162. dirs(Dir) ->
  163. dirs1(filename:split(Dir), "", []).
  164. dirs1([], _, Acc) ->
  165. lists:reverse(Acc);
  166. dirs1([H|T], "", []) ->
  167. dirs1(T, H, [H]);
  168. dirs1([H|T], Last, Acc) ->
  169. Dir = filename:join(Last, H),
  170. dirs1(T, Dir, [Dir|Acc]).
  171. usort(List) ->
  172. lists:ukeysort(1, lists:flatten(List)).
  173. get_nonempty(Files) ->
  174. [{FName,FBin} || {FName,FBin} <- Files, FBin =/= <<>>].
  175. all_deps(State) ->
  176. [list_to_existing_atom(binary_to_list(rebar_app_info:name(App)))
  177. || App <- rebar_state:all_deps(State)].
  178. def(Rm, State, Key, Default) ->
  179. Value0 = rebar_state:get(State, Key, Default),
  180. case Rm of
  181. "#!" -> "#!" ++ Value = Value0, rm_newline(Value);
  182. "%%" -> "%%" ++ Value = Value0, rm_newline(Value);
  183. "%%!" -> "%%!" ++ Value = Value0, rm_newline(Value)
  184. end.
  185. rm_newline(String) ->
  186. [C || C <- String, C =/= $\n].