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.

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