選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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