25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

414 lines
14 KiB

15 년 전
  1. %% -*- tab-width: 4;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_core).
  28. -export([run/1]).
  29. -export([app_dir/1, rel_dir/1]). % Ugh
  30. -include("rebar.hrl").
  31. -ifndef(BUILD_TIME).
  32. -define(BUILD_TIME, "undefined").
  33. -endif.
  34. %% ===================================================================
  35. %% Public API
  36. %% ===================================================================
  37. run(["help"]) ->
  38. help(),
  39. ok;
  40. run(["version"]) ->
  41. %% Load application spec and display vsn and build time info
  42. ok = application:load(rebar),
  43. version(),
  44. ok;
  45. run(RawArgs) ->
  46. %% Pre-load the rebar app so that we get default configuration
  47. ok = application:load(rebar),
  48. %% Parse out command line arguments -- what's left is a list of commands to
  49. %% run
  50. Commands = parse_args(RawArgs),
  51. %% Make sure crypto is running
  52. crypto:start(),
  53. %% Initialize logging system
  54. rebar_log:init(),
  55. %% Convert command strings to atoms
  56. CommandAtoms = [list_to_atom(C) || C <- Commands],
  57. %% Determine the location of the rebar executable; important for pulling
  58. %% resources out of the escript
  59. rebar_config:set_global(escript, filename:absname(escript:script_name())),
  60. ?DEBUG("Rebar location: ~p\n", [rebar_config:get_global(escript, undefined)]),
  61. %% Load rebar.config, if it exists
  62. process_dir(rebar_utils:get_cwd(), rebar_config:new(), CommandAtoms).
  63. %% ===================================================================
  64. %% Internal functions
  65. %% ===================================================================
  66. %%
  67. %% Parse command line arguments using getopt and also filtering out any
  68. %% key=value pairs. What's left is the list of commands to run
  69. %%
  70. parse_args(Args) ->
  71. %% Parse getopt options
  72. OptSpecList = option_spec_list(),
  73. case getopt:parse(OptSpecList, Args) of
  74. {ok, {Options, NonOptArgs}} ->
  75. %% Check options and maybe halt execution
  76. {ok, continue} = show_info_maybe_halt(Options, NonOptArgs),
  77. %% Set global variables based on getopt options
  78. set_global_flag(Options, verbose),
  79. set_global_flag(Options, force),
  80. DefJobs = rebar_config:get_jobs(),
  81. case proplists:get_value(jobs, Options, DefJobs) of
  82. DefJobs ->
  83. ok;
  84. Jobs ->
  85. rebar_config:set_global(jobs, Jobs)
  86. end,
  87. %% Filter all the flags (i.e. strings of form key=value) from the
  88. %% command line arguments. What's left will be the commands to run.
  89. filter_flags(NonOptArgs, []);
  90. {error, {Reason, Data}} ->
  91. ?ERROR("Error: ~s ~p~n~n", [Reason, Data]),
  92. help(),
  93. halt(1)
  94. end.
  95. %%
  96. %% set global flag based on getopt option boolean value
  97. %%
  98. set_global_flag(Options, Flag) ->
  99. Value = case proplists:get_bool(Flag, Options) of
  100. true ->
  101. "1";
  102. false ->
  103. "0"
  104. end,
  105. rebar_config:set_global(Flag, Value).
  106. %%
  107. %% show info and maybe halt execution
  108. %%
  109. show_info_maybe_halt(Opts, NonOptArgs) ->
  110. case proplists:get_bool(help, Opts) of
  111. true ->
  112. help(),
  113. halt(0);
  114. false ->
  115. case proplists:get_bool(commands, Opts) of
  116. true ->
  117. commands(),
  118. halt(0);
  119. false ->
  120. case proplists:get_bool(version, Opts) of
  121. true ->
  122. version(),
  123. halt(0);
  124. false ->
  125. case NonOptArgs of
  126. [] ->
  127. ?CONSOLE("No command to run specified!~n",[]),
  128. help(),
  129. halt(1);
  130. _ ->
  131. {ok, continue}
  132. end
  133. end
  134. end
  135. end.
  136. %%
  137. %% print help/usage string
  138. %%
  139. help() ->
  140. OptSpecList = option_spec_list(),
  141. getopt:usage(OptSpecList, "rebar",
  142. "[var=value,...] <command,...>",
  143. [{"var=value", "rebar global variables (e.g. force=1)"},
  144. {"command", "Command to run (e.g. compile)"}]).
  145. %%
  146. %% print known commands
  147. %%
  148. commands() ->
  149. S = <<"
  150. analyze Analyze with Dialyzer
  151. build_plt Build Dialyzer PLT
  152. check_plt Check Dialyzer PLT
  153. clean Clean
  154. compile Compile sources
  155. create template= [var=foo,...] Create skel based on template and vars
  156. create-app Create simple app skel
  157. create-node Create simple node skel
  158. check-deps Display to be fetched dependencies
  159. get-deps Fetch dependencies
  160. delete-deps Delete fetched dependencies
  161. generate [dump_spec=0/1] Build release with reltool
  162. install [target=] Install build into target
  163. eunit [suite=foo] Run eunit [test/foo_tests.erl] tests
  164. int_test [suite=] [case=] Run ct suites in ./int_test
  165. perf_test [suite=] [case=] Run ct suites in ./perf_test
  166. test [suite=] [case=] Run ct suites in ./test
  167. xref Run cross reference analysis
  168. help Show the program options
  169. version Show version information
  170. ">>,
  171. io:put_chars(S),
  172. %% workaround to delay exit until all output is written
  173. timer:sleep(300).
  174. %%
  175. %% show version information and halt
  176. %%
  177. version() ->
  178. {ok, Vsn} = application:get_key(rebar, vsn),
  179. ?CONSOLE("Version ~s built ~s\n", [Vsn, ?BUILD_TIME]).
  180. %%
  181. %% options accepted via getopt
  182. %%
  183. option_spec_list() ->
  184. Jobs = rebar_config:get_jobs(),
  185. JobsHelp = io_lib:format(
  186. "Number of concurrent workers a command may use. Default: ~B",
  187. [Jobs]),
  188. [
  189. %% {Name, ShortOpt, LongOpt, ArgSpec, HelpMsg}
  190. {help, $h, "help", undefined, "Show the program options"},
  191. {commands, $c, "commands", undefined, "Show available commands"},
  192. {verbose, $v, "verbose", undefined, "Be verbose about what gets done"},
  193. {version, $V, "version", undefined, "Show version information"},
  194. {force, $f, "force", undefined, "Force"},
  195. {jobs, $j, "jobs", integer, JobsHelp}
  196. ].
  197. %%
  198. %% Seperate all commands (single-words) from flags (key=value) and store
  199. %% values into the rebar_config global storage.
  200. %%
  201. filter_flags([], Commands) ->
  202. lists:reverse(Commands);
  203. filter_flags([Item | Rest], Commands) ->
  204. case string:tokens(Item, "=") of
  205. [Command] ->
  206. filter_flags(Rest, [Command | Commands]);
  207. [KeyStr, Value] ->
  208. Key = list_to_atom(KeyStr),
  209. rebar_config:set_global(Key, Value),
  210. filter_flags(Rest, Commands);
  211. Other ->
  212. ?CONSOLE("Ignoring command line argument: ~p\n", [Other]),
  213. filter_flags(Rest, Commands)
  214. end.
  215. process_dir(Dir, ParentConfig, Commands) ->
  216. case filelib:is_dir(Dir) of
  217. false ->
  218. ?WARN("Skipping non-existent sub-dir: ~p\n", [Dir]),
  219. ok;
  220. true ->
  221. ok = file:set_cwd(Dir),
  222. Config = rebar_config:new(ParentConfig),
  223. %% Save the current code path and then update it with
  224. %% lib_dirs. Children inherit parents code path, but we
  225. %% also want to ensure that we restore everything to pristine
  226. %% condition after processing this child
  227. CurrentCodePath = update_code_path(Config),
  228. %% Get the list of processing modules and check each one against
  229. %% CWD to see if it's a fit -- if it is, use that set of modules
  230. %% to process this dir.
  231. {ok, AvailModuleSets} = application:get_env(rebar, modules),
  232. {DirModules, ModuleSetFile} = choose_module_set(AvailModuleSets, Dir),
  233. %% Get the list of modules for "any dir". This is a catch-all list of modules
  234. %% that are processed in addition to modules associated with this directory
  235. %% type. These any_dir modules are processed FIRST.
  236. {ok, AnyDirModules} = application:get_env(rebar, any_dir_modules),
  237. Modules = AnyDirModules ++ DirModules,
  238. %% Give the modules a chance to tweak config and indicate if there
  239. %% are any other dirs that might need processing first.
  240. {UpdatedConfig, Dirs} = acc_modules(select_modules(Modules, preprocess, []),
  241. preprocess, Config, ModuleSetFile, []),
  242. ?DEBUG("~s subdirs: ~p\n", [Dir, Dirs]),
  243. [process_dir(D, UpdatedConfig, Commands) || D <- Dirs],
  244. %% Make sure the CWD is reset properly; processing subdirs may have caused it
  245. %% to change
  246. ok = file:set_cwd(Dir),
  247. %% Finally, process the current working directory
  248. ?DEBUG("Commands: ~p Modules: ~p\n", [Commands, Modules]),
  249. apply_commands(Commands, Modules, UpdatedConfig, ModuleSetFile),
  250. %% Once we're all done processing, reset the code path to whatever
  251. %% the parent initialized it to
  252. restore_code_path(CurrentCodePath),
  253. ok
  254. end.
  255. %%
  256. %% Given a list of module sets from rebar.app and a directory, find
  257. %% the appropriate subset of modules for this directory
  258. %%
  259. choose_module_set([], _Dir) ->
  260. {[], undefined};
  261. choose_module_set([{Fn, Modules} | Rest], Dir) ->
  262. case ?MODULE:Fn(Dir) of
  263. {true, File} ->
  264. {Modules, File};
  265. false ->
  266. choose_module_set(Rest, Dir)
  267. end.
  268. %%
  269. %% Return .app file if the current directory is an OTP app
  270. %%
  271. app_dir(Dir) ->
  272. rebar_app_utils:is_app_dir(Dir).
  273. %%
  274. %% Return the reltool.config file if the current directory is release directory
  275. %%
  276. rel_dir(Dir) ->
  277. rebar_rel_utils:is_rel_dir(Dir).
  278. apply_commands([], _Modules, _Config, _ModuleFile) ->
  279. ok;
  280. apply_commands([Command | Rest], Modules, Config, ModuleFile) ->
  281. case select_modules(Modules, Command, []) of
  282. [] ->
  283. ?WARN("'~p' command does not apply to directory ~s\n",
  284. [Command, rebar_utils:get_cwd()]),
  285. apply_commands(Rest, Modules, Config, ModuleFile);
  286. TargetModules ->
  287. %% Provide some info on where we are
  288. Dir = rebar_utils:get_cwd(),
  289. ?CONSOLE("==> ~s (~s)\n", [filename:basename(Dir), Command]),
  290. %% Run the available modules
  291. case catch(run_modules(TargetModules, Command, Config, ModuleFile)) of
  292. ok ->
  293. apply_commands(Rest, Modules, Config, ModuleFile);
  294. {error, failed} ->
  295. ?FAIL;
  296. Other ->
  297. ?ABORT("~p failed while processing ~s: ~s",
  298. [Command, Dir, io_lib:print(Other, 1,80,-1)])
  299. end
  300. end.
  301. update_code_path(Config) ->
  302. case rebar_config:get(Config, lib_dirs, []) of
  303. [] ->
  304. no_change;
  305. Paths ->
  306. OldPath = code:get_path(),
  307. LibPaths = expand_lib_dirs(Paths, rebar_utils:get_cwd(), []),
  308. ok = code:add_pathsa(LibPaths),
  309. {old, OldPath}
  310. end.
  311. restore_code_path(no_change) ->
  312. ok;
  313. restore_code_path({old, Path}) ->
  314. %% Verify that all of the paths still exist -- some dynamically add paths
  315. %% can get blown away during clean.
  316. true = code:set_path(lists:filter(fun filelib:is_file/1, Path)),
  317. ok.
  318. expand_lib_dirs([], _Root, Acc) ->
  319. Acc;
  320. expand_lib_dirs([Dir | Rest], Root, Acc) ->
  321. Apps = filelib:wildcard(filename:join([Dir, '*', ebin])),
  322. FqApps = [filename:join([Root, A]) || A <- Apps],
  323. expand_lib_dirs(Rest, Root, Acc ++ FqApps).
  324. select_modules([], _Command, Acc) ->
  325. lists:reverse(Acc);
  326. select_modules([Module | Rest], Command, Acc) ->
  327. Exports = Module:module_info(exports),
  328. case lists:member({Command, 2}, Exports) of
  329. true ->
  330. select_modules(Rest, Command, [Module | Acc]);
  331. false ->
  332. select_modules(Rest, Command, Acc)
  333. end.
  334. run_modules([], _Command, _Config, _File) ->
  335. ok;
  336. run_modules([Module | Rest], Command, Config, File) ->
  337. case Module:Command(Config, File) of
  338. ok ->
  339. run_modules(Rest, Command, Config, File);
  340. {error, Reason} ->
  341. {error, Reason}
  342. end.
  343. acc_modules([], _Command, Config, _File, Acc) ->
  344. {Config, Acc};
  345. acc_modules([Module | Rest], Command, Config, File, Acc) ->
  346. case Module:Command(Config, File) of
  347. {ok, NewConfig, Result} when is_list(Result) ->
  348. List = Result;
  349. {ok, NewConfig, Result} ->
  350. List = [Result]
  351. end,
  352. acc_modules(Rest, Command, NewConfig, File, List ++ Acc).