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.

528 lines
18 KiB

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