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.

277 lines
11 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, true},
  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. Providers = rebar_state:providers(State),
  56. Cwd = rebar_state:dir(State),
  57. rebar_hooks:run_project_and_app_hooks(Cwd, pre, ?PROVIDER, Providers, State),
  58. ?INFO("Building escript...", []),
  59. Res = case rebar_state:get(State, escript_main_app, undefined) of
  60. undefined ->
  61. case rebar_state:project_apps(State) of
  62. [App] ->
  63. escriptize(State, App);
  64. _ ->
  65. ?PRV_ERROR(no_main_app)
  66. end;
  67. Name ->
  68. AllApps = rebar_state:all_deps(State)++rebar_state:project_apps(State),
  69. case rebar_app_utils:find(ec_cnv:to_binary(Name), AllApps) of
  70. {ok, AppInfo} ->
  71. escriptize(State, AppInfo);
  72. _ ->
  73. ?PRV_ERROR({bad_name, Name})
  74. end
  75. end,
  76. rebar_hooks:run_project_and_app_hooks(Cwd, post, ?PROVIDER, Providers, State),
  77. Res.
  78. escriptize(State0, App) ->
  79. AppName = rebar_app_info:name(App),
  80. AppNameStr = ec_cnv:to_list(AppName),
  81. %% Get the output filename for the escript -- this may include dirs
  82. Filename = filename:join([rebar_dir:base_dir(State0), "bin",
  83. rebar_state:get(State0, escript_name, AppName)]),
  84. ?DEBUG("Creating escript file ~s", [Filename]),
  85. ok = filelib:ensure_dir(Filename),
  86. State = rebar_state:escript_path(State0, Filename),
  87. %% Look for a list of other applications (dependencies) to include
  88. %% in the output file. We then use the .app files for each of these
  89. %% to pull in all the .beam files.
  90. TopInclApps = lists:usort([ec_cnv:to_atom(AppName) | rebar_state:get(State, escript_incl_apps, [])]),
  91. AllApps = rebar_state:all_deps(State)++rebar_state:project_apps(State),
  92. InclApps = find_deps(TopInclApps, AllApps),
  93. InclBeams = get_apps_beams(InclApps, AllApps),
  94. %% Look for a list of extra files to include in the output file.
  95. %% For internal rebar-private use only. Do not use outside rebar.
  96. InclExtra = get_extra(State),
  97. %% Construct the archive of everything in ebin/ dir -- put it on the
  98. %% top-level of the zip file so that code loading works properly.
  99. EbinPrefix = filename:join(AppNameStr, "ebin"),
  100. EbinFiles = usort(load_files(EbinPrefix, "*", "ebin")),
  101. ExtraFiles = usort(InclBeams ++ InclExtra),
  102. Files = get_nonempty(EbinFiles ++ ExtraFiles),
  103. DefaultEmuArgs = ?FMT("%%! -escript main ~s -pz ~s/~s/ebin\n",
  104. [AppNameStr, AppNameStr, AppNameStr]),
  105. EscriptSections =
  106. [ {shebang,
  107. def("#!", State, escript_shebang, "#!/usr/bin/env escript\n")}
  108. , {comment, def("%%", State, escript_comment, "%%\n")}
  109. , {emu_args, def("%%!", State, escript_emu_args, DefaultEmuArgs)}
  110. , {archive, Files, []} ],
  111. case escript:create(Filename, EscriptSections) of
  112. ok -> ok;
  113. {error, EscriptError} ->
  114. throw(?PRV_ERROR({escript_creation_failed, AppName, EscriptError}))
  115. end,
  116. %% Finally, update executable perms for our script on *nix or write out
  117. %% script files on win32
  118. case os:type() of
  119. {unix, _} ->
  120. {ok, #file_info{mode = Mode}} = file:read_file_info(Filename),
  121. ok = file:change_mode(Filename, Mode bor 8#00111);
  122. {win32, _} ->
  123. write_windows_script(Filename)
  124. end,
  125. {ok, State}.
  126. -spec format_error(any()) -> iolist().
  127. format_error({write_failed, AppName, WriteError}) ->
  128. io_lib:format("Failed to write ~p script: ~p", [AppName, WriteError]);
  129. format_error({zip_error, AppName, ZipError}) ->
  130. io_lib:format("Failed to construct ~p escript: ~p", [AppName, ZipError]);
  131. format_error({bad_name, App}) ->
  132. io_lib:format("Failed to get ebin/ directory for "
  133. "escript_incl_app: ~p", [App]);
  134. format_error(no_main_app) ->
  135. io_lib:format("Multiple project apps and {escript_main_app, atom()}."
  136. " not set in rebar.config", []).
  137. %% ===================================================================
  138. %% Internal functions
  139. %% ===================================================================
  140. get_apps_beams(Apps, AllApps) ->
  141. get_apps_beams(Apps, AllApps, []).
  142. get_apps_beams([], _, Acc) ->
  143. Acc;
  144. get_apps_beams([App | Rest], AllApps, Acc) ->
  145. case rebar_app_utils:find(ec_cnv:to_binary(App), AllApps) of
  146. {ok, App1} ->
  147. OutDir = filename:absname(rebar_app_info:ebin_dir(App1)),
  148. Beams = get_app_beams(App, OutDir),
  149. get_apps_beams(Rest, AllApps, Beams ++ Acc);
  150. _->
  151. case code:lib_dir(App, ebin) of
  152. {error, bad_name} ->
  153. throw(?PRV_ERROR({bad_name, App}));
  154. Path ->
  155. Beams = get_app_beams(App, Path),
  156. get_apps_beams(Rest, AllApps, Beams ++ Acc)
  157. end
  158. end.
  159. get_app_beams(App, Path) ->
  160. Prefix = filename:join(atom_to_list(App), "ebin"),
  161. load_files(Prefix, "*.beam", Path) ++
  162. load_files(Prefix, "*.app", Path).
  163. get_extra(State) ->
  164. Extra = rebar_state:get(State, escript_incl_extra, []),
  165. lists:foldl(fun({Wildcard, Dir}, Files) ->
  166. load_files(Wildcard, Dir) ++ Files
  167. end, [], Extra).
  168. load_files(Wildcard, Dir) ->
  169. load_files("", Wildcard, Dir).
  170. load_files(Prefix, Wildcard, Dir) ->
  171. [read_file(Prefix, Filename, Dir)
  172. || Filename <- filelib:wildcard(Wildcard, Dir)].
  173. read_file(Prefix, Filename, Dir) ->
  174. Filename1 = case Prefix of
  175. "" ->
  176. Filename;
  177. _ ->
  178. filename:join([Prefix, Filename])
  179. end,
  180. [dir_entries(filename:dirname(Filename1)),
  181. {Filename1, file_contents(filename:join(Dir, Filename))}].
  182. file_contents(Filename) ->
  183. {ok, Bin} = file:read_file(Filename),
  184. Bin.
  185. %% Given a filename, return zip archive dir entries for each sub-dir.
  186. %% Required to work around issues fixed in OTP-10071.
  187. dir_entries(File) ->
  188. Dirs = dirs(File),
  189. [{Dir ++ "/", <<>>} || Dir <- Dirs].
  190. %% Given "foo/bar/baz", return ["foo", "foo/bar", "foo/bar/baz"].
  191. dirs(Dir) ->
  192. dirs1(filename:split(Dir), "", []).
  193. dirs1([], _, Acc) ->
  194. lists:reverse(Acc);
  195. dirs1([H|T], "", []) ->
  196. dirs1(T, H, [H]);
  197. dirs1([H|T], Last, Acc) ->
  198. Dir = filename:join(Last, H),
  199. dirs1(T, Dir, [Dir|Acc]).
  200. usort(List) ->
  201. lists:ukeysort(1, lists:flatten(List)).
  202. get_nonempty(Files) ->
  203. [{FName,FBin} || {FName,FBin} <- Files, FBin =/= <<>>].
  204. find_deps(AppNames, AllApps) ->
  205. BinAppNames = [ec_cnv:to_binary(Name) || Name <- AppNames],
  206. [ec_cnv:to_atom(Name) ||
  207. Name <- find_deps_of_deps(BinAppNames, AllApps, BinAppNames)].
  208. %% Should look at the app files to find direct dependencies
  209. find_deps_of_deps([], _, Acc) -> Acc;
  210. find_deps_of_deps([Name|Names], Apps, Acc) ->
  211. ?DEBUG("processing ~p", [Name]),
  212. {ok, App} = rebar_app_utils:find(Name, Apps),
  213. DepNames = proplists:get_value(applications, rebar_app_info:app_details(App), []),
  214. BinDepNames = [ec_cnv:to_binary(Dep) || Dep <- DepNames,
  215. %% ignore system libs; shouldn't include them.
  216. DepDir <- [code:lib_dir(Dep)],
  217. DepDir =:= {error, bad_name} orelse % those are all local
  218. not lists:prefix(code:root_dir(), DepDir)]
  219. -- ([Name|Names]++Acc), % avoid already seen deps
  220. ?DEBUG("new deps of ~p found to be ~p", [Name, BinDepNames]),
  221. find_deps_of_deps(BinDepNames ++ Names, Apps, BinDepNames ++ Acc).
  222. def(Rm, State, Key, Default) ->
  223. Value0 = rebar_state:get(State, Key, Default),
  224. case Rm of
  225. "#!" -> "#!" ++ Value = Value0, rm_newline(Value);
  226. "%%" -> "%%" ++ Value = Value0, rm_newline(Value);
  227. "%%!" -> "%%!" ++ Value = Value0, rm_newline(Value)
  228. end.
  229. rm_newline(String) ->
  230. [C || C <- String, C =/= $\n].
  231. write_windows_script(Target) ->
  232. CmdPath = if is_binary(Target) -> <<Target/binary, ".cmd">>;
  233. is_list(Target) -> Target ++ ".cmd"
  234. end,
  235. CmdScript=
  236. "@echo off\r\n"
  237. "setlocal\r\n"
  238. "set rebarscript=%~f0\r\n"
  239. "escript.exe \"%rebarscript:.cmd=%\" %*\r\n",
  240. ok = file:write_file(CmdPath, CmdScript).