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.

424 lines
15 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. #!/usr/bin/env escript
  2. %% -*- mode: erlang;erlang-indent-level: 4;indent-tabs-mode: nil -*-
  3. %% ex: ft=erlang ts=4 sw=4 et
  4. main(_) ->
  5. application:start(crypto),
  6. application:start(asn1),
  7. application:start(public_key),
  8. application:start(ssl),
  9. inets:start(),
  10. inets:start(httpc, [{profile, rebar}]),
  11. set_httpc_options(),
  12. %% Fetch and build deps required to build rebar3
  13. BaseDeps = [{providers, []}
  14. ,{getopt, []}
  15. ,{cf, []}
  16. ,{erlware_commons, ["ec_dictionary.erl", "ec_vsn.erl"]}
  17. ,{certifi, []}],
  18. Deps = get_deps(),
  19. [fetch_and_compile(Dep, Deps) || Dep <- BaseDeps],
  20. %% Build rebar3 modules with compile:file
  21. bootstrap_rebar3(),
  22. %% Build rebar.app from rebar.app.src
  23. {ok, App} = rebar_app_info:new(rebar, "3.3.4", filename:absname("_build/default/lib/rebar/")),
  24. rebar_otp_app:compile(rebar_state:new(), App),
  25. %% Because we are compiling files that are loaded already we want to silence
  26. %% not_purged errors in rebar_erlc_compiler:opts_changed/1
  27. error_logger:tty(false),
  28. setup_env(),
  29. os:putenv("REBAR_PROFILE", "bootstrap"),
  30. RegistryFile = default_registry_file(),
  31. case filelib:is_file(RegistryFile) of
  32. true ->
  33. ok;
  34. false ->
  35. rebar3:run(["update"])
  36. end,
  37. {ok, State} = rebar3:run(["compile"]),
  38. reset_env(),
  39. os:putenv("REBAR_PROFILE", ""),
  40. DepsPaths = rebar_state:code_paths(State, all_deps),
  41. code:add_pathsa(DepsPaths),
  42. rebar3:run(["clean", "-a"]),
  43. rebar3:run(["escriptize"]),
  44. %% Done with compile, can turn back on error logger
  45. error_logger:tty(true),
  46. %% Finally, update executable perms for our script on *nix,
  47. %% or write out script files on win32.
  48. ec_file:copy("_build/default/bin/rebar3", "./rebar3"),
  49. case os:type() of
  50. {unix,_} ->
  51. [] = os:cmd("chmod u+x rebar3"),
  52. ok;
  53. {win32,_} ->
  54. write_windows_scripts(),
  55. ok;
  56. _ ->
  57. ok
  58. end.
  59. default_registry_file() ->
  60. {ok, [[Home]]} = init:get_argument(home),
  61. CacheDir = filename:join([Home, ".cache", "rebar3"]),
  62. filename:join([CacheDir, "hex", "default", "registry"]).
  63. fetch_and_compile({Name, ErlFirstFiles}, Deps) ->
  64. case lists:keyfind(Name, 1, Deps) of
  65. {Name, Vsn} ->
  66. ok = fetch({pkg, atom_to_binary(Name, utf8), list_to_binary(Vsn)}, Name);
  67. {Name, _, Source} ->
  68. ok = fetch(Source, Name)
  69. end,
  70. %% Hack: erlware_commons depends on a .script file to check if it is being built with
  71. %% rebar2 or rebar3. But since rebar3 isn't built yet it can't get the vsn with get_key.
  72. %% So we simply make sure that file is deleted before compiling
  73. file:delete("_build/default/lib/erlware_commons/rebar.config.script"),
  74. compile(Name, ErlFirstFiles).
  75. fetch({pkg, Name, Vsn}, App) ->
  76. Dir = filename:join([filename:absname("_build/default/lib/"), App]),
  77. case filelib:is_dir(Dir) of
  78. false ->
  79. CDN = "https://repo.hex.pm/tarballs",
  80. Package = binary_to_list(<<Name/binary, "-", Vsn/binary, ".tar">>),
  81. Url = string:join([CDN, Package], "/"),
  82. case request(Url) of
  83. {ok, Binary} ->
  84. {ok, Contents} = extract(Binary),
  85. ok = erl_tar:extract({binary, Contents}, [{cwd, Dir}, compressed]);
  86. {error, {Reason, _}} ->
  87. ReasonText = re:replace(atom_to_list(Reason), "_", " ", [global,{return,list}]),
  88. io:format("Error: Unable to fetch package ~s ~s: ~s~n", [Name, Vsn, ReasonText])
  89. end;
  90. true ->
  91. io:format("Dependency ~s already exists~n", [Name])
  92. end.
  93. extract(Binary) ->
  94. {ok, Files} = erl_tar:extract({binary, Binary}, [memory]),
  95. {"contents.tar.gz", Contents} = lists:keyfind("contents.tar.gz", 1, Files),
  96. {ok, Contents}.
  97. request(Url) ->
  98. HttpOptions = [{relaxed, true} | get_proxy_auth()],
  99. case httpc:request(get, {Url, []},
  100. HttpOptions,
  101. [{body_format, binary}],
  102. rebar) of
  103. {ok, {{_Version, 200, _Reason}, _Headers, Body}} ->
  104. {ok, Body};
  105. Error ->
  106. Error
  107. end.
  108. get_rebar_config() ->
  109. {ok, [[Home]]} = init:get_argument(home),
  110. ConfDir = filename:join(Home, ".config/rebar3"),
  111. case file:consult(filename:join(ConfDir, "rebar.config")) of
  112. {ok, Config} ->
  113. Config;
  114. _ ->
  115. []
  116. end.
  117. get_http_vars(Scheme) ->
  118. OS = case os:getenv(atom_to_list(Scheme)) of
  119. Str when is_list(Str) -> Str;
  120. _ -> []
  121. end,
  122. proplists:get_value(Scheme, get_rebar_config(), OS).
  123. set_httpc_options() ->
  124. set_httpc_options(https_proxy, get_http_vars(https_proxy)),
  125. set_httpc_options(proxy, get_http_vars(http_proxy)).
  126. set_httpc_options(_, []) ->
  127. ok;
  128. set_httpc_options(Scheme, Proxy) ->
  129. {ok, {_, UserInfo, Host, Port, _, _}} = http_uri:parse(Proxy),
  130. httpc:set_options([{Scheme, {{Host, Port}, []}}], rebar),
  131. set_proxy_auth(UserInfo).
  132. compile(App, FirstFiles) ->
  133. Dir = filename:join(filename:absname("_build/default/lib/"), App),
  134. filelib:ensure_dir(filename:join([Dir, "ebin", "dummy.beam"])),
  135. code:add_path(filename:join(Dir, "ebin")),
  136. FirstFilesPaths = [filename:join([Dir, "src", Module]) || Module <- FirstFiles],
  137. Sources = FirstFilesPaths ++ filelib:wildcard(filename:join([Dir, "src", "*.erl"])),
  138. [compile_file(X, [{i, filename:join(Dir, "include")}
  139. ,debug_info
  140. ,{outdir, filename:join(Dir, "ebin")}
  141. ,return | additional_defines()]) || X <- Sources].
  142. compile_file(File, Opts) ->
  143. case compile:file(File, Opts) of
  144. {ok, _Mod} ->
  145. ok;
  146. {ok, _Mod, []} ->
  147. ok;
  148. {ok, _Mod, Ws} ->
  149. io:format("~s~n", [format_warnings(File, Ws)]),
  150. halt(1);
  151. {error, Es, Ws} ->
  152. io:format("~s ~s~n", [format_errors(File, Es), format_warnings(File, Ws)]),
  153. halt(1)
  154. end.
  155. bootstrap_rebar3() ->
  156. filelib:ensure_dir("_build/default/lib/rebar/ebin/dummy.beam"),
  157. code:add_path("_build/default/lib/rebar/ebin/"),
  158. ok = symlink_or_copy(filename:absname("src"),
  159. filename:absname("_build/default/lib/rebar/src")),
  160. Sources = ["src/rebar_resource.erl" | filelib:wildcard("src/*.erl")],
  161. [compile_file(X, [{outdir, "_build/default/lib/rebar/ebin/"}
  162. ,return | additional_defines()]) || X <- Sources],
  163. code:add_patha(filename:absname("_build/default/lib/rebar/ebin")).
  164. %%rebar.hrl
  165. -define(FMT(Str, Args), lists:flatten(io_lib:format(Str, Args))).
  166. %%/rebar.hrl
  167. %%rebar_file_utils
  168. symlink_or_copy(Source, Target) ->
  169. Link = case os:type() of
  170. {win32, _} ->
  171. Source;
  172. _ ->
  173. make_relative_path(Source, Target)
  174. end,
  175. case file:make_symlink(Link, Target) of
  176. ok ->
  177. ok;
  178. {error, eexist} ->
  179. ok;
  180. {error, _} ->
  181. cp_r([Source], Target)
  182. end.
  183. make_relative_path(Source, Target) ->
  184. do_make_relative_path(filename:split(Source), filename:split(Target)).
  185. do_make_relative_path([H|T1], [H|T2]) ->
  186. do_make_relative_path(T1, T2);
  187. do_make_relative_path(Source, Target) ->
  188. Base = lists:duplicate(max(length(Target) - 1, 0), ".."),
  189. filename:join(Base ++ Source).
  190. cp_r([], _Dest) ->
  191. ok;
  192. cp_r(Sources, Dest) ->
  193. case os:type() of
  194. {unix, _} ->
  195. EscSources = [escape_path(Src) || Src <- Sources],
  196. SourceStr = string:join(EscSources, " "),
  197. os:cmd(?FMT("cp -R ~s \"~s\"", [SourceStr, Dest])),
  198. ok;
  199. {win32, _} ->
  200. lists:foreach(fun(Src) -> ok = cp_r_win32(Src,Dest) end, Sources),
  201. ok
  202. end.
  203. xcopy_win32(Source,Dest)->
  204. R = os:cmd(?FMT("xcopy \"~s\" \"~s\" /q /y /e 2> nul",
  205. [filename:nativename(Source), filename:nativename(Dest)])),
  206. case length(R) > 0 of
  207. %% when xcopy fails, stdout is empty and and error message is printed
  208. %% to stderr (which is redirected to nul)
  209. true -> ok;
  210. false ->
  211. {error, lists:flatten(
  212. io_lib:format("Failed to xcopy from ~s to ~s~n",
  213. [Source, Dest]))}
  214. end.
  215. cp_r_win32({true, SourceDir}, {true, DestDir}) ->
  216. %% from directory to directory
  217. SourceBase = filename:basename(SourceDir),
  218. ok = case file:make_dir(filename:join(DestDir, SourceBase)) of
  219. {error, eexist} -> ok;
  220. Other -> Other
  221. end,
  222. ok = xcopy_win32(SourceDir, filename:join(DestDir, SourceBase));
  223. cp_r_win32({false, Source} = S,{true, DestDir}) ->
  224. %% from file to directory
  225. cp_r_win32(S, {false, filename:join(DestDir, filename:basename(Source))});
  226. cp_r_win32({false, Source},{false, Dest}) ->
  227. %% from file to file
  228. {ok,_} = file:copy(Source, Dest),
  229. ok;
  230. cp_r_win32({true, SourceDir}, {false, DestDir}) ->
  231. case filelib:is_regular(DestDir) of
  232. true ->
  233. %% From directory to file? This shouldn't happen
  234. {error, lists:flatten(
  235. io_lib:format("Cannot copy dir (~p) to file (~p)\n",
  236. [SourceDir, DestDir]))};
  237. false ->
  238. %% Specifying a target directory that doesn't currently exist.
  239. %% So let's attempt to create this directory
  240. case filelib:ensure_dir(filename:join(DestDir, "dummy")) of
  241. ok ->
  242. ok = xcopy_win32(SourceDir, DestDir);
  243. {error, Reason} ->
  244. {error, lists:flatten(
  245. io_lib:format("Unable to create dir ~p: ~p\n",
  246. [DestDir, Reason]))}
  247. end
  248. end;
  249. cp_r_win32(Source,Dest) ->
  250. Dst = {filelib:is_dir(Dest), Dest},
  251. lists:foreach(fun(Src) ->
  252. ok = cp_r_win32({filelib:is_dir(Src), Src}, Dst)
  253. end, filelib:wildcard(Source)),
  254. ok.
  255. escape_path(Str) ->
  256. re:replace(Str, "([ ()?])", "\\\\&", [global, {return, list}]).
  257. %%/rebar_file_utils
  258. setup_env() ->
  259. %% We don't need or want relx providers loaded yet
  260. application:load(rebar),
  261. {ok, Providers} = application:get_env(rebar, providers),
  262. Providers1 = Providers -- [rebar_prv_release,
  263. rebar_prv_relup,
  264. rebar_prv_tar],
  265. application:set_env(rebar, providers, Providers1).
  266. reset_env() ->
  267. %% Reset the env so we get all providers
  268. application:unset_env(rebar, providers),
  269. application:unload(rebar),
  270. application:load(rebar).
  271. write_windows_scripts() ->
  272. CmdScript=
  273. "@echo off\r\n"
  274. "setlocal\r\n"
  275. "set rebarscript=%~f0\r\n"
  276. "escript.exe \"%rebarscript:.cmd=%\" %*\r\n",
  277. ok = file:write_file("rebar3.cmd", CmdScript).
  278. get_deps() ->
  279. case file:consult("rebar.lock") of
  280. {ok, [[]]} ->
  281. %% Something went wrong in a previous build, lock file shouldn't be empty
  282. io:format("Empty list in lock file, deleting rebar.lock~n"),
  283. ok = file:delete("rebar.lock"),
  284. {ok, Config} = file:consult("rebar.config"),
  285. proplists:get_value(deps, Config);
  286. {ok, [Deps]} ->
  287. [{binary_to_atom(Name, utf8), "", Source} || {Name, Source, _Level} <- Deps];
  288. _ ->
  289. {ok, Config} = file:consult("rebar.config"),
  290. proplists:get_value(deps, Config)
  291. end.
  292. format_errors(Source, Errors) ->
  293. format_errors(Source, "", Errors).
  294. format_warnings(Source, Warnings) ->
  295. format_warnings(Source, Warnings, []).
  296. format_warnings(Source, Warnings, Opts) ->
  297. Prefix = case lists:member(warnings_as_errors, Opts) of
  298. true -> "";
  299. false -> "Warning: "
  300. end,
  301. format_errors(Source, Prefix, Warnings).
  302. format_errors(_MainSource, Extra, Errors) ->
  303. [begin
  304. [format_error(Source, Extra, Desc) || Desc <- Descs]
  305. end
  306. || {Source, Descs} <- Errors].
  307. format_error(AbsSource, Extra, {{Line, Column}, Mod, Desc}) ->
  308. ErrorDesc = Mod:format_error(Desc),
  309. io_lib:format("~s:~w:~w: ~s~s~n", [AbsSource, Line, Column, Extra, ErrorDesc]);
  310. format_error(AbsSource, Extra, {Line, Mod, Desc}) ->
  311. ErrorDesc = Mod:format_error(Desc),
  312. io_lib:format("~s:~w: ~s~s~n", [AbsSource, Line, Extra, ErrorDesc]);
  313. format_error(AbsSource, Extra, {Mod, Desc}) ->
  314. ErrorDesc = Mod:format_error(Desc),
  315. io_lib:format("~s: ~s~s~n", [AbsSource, Extra, ErrorDesc]).
  316. additional_defines() ->
  317. [{d, D} || {Re, D} <- [{"^[0-9]+", namespaced_types}, {"^R1[4|5]", deprecated_crypto}, {"^((1[8|9])|2)", rand_module}], is_otp_release(Re)].
  318. is_otp_release(ArchRegex) ->
  319. case re:run(otp_release(), ArchRegex, [{capture, none}]) of
  320. match ->
  321. true;
  322. nomatch ->
  323. false
  324. end.
  325. otp_release() ->
  326. otp_release1(erlang:system_info(otp_release)).
  327. %% If OTP <= R16, otp_release is already what we want.
  328. otp_release1([$R,N|_]=Rel) when is_integer(N) ->
  329. Rel;
  330. %% If OTP >= 17.x, erlang:system_info(otp_release) returns just the
  331. %% major version number, we have to read the full version from
  332. %% a file. See http://www.erlang.org/doc/system_principles/versions.html
  333. %% Read vsn string from the 'OTP_VERSION' file and return as list without
  334. %% the "\n".
  335. otp_release1(Rel) ->
  336. File = filename:join([code:root_dir(), "releases", Rel, "OTP_VERSION"]),
  337. case file:read_file(File) of
  338. {error, _} ->
  339. Rel;
  340. {ok, Vsn} ->
  341. %% It's fine to rely on the binary module here because we can
  342. %% be sure that it's available when the otp_release string does
  343. %% not begin with $R.
  344. Size = byte_size(Vsn),
  345. %% The shortest vsn string consists of at least two digits
  346. %% followed by "\n". Therefore, it's safe to assume Size >= 3.
  347. case binary:part(Vsn, {Size, -3}) of
  348. <<"**\n">> ->
  349. %% The OTP documentation mentions that a system patched
  350. %% using the otp_patch_apply tool available to licensed
  351. %% customers will leave a '**' suffix in the version as a
  352. %% flag saying the system consists of application versions
  353. %% from multiple OTP versions. We ignore this flag and
  354. %% drop the suffix, given for all intents and purposes, we
  355. %% cannot obtain relevant information from it as far as
  356. %% tooling is concerned.
  357. binary:bin_to_list(Vsn, {0, Size - 3});
  358. _ ->
  359. binary:bin_to_list(Vsn, {0, Size - 1})
  360. end
  361. end.
  362. set_proxy_auth([]) ->
  363. ok;
  364. set_proxy_auth(UserInfo) ->
  365. Idx = string:chr(UserInfo, $:),
  366. Username = string:sub_string(UserInfo, 1, Idx-1),
  367. Password = string:sub_string(UserInfo, Idx+1),
  368. %% password may contain url encoded characters, need to decode them first
  369. put(proxy_auth, [{proxy_auth, {Username, http_uri:decode(Password)}}]).
  370. get_proxy_auth() ->
  371. case get(proxy_auth) of
  372. undefined -> [];
  373. ProxyAuth -> ProxyAuth
  374. end.