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.

384 line
14 KiB

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