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.

400 rivejä
14 KiB

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