Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

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