您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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