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.

378 lines
13 KiB

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