Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

517 linhas
17 KiB

15 anos atrás
15 anos atrás
13 anos atrás
15 anos atrás
13 anos atrás
14 anos atrás
14 anos atrás
13 anos atrás
13 anos atrás
13 anos atrás
13 anos atrás
13 anos atrás
13 anos atrás
12 anos atrás
13 anos atrás
13 anos atrás
13 anos atrás
14 anos atrás
13 anos atrás
13 anos atrás
14 anos atrás
14 anos atrás
  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, 2010 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_utils).
  28. -export([get_cwd/0,
  29. is_arch/1,
  30. get_arch/0,
  31. wordsize/0,
  32. sh/2,
  33. find_files/2, find_files/3,
  34. now_str/0,
  35. ensure_dir/1,
  36. beam_to_mod/2, beams/1,
  37. erl_to_mod/1,
  38. abort/0, abort/2,
  39. escript_foldl/3,
  40. find_executable/1,
  41. prop_check/3,
  42. expand_code_path/0,
  43. expand_env_variable/3,
  44. vcs_vsn/3,
  45. deprecated/3, deprecated/4,
  46. get_deprecated_global/4, get_deprecated_global/5,
  47. get_deprecated_list/4, get_deprecated_list/5,
  48. get_deprecated_local/4, get_deprecated_local/5,
  49. delayed_halt/1,
  50. erl_opts/1,
  51. src_dirs/1,
  52. test_dir/0,
  53. ebin_dir/0,
  54. processing_base_dir/1, processing_base_dir/2]).
  55. -include("rebar.hrl").
  56. %% ====================================================================
  57. %% Public API
  58. %% ====================================================================
  59. get_cwd() ->
  60. {ok, Dir} = file:get_cwd(),
  61. Dir.
  62. is_arch(ArchRegex) ->
  63. case re:run(get_arch(), ArchRegex, [{capture, none}]) of
  64. match ->
  65. true;
  66. nomatch ->
  67. false
  68. end.
  69. get_arch() ->
  70. Words = wordsize(),
  71. erlang:system_info(otp_release) ++ "-"
  72. ++ erlang:system_info(system_architecture) ++ "-" ++ Words
  73. ++ "-" ++ os_family().
  74. wordsize() ->
  75. try erlang:system_info({wordsize, external}) of
  76. Val ->
  77. integer_to_list(8 * Val)
  78. catch
  79. error:badarg ->
  80. integer_to_list(8 * erlang:system_info(wordsize))
  81. end.
  82. %%
  83. %% Options = [Option] -- defaults to [use_stdout, abort_on_error]
  84. %% Option = ErrorOption | OutputOption | {cd, string()} | {env, Env}
  85. %% ErrorOption = return_on_error | abort_on_error | {abort_on_error, string()}
  86. %% OutputOption = use_stdout | {use_stdout, bool()}
  87. %% Env = [{string(), Val}]
  88. %% Val = string() | false
  89. %%
  90. sh(Command0, Options0) ->
  91. ?INFO("sh info:\n\tcwd: ~p\n\tcmd: ~s\n", [get_cwd(), Command0]),
  92. ?DEBUG("\topts: ~p\n", [Options0]),
  93. DefaultOptions = [use_stdout, abort_on_error],
  94. Options = [expand_sh_flag(V)
  95. || V <- proplists:compact(Options0 ++ DefaultOptions)],
  96. ErrorHandler = proplists:get_value(error_handler, Options),
  97. OutputHandler = proplists:get_value(output_handler, Options),
  98. Command = patch_on_windows(Command0, proplists:get_value(env, Options, [])),
  99. PortSettings = proplists:get_all_values(port_settings, Options) ++
  100. [exit_status, {line, 16384}, use_stdio, stderr_to_stdout, hide],
  101. Port = open_port({spawn, Command}, PortSettings),
  102. case sh_loop(Port, OutputHandler, []) of
  103. {ok, _Output} = Ok ->
  104. Ok;
  105. {error, {_Rc, _Output}=Err} ->
  106. ErrorHandler(Command, Err)
  107. end.
  108. find_files(Dir, Regex) ->
  109. find_files(Dir, Regex, true).
  110. find_files(Dir, Regex, Recursive) ->
  111. filelib:fold_files(Dir, Regex, Recursive,
  112. fun(F, Acc) -> [F | Acc] end, []).
  113. now_str() ->
  114. {{Year, Month, Day}, {Hour, Minute, Second}} = calendar:local_time(),
  115. lists:flatten(io_lib:format("~4b/~2..0b/~2..0b ~2..0b:~2..0b:~2..0b",
  116. [Year, Month, Day, Hour, Minute, Second])).
  117. %% TODO: filelib:ensure_dir/1 corrected in R13B04. Remove when we drop
  118. %% support for OTP releases older than R13B04.
  119. ensure_dir(Path) ->
  120. case filelib:ensure_dir(Path) of
  121. ok ->
  122. ok;
  123. {error,eexist} ->
  124. ok;
  125. Error ->
  126. Error
  127. end.
  128. -spec abort() -> no_return().
  129. abort() ->
  130. throw(rebar_abort).
  131. -spec abort(string(), [term()]) -> no_return().
  132. abort(String, Args) ->
  133. ?ERROR(String, Args),
  134. abort().
  135. %% TODO: Rename emulate_escript_foldl to escript_foldl and remove
  136. %% this function when the time is right. escript:foldl/3 was an
  137. %% undocumented exported fun and has been removed in R14.
  138. escript_foldl(Fun, Acc, File) ->
  139. {module, zip} = code:ensure_loaded(zip),
  140. case erlang:function_exported(zip, foldl, 3) of
  141. true ->
  142. emulate_escript_foldl(Fun, Acc, File);
  143. false ->
  144. escript:foldl(Fun, Acc, File)
  145. end.
  146. find_executable(Name) ->
  147. case os:find_executable(Name) of
  148. false -> false;
  149. Path ->
  150. "\"" ++ filename:nativename(Path) ++ "\""
  151. end.
  152. %% Helper function for checking values and aborting when needed
  153. prop_check(true, _, _) -> true;
  154. prop_check(false, Msg, Args) -> ?ABORT(Msg, Args).
  155. %% Convert all the entries in the code path to absolute paths.
  156. expand_code_path() ->
  157. CodePath = lists:foldl(fun (Path, Acc) ->
  158. [filename:absname(Path) | Acc]
  159. end, [], code:get_path()),
  160. code:set_path(lists:reverse(CodePath)).
  161. %%
  162. %% Given env. variable FOO we want to expand all references to
  163. %% it in InStr. References can have two forms: $FOO and ${FOO}
  164. %% The end of form $FOO is delimited with whitespace or eol
  165. %%
  166. expand_env_variable(InStr, VarName, RawVarValue) ->
  167. case string:chr(InStr, $$) of
  168. 0 ->
  169. %% No variables to expand
  170. InStr;
  171. _ ->
  172. VarValue = re:replace(RawVarValue, "\\\\", "\\\\\\\\", [global]),
  173. %% Use a regex to match/replace:
  174. %% Given variable "FOO": match $FOO\s | $FOOeol | ${FOO}
  175. RegEx = io_lib:format("\\\$(~s(\\s|$)|{~s})", [VarName, VarName]),
  176. ReOpts = [global, {return, list}],
  177. re:replace(InStr, RegEx, [VarValue, "\\2"], ReOpts)
  178. end.
  179. vcs_vsn(Config, Vcs, Dir) ->
  180. Key = {Vcs, Dir},
  181. Cache = rebar_config:get_xconf(Config, vsn_cache),
  182. case dict:find(Key, Cache) of
  183. error ->
  184. VsnString = vcs_vsn_1(Vcs, Dir),
  185. Cache1 = dict:store(Key, VsnString, Cache),
  186. Config1 = rebar_config:set_xconf(Config, vsn_cache, Cache1),
  187. {Config1, VsnString};
  188. {ok, VsnString} ->
  189. {Config, VsnString}
  190. end.
  191. get_deprecated_global(Config, OldOpt, NewOpt, When) ->
  192. get_deprecated_global(Config, OldOpt, NewOpt, undefined, When).
  193. get_deprecated_global(Config, OldOpt, NewOpt, Default, When) ->
  194. case rebar_config:get_global(Config, NewOpt, Default) of
  195. Default ->
  196. case rebar_config:get_global(Config, OldOpt, Default) of
  197. Default ->
  198. Default;
  199. Old ->
  200. deprecated(OldOpt, NewOpt, When),
  201. Old
  202. end;
  203. New ->
  204. New
  205. end.
  206. get_deprecated_list(Config, OldOpt, NewOpt, When) ->
  207. get_deprecated_list(Config, OldOpt, NewOpt, undefined, When).
  208. get_deprecated_list(Config, OldOpt, NewOpt, Default, When) ->
  209. get_deprecated_3(fun rebar_config:get_list/3,
  210. Config, OldOpt, NewOpt, Default, When).
  211. get_deprecated_local(Config, OldOpt, NewOpt, When) ->
  212. get_deprecated_local(Config, OldOpt, NewOpt, undefined, When).
  213. get_deprecated_local(Config, OldOpt, NewOpt, Default, When) ->
  214. get_deprecated_3(fun rebar_config:get_local/3,
  215. Config, OldOpt, NewOpt, Default, When).
  216. deprecated(Old, New, Opts, When) when is_list(Opts) ->
  217. case lists:member(Old, Opts) of
  218. true ->
  219. deprecated(Old, New, When);
  220. false ->
  221. ok
  222. end;
  223. deprecated(Old, New, Config, When) ->
  224. case rebar_config:get(Config, Old, undefined) of
  225. undefined ->
  226. ok;
  227. _ ->
  228. deprecated(Old, New, When)
  229. end.
  230. deprecated(Old, New, When) ->
  231. io:format(
  232. <<"WARNING: deprecated ~p option used~n"
  233. "Option '~p' has been deprecated~n"
  234. "in favor of '~p'.~n"
  235. "'~p' will be removed ~s.~n~n">>,
  236. [Old, Old, New, Old, When]).
  237. -spec delayed_halt(integer()) -> no_return().
  238. delayed_halt(Code) ->
  239. %% Work around buffer flushing issue in erlang:halt if OTP older
  240. %% than R15B01.
  241. %% TODO: remove workaround once we require R15B01 or newer
  242. %% R15B01 introduced erlang:halt/2
  243. case erlang:is_builtin(erlang, halt, 2) of
  244. true ->
  245. halt(Code);
  246. false ->
  247. case os:type() of
  248. {win32, nt} ->
  249. timer:sleep(100),
  250. halt(Code);
  251. _ ->
  252. halt(Code),
  253. %% workaround to delay exit until all output is written
  254. receive after infinity -> ok end
  255. end
  256. end.
  257. %% @doc Return list of erl_opts
  258. -spec erl_opts(rebar_config:config()) -> list().
  259. erl_opts(Config) ->
  260. RawErlOpts = filter_defines(rebar_config:get(Config, erl_opts, []), []),
  261. Defines = [{d, list_to_atom(D)} ||
  262. D <- rebar_config:get_xconf(Config, defines, [])],
  263. Opts = Defines ++ RawErlOpts,
  264. case proplists:is_defined(no_debug_info, Opts) of
  265. true ->
  266. [O || O <- Opts, O =/= no_debug_info];
  267. false ->
  268. [debug_info|Opts]
  269. end.
  270. -spec src_dirs([string()]) -> [file:filename(), ...].
  271. src_dirs([]) ->
  272. ["src"];
  273. src_dirs(SrcDirs) ->
  274. SrcDirs.
  275. test_dir() ->
  276. filename:join(get_cwd(), ?TEST_DIR).
  277. ebin_dir() ->
  278. filename:join(get_cwd(), "ebin").
  279. processing_base_dir(Config) ->
  280. Cwd = rebar_utils:get_cwd(),
  281. processing_base_dir(Config, Cwd).
  282. processing_base_dir(Config, Dir) ->
  283. Dir =:= rebar_config:get_xconf(Config, base_dir).
  284. %% ====================================================================
  285. %% Internal functions
  286. %% ====================================================================
  287. os_family() ->
  288. {OsFamily, _} = os:type(),
  289. atom_to_list(OsFamily).
  290. get_deprecated_3(Get, Config, OldOpt, NewOpt, Default, When) ->
  291. case Get(Config, NewOpt, Default) of
  292. Default ->
  293. case Get(Config, OldOpt, Default) of
  294. Default ->
  295. Default;
  296. Old ->
  297. deprecated(OldOpt, NewOpt, When),
  298. Old
  299. end;
  300. New ->
  301. New
  302. end.
  303. %% We do the shell variable substitution ourselves on Windows and hope that the
  304. %% command doesn't use any other shell magic.
  305. patch_on_windows(Cmd, Env) ->
  306. case os:type() of
  307. {win32,nt} ->
  308. Cmd1 = "cmd /q /c "
  309. ++ lists:foldl(fun({Key, Value}, Acc) ->
  310. expand_env_variable(Acc, Key, Value)
  311. end, Cmd, Env),
  312. %% Remove left-over vars
  313. re:replace(Cmd1, "\\\$\\w+|\\\${\\w+}", "", [global, {return, list}]);
  314. _ ->
  315. Cmd
  316. end.
  317. expand_sh_flag(return_on_error) ->
  318. {error_handler,
  319. fun(_Command, Err) ->
  320. {error, Err}
  321. end};
  322. expand_sh_flag({abort_on_error, Message}) ->
  323. {error_handler,
  324. log_msg_and_abort(Message)};
  325. expand_sh_flag(abort_on_error) ->
  326. {error_handler,
  327. fun log_and_abort/2};
  328. expand_sh_flag(use_stdout) ->
  329. {output_handler,
  330. fun(Line, Acc) ->
  331. ?CONSOLE("~s", [Line]),
  332. [Line | Acc]
  333. end};
  334. expand_sh_flag({use_stdout, false}) ->
  335. {output_handler,
  336. fun(Line, Acc) ->
  337. [Line | Acc]
  338. end};
  339. expand_sh_flag({cd, _CdArg} = Cd) ->
  340. {port_settings, Cd};
  341. expand_sh_flag({env, _EnvArg} = Env) ->
  342. {port_settings, Env}.
  343. -type err_handler() :: fun((string(), {integer(), string()}) -> no_return()).
  344. -spec log_msg_and_abort(string()) -> err_handler().
  345. log_msg_and_abort(Message) ->
  346. fun(_Command, {_Rc, _Output}) ->
  347. ?ABORT(Message, [])
  348. end.
  349. -spec log_and_abort(string(), {integer(), string()}) -> no_return().
  350. log_and_abort(Command, {Rc, Output}) ->
  351. ?ABORT("~s failed with error: ~w and output:~n~s~n",
  352. [Command, Rc, Output]).
  353. sh_loop(Port, Fun, Acc) ->
  354. receive
  355. {Port, {data, {eol, Line}}} ->
  356. sh_loop(Port, Fun, Fun(Line ++ "\n", Acc));
  357. {Port, {data, {noeol, Line}}} ->
  358. sh_loop(Port, Fun, Fun(Line, Acc));
  359. {Port, {exit_status, 0}} ->
  360. {ok, lists:flatten(lists:reverse(Acc))};
  361. {Port, {exit_status, Rc}} ->
  362. {error, {Rc, lists:flatten(lists:reverse(Acc))}}
  363. end.
  364. beam_to_mod(Dir, Filename) ->
  365. [Dir | Rest] = filename:split(Filename),
  366. list_to_atom(filename:basename(string:join(Rest, "."), ".beam")).
  367. erl_to_mod(Filename) ->
  368. list_to_atom(filename:rootname(filename:basename(Filename))).
  369. beams(Dir) ->
  370. filelib:fold_files(Dir, ".*\.beam\$", true,
  371. fun(F, Acc) -> [F | Acc] end, []).
  372. emulate_escript_foldl(Fun, Acc, File) ->
  373. case escript:extract(File, [compile_source]) of
  374. {ok, [_Shebang, _Comment, _EmuArgs, Body]} ->
  375. case Body of
  376. {source, BeamCode} ->
  377. GetInfo = fun() -> file:read_file_info(File) end,
  378. GetBin = fun() -> BeamCode end,
  379. {ok, Fun(".", GetInfo, GetBin, Acc)};
  380. {beam, BeamCode} ->
  381. GetInfo = fun() -> file:read_file_info(File) end,
  382. GetBin = fun() -> BeamCode end,
  383. {ok, Fun(".", GetInfo, GetBin, Acc)};
  384. {archive, ArchiveBin} ->
  385. zip:foldl(Fun, Acc, {File, ArchiveBin})
  386. end;
  387. {error, _} = Error ->
  388. Error
  389. end.
  390. vcs_vsn_1(Vcs, Dir) ->
  391. case vcs_vsn_cmd(Vcs) of
  392. {unknown, VsnString} ->
  393. ?DEBUG("vcs_vsn: Unknown VCS atom in vsn field: ~p\n", [Vcs]),
  394. VsnString;
  395. {cmd, CmdString} ->
  396. vcs_vsn_invoke(CmdString, Dir);
  397. Cmd ->
  398. %% If there is a valid VCS directory in the application directory,
  399. %% use that version info
  400. Extension = lists:concat([".", Vcs]),
  401. case filelib:is_dir(filename:join(Dir, Extension)) of
  402. true ->
  403. ?DEBUG("vcs_vsn: Primary vcs used for ~s\n", [Dir]),
  404. vcs_vsn_invoke(Cmd, Dir);
  405. false ->
  406. %% No VCS directory found for the app. Depending on source
  407. %% tree structure, there may be one higher up, but that can
  408. %% yield unexpected results when used with deps. So, we
  409. %% fallback to searching for a priv/vsn.Vcs file.
  410. VsnFile = filename:join([Dir, "priv", "vsn" ++ Extension]),
  411. case file:read_file(VsnFile) of
  412. {ok, VsnBin} ->
  413. ?DEBUG("vcs_vsn: Read ~s from priv/vsn.~p\n",
  414. [VsnBin, Vcs]),
  415. string:strip(binary_to_list(VsnBin), right, $\n);
  416. {error, enoent} ->
  417. ?DEBUG("vcs_vsn: Fallback to vcs for ~s\n", [Dir]),
  418. vcs_vsn_invoke(Cmd, Dir)
  419. end
  420. end
  421. end.
  422. vcs_vsn_cmd(git) ->
  423. %% git describe the last commit that touched CWD
  424. %% required for correct versioning of apps in subdirs, such as apps/app1
  425. case os:type() of
  426. {win32,nt} ->
  427. "FOR /F \"usebackq tokens=* delims=\" %i in "
  428. "(`git log -n 1 \"--pretty=format:%h\" .`) do "
  429. "@git describe --always --tags %i";
  430. _ ->
  431. "git describe --always --tags `git log -n 1 --pretty=format:%h .`"
  432. end;
  433. vcs_vsn_cmd(hg) -> "hg identify -i";
  434. vcs_vsn_cmd(bzr) -> "bzr revno";
  435. vcs_vsn_cmd(svn) -> "svnversion";
  436. vcs_vsn_cmd({cmd, _Cmd}=Custom) -> Custom;
  437. vcs_vsn_cmd(Version) -> {unknown, Version}.
  438. vcs_vsn_invoke(Cmd, Dir) ->
  439. {ok, VsnString} = rebar_utils:sh(Cmd, [{cd, Dir}, {use_stdout, false}]),
  440. string:strip(VsnString, right, $\n).
  441. %%
  442. %% Filter a list of erl_opts platform_define options such that only
  443. %% those which match the provided architecture regex are returned.
  444. %%
  445. filter_defines([], Acc) ->
  446. lists:reverse(Acc);
  447. filter_defines([{platform_define, ArchRegex, Key} | Rest], Acc) ->
  448. case rebar_utils:is_arch(ArchRegex) of
  449. true ->
  450. filter_defines(Rest, [{d, Key} | Acc]);
  451. false ->
  452. filter_defines(Rest, Acc)
  453. end;
  454. filter_defines([{platform_define, ArchRegex, Key, Value} | Rest], Acc) ->
  455. case rebar_utils:is_arch(ArchRegex) of
  456. true ->
  457. filter_defines(Rest, [{d, Key, Value} | Acc]);
  458. false ->
  459. filter_defines(Rest, Acc)
  460. end;
  461. filter_defines([Opt | Rest], Acc) ->
  462. filter_defines(Rest, [Opt | Acc]).