25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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