Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

427 righe
15 KiB

  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.2", 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, {_, _, Host, Port, _, _}} = http_uri:parse(Proxy),
  130. httpc:set_options([{Scheme, {{Host, Port}, []}}], rebar).
  131. compile(App, FirstFiles) ->
  132. Dir = filename:join(filename:absname("_build/default/lib/"), App),
  133. filelib:ensure_dir(filename:join([Dir, "ebin", "dummy.beam"])),
  134. code:add_path(filename:join(Dir, "ebin")),
  135. FirstFilesPaths = [filename:join([Dir, "src", Module]) || Module <- FirstFiles],
  136. Sources = FirstFilesPaths ++ filelib:wildcard(filename:join([Dir, "src", "*.erl"])),
  137. [compile_file(X, [{i, filename:join(Dir, "include")}
  138. ,debug_info
  139. ,{outdir, filename:join(Dir, "ebin")}
  140. ,return | additional_defines()]) || X <- Sources].
  141. compile_file(File, Opts) ->
  142. case compile:file(File, Opts) of
  143. {ok, _Mod} ->
  144. ok;
  145. {ok, _Mod, []} ->
  146. ok;
  147. {ok, _Mod, Ws} ->
  148. io:format("~s~n", [format_warnings(File, Ws)]),
  149. halt(1);
  150. {error, Es, Ws} ->
  151. io:format("~s ~s~n", [format_errors(File, Es), format_warnings(File, Ws)]),
  152. halt(1)
  153. end.
  154. bootstrap_rebar3() ->
  155. filelib:ensure_dir("_build/default/lib/rebar/ebin/dummy.beam"),
  156. code:add_path("_build/default/lib/rebar/ebin/"),
  157. ok = symlink_or_copy(filename:absname("src"),
  158. filename:absname("_build/default/lib/rebar/src")),
  159. Sources = ["src/rebar_resource.erl" | filelib:wildcard("src/*.erl")],
  160. [compile_file(X, [{outdir, "_build/default/lib/rebar/ebin/"}
  161. ,return | additional_defines()]) || X <- Sources],
  162. code:add_patha(filename:absname("_build/default/lib/rebar/ebin")).
  163. %%rebar.hrl
  164. -define(FMT(Str, Args), lists:flatten(io_lib:format(Str, Args))).
  165. %%/rebar.hrl
  166. %%rebar_file_utils
  167. symlink_or_copy(Source, Target) ->
  168. Link = case os:type() of
  169. {win32, _} ->
  170. Source;
  171. _ ->
  172. make_relative_path(Source, Target)
  173. end,
  174. case file:make_symlink(Link, Target) of
  175. ok ->
  176. ok;
  177. {error, eexist} ->
  178. ok;
  179. {error, _} ->
  180. cp_r([Source], Target)
  181. end.
  182. make_relative_path(Source, Target) ->
  183. do_make_relative_path(filename:split(Source), filename:split(Target)).
  184. do_make_relative_path([H|T1], [H|T2]) ->
  185. do_make_relative_path(T1, T2);
  186. do_make_relative_path(Source, Target) ->
  187. Base = lists:duplicate(max(length(Target) - 1, 0), ".."),
  188. filename:join(Base ++ Source).
  189. cp_r([], _Dest) ->
  190. ok;
  191. cp_r(Sources, Dest) ->
  192. case os:type() of
  193. {unix, _} ->
  194. EscSources = [escape_path(Src) || Src <- Sources],
  195. SourceStr = string:join(EscSources, " "),
  196. os:cmd(?FMT("cp -R ~s \"~s\"", [SourceStr, Dest])),
  197. ok;
  198. {win32, _} ->
  199. lists:foreach(fun(Src) -> ok = cp_r_win32(Src,Dest) end, Sources),
  200. ok
  201. end.
  202. xcopy_win32(Source,Dest)->
  203. R = os:cmd(?FMT("xcopy \"~s\" \"~s\" /q /y /e 2> nul",
  204. [filename:nativename(Source), filename:nativename(Dest)])),
  205. case length(R) > 0 of
  206. %% when xcopy fails, stdout is empty and and error message is printed
  207. %% to stderr (which is redirected to nul)
  208. true -> ok;
  209. false ->
  210. {error, lists:flatten(
  211. io_lib:format("Failed to xcopy from ~s to ~s~n",
  212. [Source, Dest]))}
  213. end.
  214. cp_r_win32({true, SourceDir}, {true, DestDir}) ->
  215. %% from directory to directory
  216. SourceBase = filename:basename(SourceDir),
  217. ok = case file:make_dir(filename:join(DestDir, SourceBase)) of
  218. {error, eexist} -> ok;
  219. Other -> Other
  220. end,
  221. ok = xcopy_win32(SourceDir, filename:join(DestDir, SourceBase));
  222. cp_r_win32({false, Source} = S,{true, DestDir}) ->
  223. %% from file to directory
  224. cp_r_win32(S, {false, filename:join(DestDir, filename:basename(Source))});
  225. cp_r_win32({false, Source},{false, Dest}) ->
  226. %% from file to file
  227. {ok,_} = file:copy(Source, Dest),
  228. ok;
  229. cp_r_win32({true, SourceDir}, {false, DestDir}) ->
  230. case filelib:is_regular(DestDir) of
  231. true ->
  232. %% From directory to file? This shouldn't happen
  233. {error, lists:flatten(
  234. io_lib:format("Cannot copy dir (~p) to file (~p)\n",
  235. [SourceDir, DestDir]))};
  236. false ->
  237. %% Specifying a target directory that doesn't currently exist.
  238. %% So let's attempt to create this directory
  239. case filelib:ensure_dir(filename:join(DestDir, "dummy")) of
  240. ok ->
  241. ok = xcopy_win32(SourceDir, DestDir);
  242. {error, Reason} ->
  243. {error, lists:flatten(
  244. io_lib:format("Unable to create dir ~p: ~p\n",
  245. [DestDir, Reason]))}
  246. end
  247. end;
  248. cp_r_win32(Source,Dest) ->
  249. Dst = {filelib:is_dir(Dest), Dest},
  250. lists:foreach(fun(Src) ->
  251. ok = cp_r_win32({filelib:is_dir(Src), Src}, Dst)
  252. end, filelib:wildcard(Source)),
  253. ok.
  254. escape_path(Str) ->
  255. re:replace(Str, "([ ()?])", "\\\\&", [global, {return, list}]).
  256. %%/rebar_file_utils
  257. setup_env() ->
  258. %% We don't need or want relx providers loaded yet
  259. application:load(rebar),
  260. {ok, Providers} = application:get_env(rebar, providers),
  261. Providers1 = Providers -- [rebar_prv_release,
  262. rebar_prv_relup,
  263. rebar_prv_tar],
  264. application:set_env(rebar, providers, Providers1).
  265. reset_env() ->
  266. %% Reset the env so we get all providers
  267. application:unset_env(rebar, providers),
  268. application:unload(rebar),
  269. application:load(rebar).
  270. write_windows_scripts() ->
  271. CmdScript=
  272. "@echo off\r\n"
  273. "setlocal\r\n"
  274. "set rebarscript=%~f0\r\n"
  275. "escript.exe \"%rebarscript:.cmd=%\" %*\r\n",
  276. ok = file:write_file("rebar3.cmd", CmdScript).
  277. get_deps() ->
  278. case file:consult("rebar.lock") of
  279. {ok, [[]]} ->
  280. %% Something went wrong in a previous build, lock file shouldn't be empty
  281. io:format("Empty list in lock file, deleting rebar.lock~n"),
  282. ok = file:delete("rebar.lock"),
  283. {ok, Config} = file:consult("rebar.config"),
  284. proplists:get_value(deps, Config);
  285. {ok, [Deps]} ->
  286. [{binary_to_atom(Name, utf8), "", Source} || {Name, Source, _Level} <- Deps];
  287. _ ->
  288. {ok, Config} = file:consult("rebar.config"),
  289. proplists:get_value(deps, Config)
  290. end.
  291. format_errors(Source, Errors) ->
  292. format_errors(Source, "", Errors).
  293. format_warnings(Source, Warnings) ->
  294. format_warnings(Source, Warnings, []).
  295. format_warnings(Source, Warnings, Opts) ->
  296. Prefix = case lists:member(warnings_as_errors, Opts) of
  297. true -> "";
  298. false -> "Warning: "
  299. end,
  300. format_errors(Source, Prefix, Warnings).
  301. format_errors(_MainSource, Extra, Errors) ->
  302. [begin
  303. [format_error(Source, Extra, Desc) || Desc <- Descs]
  304. end
  305. || {Source, Descs} <- Errors].
  306. format_error(AbsSource, Extra, {{Line, Column}, Mod, Desc}) ->
  307. ErrorDesc = Mod:format_error(Desc),
  308. io_lib:format("~s:~w:~w: ~s~s~n", [AbsSource, Line, Column, Extra, ErrorDesc]);
  309. format_error(AbsSource, Extra, {Line, Mod, Desc}) ->
  310. ErrorDesc = Mod:format_error(Desc),
  311. io_lib:format("~s:~w: ~s~s~n", [AbsSource, Line, Extra, ErrorDesc]);
  312. format_error(AbsSource, Extra, {Mod, Desc}) ->
  313. ErrorDesc = Mod:format_error(Desc),
  314. io_lib:format("~s: ~s~s~n", [AbsSource, Extra, ErrorDesc]).
  315. additional_defines() ->
  316. [{d, D} || {Re, D} <- [{"^[0-9]+", namespaced_types}, {"^R1[4|5]", deprecated_crypto}, {"^((1[8|9])|2)", rand_module}], is_otp_release(Re)].
  317. is_otp_release(ArchRegex) ->
  318. case re:run(otp_release(), ArchRegex, [{capture, none}]) of
  319. match ->
  320. true;
  321. nomatch ->
  322. false
  323. end.
  324. otp_release() ->
  325. otp_release1(erlang:system_info(otp_release)).
  326. %% If OTP <= R16, otp_release is already what we want.
  327. otp_release1([$R,N|_]=Rel) when is_integer(N) ->
  328. Rel;
  329. %% If OTP >= 17.x, erlang:system_info(otp_release) returns just the
  330. %% major version number, we have to read the full version from
  331. %% a file. See http://www.erlang.org/doc/system_principles/versions.html
  332. %% Read vsn string from the 'OTP_VERSION' file and return as list without
  333. %% the "\n".
  334. otp_release1(Rel) ->
  335. File = filename:join([code:root_dir(), "releases", Rel, "OTP_VERSION"]),
  336. case file:read_file(File) of
  337. {error, _} ->
  338. Rel;
  339. {ok, Vsn} ->
  340. %% It's fine to rely on the binary module here because we can
  341. %% be sure that it's available when the otp_release string does
  342. %% not begin with $R.
  343. Size = byte_size(Vsn),
  344. %% The shortest vsn string consists of at least two digits
  345. %% followed by "\n". Therefore, it's safe to assume Size >= 3.
  346. case binary:part(Vsn, {Size, -3}) of
  347. <<"**\n">> ->
  348. %% The OTP documentation mentions that a system patched
  349. %% using the otp_patch_apply tool available to licensed
  350. %% customers will leave a '**' suffix in the version as a
  351. %% flag saying the system consists of application versions
  352. %% from multiple OTP versions. We ignore this flag and
  353. %% drop the suffix, given for all intents and purposes, we
  354. %% cannot obtain relevant information from it as far as
  355. %% tooling is concerned.
  356. binary:bin_to_list(Vsn, {0, Size - 3});
  357. _ ->
  358. binary:bin_to_list(Vsn, {0, Size - 1})
  359. end
  360. end.
  361. %% extracts username and password from HTTPS_PROXY and returns them as tuple
  362. get_proxy_auth() ->
  363. get_proxy_auth(get_http_vars(https_proxy)).
  364. get_proxy_auth([]) ->
  365. [];
  366. get_proxy_auth(HttpsProxy) ->
  367. {ok, {_, UserInfo, _, _, _, _}} = http_uri:parse(HttpsProxy),
  368. parse_user_info(UserInfo).
  369. parse_user_info([]) ->
  370. [];
  371. parse_user_info(UserInfo) ->
  372. Idx = string:chr(UserInfo, $:),
  373. Username = string:sub_string(UserInfo, 1, Idx-1),
  374. Password = string:sub_string(UserInfo, Idx+1),
  375. %% password may contain url encoded characters, need to decode them first
  376. [{proxy_auth, {Username, http_uri:decode(Password)}}].