Não pode escolher mais do que 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.

360 linhas
13 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(rebar3).
  28. -export([main/0,
  29. main/1,
  30. run/1,
  31. run/2,
  32. global_option_spec_list/0,
  33. init_config/0,
  34. set_options/2,
  35. parse_args/1,
  36. version/0,
  37. log_level/0]).
  38. -include("rebar.hrl").
  39. %% ====================================================================
  40. %% Public API
  41. %% ====================================================================
  42. %% For running with:
  43. %% erl +sbtu +A0 -noinput -mode minimal -boot start_clean -s rebar3 main -extra "$@"
  44. -spec main() -> no_return().
  45. main() ->
  46. List = init:get_plain_arguments(),
  47. main(List).
  48. %% escript Entry point
  49. -spec main(list()) -> no_return().
  50. main(Args) ->
  51. try run(Args) of
  52. {ok, _State} ->
  53. erlang:halt(0);
  54. Error ->
  55. handle_error(Error)
  56. catch
  57. _:Error ->
  58. handle_error(Error)
  59. end.
  60. %% Erlang-API entry point
  61. run(BaseState, Commands) ->
  62. start_and_load_apps(api),
  63. BaseState1 = rebar_state:set(BaseState, task, Commands),
  64. BaseState2 = rebar_state:set(BaseState1, caller, api),
  65. Verbosity = log_level(),
  66. ok = rebar_log:init(api, Verbosity),
  67. run_aux(BaseState2, Commands).
  68. %% ====================================================================
  69. %% Internal functions
  70. %% ====================================================================
  71. run(RawArgs) ->
  72. start_and_load_apps(command_line),
  73. BaseState = init_config(),
  74. BaseState1 = rebar_state:set(BaseState, caller, command_line),
  75. case erlang:system_info(version) of
  76. "6.1" ->
  77. ?WARN("Due to a filelib bug in Erlang 17.1 it is recommended"
  78. "you update to a newer release.", []);
  79. _ ->
  80. ok
  81. end,
  82. {BaseState2, _Args1} = set_options(BaseState1, {[], []}),
  83. run_aux(BaseState2, RawArgs).
  84. run_aux(State, RawArgs) ->
  85. State1 = case os:getenv("REBAR_PROFILE") of
  86. false ->
  87. State;
  88. "" ->
  89. State;
  90. Profile ->
  91. rebar_state:apply_profiles(State, [list_to_atom(Profile)])
  92. end,
  93. rebar_utils:check_min_otp_version(rebar_state:get(State1, minimum_otp_vsn, undefined)),
  94. rebar_utils:check_blacklisted_otp_versions(rebar_state:get(State1, blacklisted_otp_vsns, undefined)),
  95. State2 = case os:getenv("HEX_CDN") of
  96. false ->
  97. State1;
  98. CDN ->
  99. rebar_state:set(State1, rebar_packages_cdn, CDN)
  100. end,
  101. %% bootstrap test profile
  102. State3 = rebar_state:add_to_profile(State2, test, test_state(State1)),
  103. %% Process each command, resetting any state between each one
  104. BaseDir = rebar_state:get(State, base_dir, ?DEFAULT_BASE_DIR),
  105. State4 = rebar_state:set(State3, base_dir,
  106. filename:join(filename:absname(rebar_state:dir(State3)), BaseDir)),
  107. {ok, Providers} = application:get_env(rebar, providers),
  108. %% Providers can modify profiles stored in opts, so set default after initializing providers
  109. State5 = rebar_state:create_logic_providers(Providers, State4),
  110. %% Initializing project_plugins which can override default providers
  111. State6 = rebar_plugins:project_plugins_install(State5),
  112. State7 = rebar_plugins:top_level_install(State6),
  113. State8 = case os:getenv("REBAR_CACHE_DIR") of
  114. false ->
  115. State7;
  116. ConfigFile ->
  117. rebar_state:set(State7, global_rebar_dir, ConfigFile)
  118. end,
  119. State9 = rebar_state:default(State8, rebar_state:opts(State8)),
  120. {Task, Args} = parse_args(RawArgs),
  121. State10 = rebar_state:code_paths(State9, default, code:get_path()),
  122. rebar_core:init_command(rebar_state:command_args(State10, Args), Task).
  123. init_config() ->
  124. rebar_utils:set_httpc_options(),
  125. %% Initialize logging system
  126. Verbosity = log_level(),
  127. ok = rebar_log:init(command_line, Verbosity),
  128. Config = rebar_config:consult(),
  129. Config1 = rebar_config:merge_locks(Config, rebar_config:consult_lock_file(?LOCK_FILE)),
  130. %% If $HOME/.config/rebar3/rebar.config exists load and use as global config
  131. GlobalConfigFile = rebar_dir:global_config(),
  132. State = case filelib:is_regular(GlobalConfigFile) of
  133. true ->
  134. ?DEBUG("Load global config file ~s", [GlobalConfigFile]),
  135. try state_from_global_config(Config1, GlobalConfigFile)
  136. catch
  137. _:_ ->
  138. ?WARN("Global config ~s exists but can not be read. Ignoring global config values.", [GlobalConfigFile]),
  139. rebar_state:new(Config1)
  140. end;
  141. false ->
  142. rebar_state:new(Config1)
  143. end,
  144. %% Determine the location of the rebar executable; important for pulling
  145. %% resources out of the escript
  146. State1 = try
  147. ScriptName = filename:absname(escript:script_name()),
  148. %% Running with 'erl -s rebar3 main' still sets a name for some reason
  149. %% so verify it is a real file
  150. case filelib:is_regular(ScriptName) of
  151. true ->
  152. rebar_state:escript_path(State, ScriptName);
  153. false ->
  154. State
  155. end
  156. catch
  157. _:_ ->
  158. State
  159. end,
  160. %% TODO: Do we need this still? I think it may still be used.
  161. %% Initialize vsn cache
  162. rebar_state:set(State1, vsn_cache, dict:new()).
  163. parse_args([]) ->
  164. parse_args(["help"]);
  165. parse_args([H | Rest]) when H =:= "-h"
  166. ; H =:= "--help" ->
  167. parse_args(["help" | Rest]);
  168. parse_args([H | Rest]) when H =:= "-v"
  169. ; H =:= "--version" ->
  170. parse_args(["version" | Rest]);
  171. parse_args([Task | RawRest]) ->
  172. {list_to_atom(Task), RawRest}.
  173. set_options(State, {Options, NonOptArgs}) ->
  174. GlobalDefines = proplists:get_all_values(defines, Options),
  175. State1 = rebar_state:set(State, defines, GlobalDefines),
  176. %% Set global variables based on getopt options
  177. State2 = set_global_flag(State1, Options, force),
  178. Task = proplists:get_value(task, Options, "help"),
  179. {rebar_state:set(State2, task, Task), NonOptArgs}.
  180. %%
  181. %% get log level based on getopt option
  182. %%
  183. log_level() ->
  184. case os:getenv("QUIET") of
  185. Q when Q == false; Q == "" ->
  186. DefaultLevel = rebar_log:default_level(),
  187. case os:getenv("DEBUG") of
  188. D when D == false; D == "" ->
  189. DefaultLevel;
  190. _ ->
  191. DefaultLevel + 3
  192. end;
  193. _ ->
  194. rebar_log:error_level()
  195. end.
  196. %%
  197. %% show version information and halt
  198. %%
  199. version() ->
  200. {ok, Vsn} = application:get_key(rebar, vsn),
  201. ?CONSOLE("rebar ~s on Erlang/OTP ~s Erts ~s",
  202. [Vsn, erlang:system_info(otp_release), erlang:system_info(version)]).
  203. %% TODO: Actually make it 'global'
  204. %%
  205. %% set global flag based on getopt option boolean value
  206. %%
  207. set_global_flag(State, Options, Flag) ->
  208. Value = case proplists:get_bool(Flag, Options) of
  209. true ->
  210. "1";
  211. false ->
  212. "0"
  213. end,
  214. rebar_state:set(State, Flag, Value).
  215. %%
  216. %% options accepted via getopt
  217. %%
  218. global_option_spec_list() ->
  219. [
  220. %% {Name, ShortOpt, LongOpt, ArgSpec, HelpMsg}
  221. {help, $h, "help", undefined, "Print this help."},
  222. {version, $v, "version", undefined, "Show version information."},
  223. {task, undefined, undefined, string, "Task to run."}
  224. ].
  225. handle_error(rebar_abort) ->
  226. erlang:halt(1);
  227. handle_error({error, rebar_abort}) ->
  228. erlang:halt(1);
  229. handle_error({error, {Module, Reason}}) ->
  230. case code:which(Module) of
  231. non_existing ->
  232. ?CRASHDUMP("~p: ~p~n~p~n~n", [Module, Reason, erlang:get_stacktrace()]),
  233. ?ERROR("Uncaught error in rebar_core. Run with DEBUG=1 to stacktrace or consult rebar3.crashdump", []),
  234. ?DEBUG("Uncaught error: ~p ~p", [Module, Reason]),
  235. ?INFO("When submitting a bug report, please include the output of `rebar3 report \"your command\"`", []);
  236. _ ->
  237. ?ERROR("~s", [Module:format_error(Reason)])
  238. end,
  239. erlang:halt(1);
  240. handle_error({error, Error}) when is_list(Error) ->
  241. ?ERROR("~s", [Error]),
  242. erlang:halt(1);
  243. handle_error(Error) ->
  244. %% Nothing should percolate up from rebar_core;
  245. %% Dump this error to console
  246. StackTrace = erlang:get_stacktrace(),
  247. ?CRASHDUMP("Error: ~p~n~p~n~n", [Error, StackTrace]),
  248. ?ERROR("Uncaught error in rebar_core. Run with DEBUG=1 to see stacktrace or consult rebar3.crashdump", []),
  249. ?DEBUG("Uncaught error: ~p", [Error]),
  250. case StackTrace of
  251. [] -> ok;
  252. Trace ->
  253. ?DEBUG("Stack trace to the error location:~n~p", [Trace])
  254. end,
  255. ?INFO("When submitting a bug report, please include the output of `rebar3 report \"your command\"`", []),
  256. erlang:halt(1).
  257. start_and_load_apps(Caller) ->
  258. _ = application:load(rebar),
  259. %% Make sure crypto is running
  260. ensure_running(crypto, Caller),
  261. ensure_running(asn1, Caller),
  262. ensure_running(public_key, Caller),
  263. ensure_running(ssl, Caller),
  264. inets:start(),
  265. inets:start(httpc, [{profile, rebar}]).
  266. ensure_running(App, Caller) ->
  267. case application:start(App) of
  268. ok -> ok;
  269. {error, {already_started, App}} -> ok;
  270. {error, Reason} ->
  271. %% These errors keep rebar3's own configuration to be loaded,
  272. %% which disables the log level and causes a failure without
  273. %% showing the error message. Bypass this entirely by overriding
  274. %% the default value (which allows logging to take place)
  275. %% and shut things down manually.
  276. Log = ec_cmd_log:new(warn, Caller),
  277. ec_cmd_log:error(Log, "Rebar dependency ~p could not be loaded "
  278. "for reason ~p~n", [App, Reason]),
  279. throw(rebar_abort)
  280. end.
  281. state_from_global_config(Config, GlobalConfigFile) ->
  282. GlobalConfigTerms = rebar_config:consult_file(GlobalConfigFile),
  283. GlobalConfig = rebar_state:new(GlobalConfigTerms),
  284. %% We don't want to worry about global plugin install state effecting later
  285. %% usage. So we throw away the global profile state used for plugin install.
  286. GlobalConfigThrowAway = rebar_state:current_profiles(GlobalConfig, [global]),
  287. GlobalState = case rebar_state:get(GlobalConfigThrowAway, plugins, []) of
  288. [] ->
  289. GlobalConfigThrowAway;
  290. GlobalPluginsToInstall ->
  291. rebar_plugins:handle_plugins(global,
  292. GlobalPluginsToInstall,
  293. GlobalConfigThrowAway)
  294. end,
  295. GlobalPlugins = rebar_state:providers(GlobalState),
  296. GlobalConfig2 = rebar_state:set(GlobalConfig, plugins, []),
  297. GlobalConfig3 = rebar_state:set(GlobalConfig2, {plugins, global}, rebar_state:get(GlobalConfigThrowAway, plugins, [])),
  298. rebar_state:providers(rebar_state:new(GlobalConfig3, Config), GlobalPlugins).
  299. test_state(State) ->
  300. ErlOpts = rebar_state:get(State, erl_opts, []),
  301. TestOpts = safe_define_test_macro(ErlOpts),
  302. [{extra_src_dirs, ["test"]}, {erl_opts, TestOpts}].
  303. safe_define_test_macro(Opts) ->
  304. %% defining a compile macro twice results in an exception so
  305. %% make sure 'TEST' is only defined once
  306. case test_defined(Opts) of
  307. true -> [];
  308. false -> [{d, 'TEST'}]
  309. end.
  310. test_defined([{d, 'TEST'}|_]) -> true;
  311. test_defined([{d, 'TEST', true}|_]) -> true;
  312. test_defined([_|Rest]) -> test_defined(Rest);
  313. test_defined([]) -> false.