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.

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