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.

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