Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

731 linhas
27 KiB

10 anos atrás
10 anos atrás
10 anos atrás
5 anos atrás
10 anos atrás
10 anos atrás
7 anos atrás
10 anos atrás
10 anos atrás
10 anos atrás
10 anos atrás
10 anos atrás
10 anos atrás
10 anos atrás
9 anos atrás
9 anos atrás
9 anos atrás
10 anos atrás
10 anos atrás
10 anos atrás
10 anos atrás
10 anos atrás
10 anos atrás
10 anos atrás
10 anos atrás
10 anos atrás
10 anos atrás
10 anos atrás
10 anos atrás
10 anos atrás
10 anos atrás
10 anos atrás
10 anos atrás
10 anos atrás
  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. ensure_app(crypto),
  6. ensure_app(asn1),
  7. ensure_app(public_key),
  8. ensure_app(ssl),
  9. inets:start(),
  10. inets:start(httpc, [{profile, rebar}]),
  11. set_httpc_options(),
  12. %% Clear directories for builds since bootstrapping may require
  13. %% a changed structure from an older one
  14. rm_rf("_build/bootstrap"),
  15. %% When recompiling rebar3 itself, the path swaps and cleaning
  16. %% removes the modules in _build/bootstrap, but the VM still
  17. %% manages to discover those in _build/prod from previous builds and
  18. %% cause weird failures when compilers get modified between releases.
  19. rm_rf("_build/prod"),
  20. %% We fetch a few deps from hex for boostraping,
  21. %% so we must compile r3_safe_erl_term.xrl which
  22. %% is part of hex_core.
  23. compile_xrl_file("src/r3_safe_erl_term.xrl"),
  24. %% Fetch and build deps required to build rebar3
  25. BaseDeps = [{providers, []}
  26. ,{getopt, []}
  27. ,{cf, []}
  28. ,{erlware_commons, ["ec_dictionary.erl", "ec_vsn.erl"]}
  29. ,{parse_trans, ["parse_trans.erl", "parse_trans_pp.erl",
  30. "parse_trans_codegen.erl"]}
  31. ,{certifi, []}],
  32. Deps = get_deps(),
  33. [fetch_and_compile(Dep, Deps) || Dep <- BaseDeps],
  34. %% Build rebar3 modules with compile:file
  35. bootstrap_rebar3(),
  36. %% Build rebar.app from rebar.app.src
  37. {ok, App} = rebar_app_info:new(rebar, "3.13.0", filename:absname("_build/default/lib/rebar/")),
  38. rebar_otp_app:compile(rebar_state:new(), App),
  39. %% Because we are compiling files that are loaded already we want to silence
  40. %% not_purged errors in rebar_erlc_compiler:opts_changed/1
  41. error_logger:tty(false),
  42. setup_env(),
  43. os:putenv("REBAR_PROFILE", "bootstrap"),
  44. {ok, State} = rebar3:run(["compile"]),
  45. reset_env(),
  46. os:putenv("REBAR_PROFILE", ""),
  47. DepsPaths = rebar_state:code_paths(State, all_deps),
  48. code:add_pathsa(DepsPaths),
  49. rebar3:run(["clean", "-a"]),
  50. rebar3:run(["as", "prod", "escriptize"]),
  51. %% Done with compile, can turn back on error logger
  52. error_logger:tty(true).
  53. ensure_app(App) ->
  54. case application:start(App) of
  55. ok ->
  56. ok;
  57. {error, _} ->
  58. io:format("OTP Application ~p not available. Please fix "
  59. "your Erlang install to support it and try "
  60. "again.~n", [App]),
  61. halt(1)
  62. end.
  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://repo.hex.pm/tarballs",
  80. Package = binary_to_list(<<Name/binary, "-", Vsn/binary, ".tar">>),
  81. Url = 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. {error, {Reason, _}} ->
  87. ReasonText = re:replace(atom_to_list(Reason), "_", " ", [global,{return,list}]),
  88. io:format("Error: Unable to fetch package ~s ~s: ~s~n", [Name, Vsn, ReasonText])
  89. end;
  90. true ->
  91. io:format("Dependency ~s already exists~n", [Name])
  92. end.
  93. extract(Binary) ->
  94. {ok, Files} = erl_tar:extract({binary, Binary}, [memory]),
  95. {"contents.tar.gz", Contents} = lists:keyfind("contents.tar.gz", 1, Files),
  96. {ok, Contents}.
  97. request(Url) ->
  98. HttpOptions = [{relaxed, true} | get_proxy_auth()],
  99. case httpc:request(get, {Url, []},
  100. HttpOptions,
  101. [{body_format, binary}],
  102. rebar) of
  103. {ok, {{_Version, 200, _Reason}, _Headers, Body}} ->
  104. {ok, Body};
  105. Error ->
  106. Error
  107. end.
  108. get_rebar_config() ->
  109. {ok, [[Home]]} = init:get_argument(home),
  110. ConfDir = filename:join(Home, ".config/rebar3"),
  111. case file:consult(filename:join(ConfDir, "rebar.config")) of
  112. {ok, Config} ->
  113. Config;
  114. _ ->
  115. []
  116. end.
  117. get_http_vars(Scheme) ->
  118. OS = case os:getenv(atom_to_list(Scheme)) of
  119. Str when is_list(Str) -> Str;
  120. _ -> []
  121. end,
  122. proplists:get_value(Scheme, get_rebar_config(), OS).
  123. set_httpc_options() ->
  124. set_httpc_options(https_proxy, get_http_vars(https_proxy)),
  125. set_httpc_options(proxy, get_http_vars(http_proxy)).
  126. set_httpc_options(_, []) ->
  127. ok;
  128. set_httpc_options(Scheme, Proxy) ->
  129. {ok, {_, UserInfo, Host, Port, _, _}} = http_uri:parse(Proxy),
  130. httpc:set_options([{Scheme, {{Host, Port}, []}}], rebar),
  131. proxy_ipfamily(Host, inet:gethostbyname(Host)),
  132. set_proxy_auth(UserInfo).
  133. proxy_ipfamily(_Host, {ok, _}) ->
  134. ok;
  135. proxy_ipfamily(Host, {error, nxdomain}) ->
  136. maybe_proxy_family(Host, inet_db:res_option(inet6)).
  137. maybe_proxy_family(Host, true) ->
  138. maybe_set_ipfamily(inet:gethostbyname(Host, inet), inet);
  139. maybe_proxy_family(Host, false) ->
  140. maybe_set_ipfamily(inet:gethostbyname(Host, inet6), inet6).
  141. maybe_set_ipfamily({ok, _}, Family) ->
  142. httpc:set_options([{ipfamily, Family}], rebar);
  143. maybe_set_ipfamily(_, _Family) ->
  144. ok.
  145. compile(App, FirstFiles) ->
  146. Dir = filename:join(filename:absname("_build/default/lib/"), App),
  147. filelib:ensure_dir(filename:join([Dir, "ebin", "dummy.beam"])),
  148. code:add_path(filename:join(Dir, "ebin")),
  149. FirstFilesPaths = [filename:join([Dir, "src", Module]) || Module <- FirstFiles],
  150. LeexFiles = filelib:wildcard(filename:join([Dir, "src", "*.xrl"])),
  151. [compile_xrl_file(X) || X <- LeexFiles],
  152. YeccFiles = filelib:wildcard(filename:join([Dir, "src", "*.yrl"])),
  153. [compile_yrl_file(X) || X <- YeccFiles],
  154. Sources = FirstFilesPaths ++ filelib:wildcard(filename:join([Dir, "src", "*.erl"])),
  155. [compile_erl_file(X, [{i, filename:join(Dir, "include")}
  156. ,debug_info
  157. ,{outdir, filename:join(Dir, "ebin")}
  158. ,return | additional_defines()]) || X <- Sources].
  159. compile_xrl_file(File) ->
  160. {ok, _} = leex:file(File).
  161. compile_yrl_file(File) ->
  162. {ok, _} = yecc:file(File).
  163. compile_erl_file(File, Opts) ->
  164. case compile:file(File, Opts) of
  165. {ok, _Mod} ->
  166. ok;
  167. {ok, _Mod, []} ->
  168. ok;
  169. {ok, _Mod, Ws} ->
  170. io:format("~s~n", [format_warnings(File, Ws)]),
  171. halt(1);
  172. {error, Es, Ws} ->
  173. io:format("~s ~s~n", [format_errors(File, Es), format_warnings(File, Ws)]),
  174. halt(1)
  175. end.
  176. bootstrap_rebar3() ->
  177. filelib:ensure_dir("_build/default/lib/rebar/ebin/dummy.beam"),
  178. code:add_path("_build/default/lib/rebar/ebin/"),
  179. Res = symlink_or_copy(filename:absname("src"),
  180. filename:absname("_build/default/lib/rebar/src")),
  181. true = Res == ok orelse Res == exists,
  182. Sources = ["src/rebar_resource_v2.erl", "src/rebar_resource.erl" | filelib:wildcard("src/*.erl") ],
  183. [compile_erl_file(X, [{outdir, "_build/default/lib/rebar/ebin/"}
  184. ,return | additional_defines()]) || X <- Sources],
  185. code:add_patha(filename:absname("_build/default/lib/rebar/ebin")).
  186. %%rebar.hrl
  187. -define(FMT(Str, Args), lists:flatten(io_lib:format(Str, Args))).
  188. %%/rebar.hrl
  189. %%rebar_file_utils
  190. -include_lib("kernel/include/file.hrl").
  191. symlink_or_copy(Source, Target) ->
  192. Link = case os:type() of
  193. {win32, _} ->
  194. Source;
  195. _ ->
  196. make_relative_path(Source, Target)
  197. end,
  198. case file:make_symlink(Link, Target) of
  199. ok ->
  200. ok;
  201. {error, eexist} ->
  202. exists;
  203. {error, _} ->
  204. case os:type() of
  205. {win32, _} ->
  206. S = unicode:characters_to_list(Source),
  207. T = unicode:characters_to_list(Target),
  208. case filelib:is_dir(S) of
  209. true ->
  210. win32_symlink_or_copy(S, T);
  211. false ->
  212. cp_r([S], T)
  213. end;
  214. _ ->
  215. case filelib:is_dir(Target) of
  216. true ->
  217. ok;
  218. false ->
  219. cp_r([Source], Target)
  220. end
  221. end
  222. end.
  223. -spec rm_rf(string()) -> 'ok'.
  224. rm_rf(Target) ->
  225. case os:type() of
  226. {unix, _} ->
  227. EscTarget = escape_chars(Target),
  228. {ok, []} = sh(?FMT("rm -rf ~ts", [EscTarget]),
  229. [{use_stdout, false}, abort_on_error]),
  230. ok;
  231. {win32, _} ->
  232. Filelist = filelib:wildcard(Target),
  233. Dirs = [F || F <- Filelist, filelib:is_dir(F)],
  234. Files = Filelist -- Dirs,
  235. ok = delete_each(Files),
  236. ok = delete_each_dir_win32(Dirs),
  237. ok
  238. end.
  239. -spec cp_r(list(string()), file:filename()) -> 'ok'.
  240. cp_r([], _Dest) ->
  241. ok;
  242. cp_r(Sources, Dest) ->
  243. case os:type() of
  244. {unix, _} ->
  245. EscSources = [escape_chars(Src) || Src <- Sources],
  246. SourceStr = join(EscSources, " "),
  247. {ok, []} = sh(?FMT("cp -Rp ~ts \"~ts\"",
  248. [SourceStr, escape_double_quotes(Dest)]),
  249. [{use_stdout, false}, abort_on_error]),
  250. ok;
  251. {win32, _} ->
  252. lists:foreach(fun(Src) -> ok = cp_r_win32(Src,Dest) end, Sources),
  253. ok
  254. end.
  255. %% @private Compatibility function for windows
  256. win32_symlink_or_copy(Source, Target) ->
  257. Res = sh(?FMT("cmd /c mklink /j \"~ts\" \"~ts\"",
  258. [escape_double_quotes(filename:nativename(Target)),
  259. escape_double_quotes(filename:nativename(Source))]),
  260. [{use_stdout, false}, return_on_error]),
  261. case win32_mklink_ok(Res, Target) of
  262. true -> ok;
  263. false -> cp_r_win32(Source, drop_last_dir_from_path(Target))
  264. end.
  265. cp_r_win32({true, SourceDir}, {true, DestDir}) ->
  266. %% from directory to directory
  267. ok = case file:make_dir(DestDir) of
  268. {error, eexist} -> ok;
  269. Other -> Other
  270. end,
  271. ok = xcopy_win32(SourceDir, DestDir);
  272. cp_r_win32({false, Source} = S,{true, DestDir}) ->
  273. %% from file to directory
  274. cp_r_win32(S, {false, filename:join(DestDir, filename:basename(Source))});
  275. cp_r_win32({false, Source},{false, Dest}) ->
  276. %% from file to file
  277. {ok,_} = file:copy(Source, Dest),
  278. ok;
  279. cp_r_win32({true, SourceDir}, {false, DestDir}) ->
  280. case filelib:is_regular(DestDir) of
  281. true ->
  282. %% From directory to file? This shouldn't happen
  283. {error, lists:flatten(
  284. io_lib:format("Cannot copy dir (~p) to file (~p)\n",
  285. [SourceDir, DestDir]))};
  286. false ->
  287. %% Specifying a target directory that doesn't currently exist.
  288. %% So let's attempt to create this directory
  289. case filelib:ensure_dir(filename:join(DestDir, "dummy")) of
  290. ok ->
  291. ok = xcopy_win32(SourceDir, DestDir);
  292. {error, Reason} ->
  293. {error, lists:flatten(
  294. io_lib:format("Unable to create dir ~p: ~p\n",
  295. [DestDir, Reason]))}
  296. end
  297. end;
  298. cp_r_win32(Source,Dest) ->
  299. Dst = {filelib:is_dir(Dest), Dest},
  300. lists:foreach(fun(Src) ->
  301. ok = cp_r_win32({filelib:is_dir(Src), Src}, Dst)
  302. end, filelib:wildcard(Source)),
  303. ok.
  304. %% drops the last 'node' of the filename, presumably the last dir such as 'src'
  305. %% this is because cp_r_win32/2 automatically adds the dir name, to appease
  306. %% robocopy and be more uniform with POSIX
  307. drop_last_dir_from_path([]) ->
  308. [];
  309. drop_last_dir_from_path(Path) ->
  310. case lists:droplast(filename:split(Path)) of
  311. [] -> [];
  312. Dirs -> filename:join(Dirs)
  313. end.
  314. %% @private specifically pattern match against the output
  315. %% of the windows 'mklink' shell call; different values from
  316. %% what win32_ok/1 handles
  317. win32_mklink_ok({ok, _}, _) ->
  318. true;
  319. win32_mklink_ok({error,{1,"Local NTFS volumes are required to complete the operation.\n"}}, _) ->
  320. false;
  321. win32_mklink_ok({error,{1,"Cannot create a file when that file already exists.\n"}}, Target) ->
  322. % File or dir is already in place; find if it is already a symlink (true) or
  323. % if it is a directory (copy-required; false)
  324. is_symlink(Target);
  325. win32_mklink_ok(_, _) ->
  326. false.
  327. xcopy_win32(Source,Dest)->
  328. %% "xcopy \"~ts\" \"~ts\" /q /y /e 2> nul", Changed to robocopy to
  329. %% handle long names. May have issues with older windows.
  330. Cmd = case filelib:is_dir(Source) of
  331. true ->
  332. %% For robocopy, copying /a/b/c/ to /d/e/f/ recursively does not
  333. %% create /d/e/f/c/*, but rather copies all files to /d/e/f/*.
  334. %% The usage we make here expects the former, not the later, so we
  335. %% must manually add the last fragment of a directory to the `Dest`
  336. %% in order to properly replicate POSIX platforms
  337. NewDest = filename:join([Dest, filename:basename(Source)]),
  338. ?FMT("robocopy \"~ts\" \"~ts\" /e 1> nul",
  339. [escape_double_quotes(filename:nativename(Source)),
  340. escape_double_quotes(filename:nativename(NewDest))]);
  341. false ->
  342. ?FMT("robocopy \"~ts\" \"~ts\" \"~ts\" /e 1> nul",
  343. [escape_double_quotes(filename:nativename(filename:dirname(Source))),
  344. escape_double_quotes(filename:nativename(Dest)),
  345. escape_double_quotes(filename:basename(Source))])
  346. end,
  347. Res = sh(Cmd, [{use_stdout, false}, return_on_error]),
  348. case win32_ok(Res) of
  349. true -> ok;
  350. false ->
  351. {error, lists:flatten(
  352. io_lib:format("Failed to copy ~ts to ~ts~n",
  353. [Source, Dest]))}
  354. end.
  355. is_symlink(Filename) ->
  356. {ok, Info} = file:read_link_info(Filename),
  357. Info#file_info.type == symlink.
  358. win32_ok({ok, _}) -> true;
  359. win32_ok({error, {Rc, _}}) when Rc<9; Rc=:=16 -> true;
  360. win32_ok(_) -> false.
  361. %% @private windows rm_rf helpers
  362. delete_each([]) ->
  363. ok;
  364. delete_each([File | Rest]) ->
  365. case file:delete(File) of
  366. ok ->
  367. delete_each(Rest);
  368. {error, enoent} ->
  369. delete_each(Rest);
  370. {error, Reason} ->
  371. io:format("Failed to delete file ~ts: ~p\n", [File, Reason]),
  372. error
  373. end.
  374. delete_each_dir_win32([]) -> ok;
  375. delete_each_dir_win32([Dir | Rest]) ->
  376. {ok, []} = sh(?FMT("rd /q /s \"~ts\"",
  377. [escape_double_quotes(filename:nativename(Dir))]),
  378. [{use_stdout, false}, return_on_error]),
  379. delete_each_dir_win32(Rest).
  380. %%/rebar_file_utils
  381. %%rebar_utils
  382. %% escape\ as\ a\ shell\?
  383. escape_chars(Str) when is_atom(Str) ->
  384. escape_chars(atom_to_list(Str));
  385. escape_chars(Str) ->
  386. re:replace(Str, "([ ()?`!$&;\"\'])", "\\\\&",
  387. [global, {return, list}, unicode]).
  388. %% "escape inside these"
  389. escape_double_quotes(Str) ->
  390. re:replace(Str, "([\"\\\\`!$&*;])", "\\\\&",
  391. [global, {return, list}, unicode]).
  392. sh(Command0, Options0) ->
  393. DefaultOptions = [{use_stdout, false}],
  394. Options = [expand_sh_flag(V)
  395. || V <- proplists:compact(Options0 ++ DefaultOptions)],
  396. ErrorHandler = proplists:get_value(error_handler, Options),
  397. OutputHandler = proplists:get_value(output_handler, Options),
  398. Command = lists:flatten(patch_on_windows(Command0, proplists:get_value(env, Options, []))),
  399. PortSettings = proplists:get_all_values(port_settings, Options) ++
  400. [exit_status, {line, 16384}, use_stdio, stderr_to_stdout, hide, eof],
  401. Port = open_port({spawn, Command}, PortSettings),
  402. try
  403. case sh_loop(Port, OutputHandler, []) of
  404. {ok, _Output} = Ok ->
  405. Ok;
  406. {error, {_Rc, _Output}=Err} ->
  407. ErrorHandler(Command, Err)
  408. end
  409. after
  410. port_close(Port)
  411. end.
  412. sh_loop(Port, Fun, Acc) ->
  413. receive
  414. {Port, {data, {eol, Line}}} ->
  415. sh_loop(Port, Fun, Fun(Line ++ "\n", Acc));
  416. {Port, {data, {noeol, Line}}} ->
  417. sh_loop(Port, Fun, Fun(Line, Acc));
  418. {Port, eof} ->
  419. Data = lists:flatten(lists:reverse(Acc)),
  420. receive
  421. {Port, {exit_status, 0}} ->
  422. {ok, Data};
  423. {Port, {exit_status, Rc}} ->
  424. {error, {Rc, Data}}
  425. end
  426. end.
  427. expand_sh_flag(return_on_error) ->
  428. {error_handler,
  429. fun(_Command, Err) ->
  430. {error, Err}
  431. end};
  432. expand_sh_flag(abort_on_error) ->
  433. {error_handler,
  434. %% moved log_and_abort/2 here because some versions somehow had trouble
  435. %% interpreting it and thought `fun log_and_abort/2' was in `erl_eval'
  436. fun(Command, {Rc, Output}) ->
  437. io:format("sh(~ts)~n"
  438. "failed with return code ~w and the following output:~n"
  439. "~ts", [Command, Rc, Output]),
  440. throw(bootstrap_abort)
  441. end};
  442. expand_sh_flag({use_stdout, false}) ->
  443. {output_handler,
  444. fun(Line, Acc) ->
  445. [Line | Acc]
  446. end};
  447. expand_sh_flag({cd, _CdArg} = Cd) ->
  448. {port_settings, Cd};
  449. expand_sh_flag({env, _EnvArg} = Env) ->
  450. {port_settings, Env}.
  451. %% We do the shell variable substitution ourselves on Windows and hope that the
  452. %% command doesn't use any other shell magic.
  453. patch_on_windows(Cmd, Env) ->
  454. case os:type() of
  455. {win32,nt} ->
  456. Cmd1 = "cmd /q /c "
  457. ++ lists:foldl(fun({Key, Value}, Acc) ->
  458. expand_env_variable(Acc, Key, Value)
  459. end, Cmd, Env),
  460. %% Remove left-over vars
  461. re:replace(Cmd1, "\\\$\\w+|\\\${\\w+}", "",
  462. [global, {return, list}, unicode]);
  463. _ ->
  464. Cmd
  465. end.
  466. %% @doc Given env. variable `FOO' we want to expand all references to
  467. %% it in `InStr'. References can have two forms: `$FOO' and `${FOO}'
  468. %% The end of form `$FOO' is delimited with whitespace or EOL
  469. -spec expand_env_variable(string(), string(), term()) -> string().
  470. expand_env_variable(InStr, VarName, RawVarValue) ->
  471. case chr(InStr, $$) of
  472. 0 ->
  473. %% No variables to expand
  474. InStr;
  475. _ ->
  476. ReOpts = [global, unicode, {return, list}],
  477. VarValue = re:replace(RawVarValue, "\\\\", "\\\\\\\\", ReOpts),
  478. %% Use a regex to match/replace:
  479. %% Given variable "FOO": match $FOO\s | $FOOeol | ${FOO}
  480. RegEx = io_lib:format("\\\$(~ts(\\W|$)|{~ts})", [VarName, VarName]),
  481. re:replace(InStr, RegEx, [VarValue, "\\2"], ReOpts)
  482. end.
  483. %%/rebar_utils
  484. %%rebar_dir
  485. make_relative_path(Source, Target) ->
  486. AbsSource = make_normalized_path(Source),
  487. AbsTarget = make_normalized_path(Target),
  488. do_make_relative_path(filename:split(AbsSource), filename:split(AbsTarget)).
  489. %% @private based on fragments of paths, replace the number of common
  490. %% segments by `../' bits, and add the rest of the source alone after it
  491. -spec do_make_relative_path([string()], [string()]) -> file:filename().
  492. do_make_relative_path([H|T1], [H|T2]) ->
  493. do_make_relative_path(T1, T2);
  494. do_make_relative_path(Source, Target) ->
  495. Base = lists:duplicate(max(length(Target) - 1, 0), ".."),
  496. filename:join(Base ++ Source).
  497. make_normalized_path(Path) ->
  498. AbsPath = make_absolute_path(Path),
  499. Components = filename:split(AbsPath),
  500. make_normalized_path(Components, []).
  501. make_absolute_path(Path) ->
  502. case filename:pathtype(Path) of
  503. absolute ->
  504. Path;
  505. relative ->
  506. {ok, Dir} = file:get_cwd(),
  507. filename:join([Dir, Path]);
  508. volumerelative ->
  509. Volume = hd(filename:split(Path)),
  510. {ok, Dir} = file:get_cwd(Volume),
  511. filename:join([Dir, Path])
  512. end.
  513. -spec make_normalized_path([string()], [string()]) -> file:filename().
  514. make_normalized_path([], NormalizedPath) ->
  515. filename:join(lists:reverse(NormalizedPath));
  516. make_normalized_path([H|T], NormalizedPath) ->
  517. case H of
  518. "." when NormalizedPath == [], T == [] -> make_normalized_path(T, ["."]);
  519. "." -> make_normalized_path(T, NormalizedPath);
  520. ".." when NormalizedPath == [] -> make_normalized_path(T, [".."]);
  521. ".." when hd(NormalizedPath) =/= ".." -> make_normalized_path(T, tl(NormalizedPath));
  522. _ -> make_normalized_path(T, [H|NormalizedPath])
  523. end.
  524. %%/rebar_dir
  525. setup_env() ->
  526. %% We don't need or want relx providers loaded yet
  527. application:load(rebar),
  528. {ok, Providers} = application:get_env(rebar, providers),
  529. Providers1 = Providers -- [rebar_prv_release,
  530. rebar_prv_relup,
  531. rebar_prv_tar],
  532. application:set_env(rebar, providers, Providers1).
  533. reset_env() ->
  534. %% Reset the env so we get all providers
  535. application:unset_env(rebar, providers),
  536. application:unload(rebar),
  537. application:load(rebar).
  538. get_deps() ->
  539. case file:consult("rebar.lock") of
  540. {ok, [[]]} ->
  541. %% Something went wrong in a previous build, lock file shouldn't be empty
  542. io:format("Empty list in lock file, deleting rebar.lock~n"),
  543. ok = file:delete("rebar.lock"),
  544. {ok, Config} = file:consult("rebar.config"),
  545. proplists:get_value(deps, Config);
  546. {ok, [Deps]} ->
  547. [{binary_to_atom(Name, utf8), "", Source} || {Name, Source, _Level} <- Deps];
  548. _ ->
  549. {ok, Config} = file:consult("rebar.config"),
  550. proplists:get_value(deps, Config)
  551. end.
  552. format_errors(Source, Errors) ->
  553. format_errors(Source, "", Errors).
  554. format_warnings(Source, Warnings) ->
  555. format_warnings(Source, Warnings, []).
  556. format_warnings(Source, Warnings, Opts) ->
  557. Prefix = case lists:member(warnings_as_errors, Opts) of
  558. true -> "";
  559. false -> "Warning: "
  560. end,
  561. format_errors(Source, Prefix, Warnings).
  562. format_errors(_MainSource, Extra, Errors) ->
  563. [begin
  564. [format_error(Source, Extra, Desc) || Desc <- Descs]
  565. end
  566. || {Source, Descs} <- Errors].
  567. format_error(AbsSource, Extra, {{Line, Column}, Mod, Desc}) ->
  568. ErrorDesc = Mod:format_error(Desc),
  569. io_lib:format("~s:~w:~w: ~s~s~n", [AbsSource, Line, Column, Extra, ErrorDesc]);
  570. format_error(AbsSource, Extra, {Line, Mod, Desc}) ->
  571. ErrorDesc = Mod:format_error(Desc),
  572. io_lib:format("~s:~w: ~s~s~n", [AbsSource, Line, Extra, ErrorDesc]);
  573. format_error(AbsSource, Extra, {Mod, Desc}) ->
  574. ErrorDesc = Mod:format_error(Desc),
  575. io_lib:format("~s: ~s~s~n", [AbsSource, Extra, ErrorDesc]).
  576. additional_defines() ->
  577. [{d, D} || {Re, D} <- [{"^[0-9]+", namespaced_types},
  578. {"^R1[4|5]", deprecated_crypto},
  579. {"^2", unicode_str},
  580. {"^(R|1|20)", fun_stacktrace},
  581. {"^((1[8|9])|2)", rand_module}],
  582. is_otp_release(Re)].
  583. is_otp_release(ArchRegex) ->
  584. case re:run(otp_release(), ArchRegex, [{capture, none}]) of
  585. match ->
  586. true;
  587. nomatch ->
  588. false
  589. end.
  590. otp_release() ->
  591. otp_release1(erlang:system_info(otp_release)).
  592. %% If OTP <= R16, otp_release is already what we want.
  593. otp_release1([$R,N|_]=Rel) when is_integer(N) ->
  594. Rel;
  595. %% If OTP >= 17.x, erlang:system_info(otp_release) returns just the
  596. %% major version number, we have to read the full version from
  597. %% a file. See http://www.erlang.org/doc/system_principles/versions.html
  598. %% Read vsn string from the 'OTP_VERSION' file and return as list without
  599. %% the "\n".
  600. otp_release1(Rel) ->
  601. File = filename:join([code:root_dir(), "releases", Rel, "OTP_VERSION"]),
  602. case file:read_file(File) of
  603. {error, _} ->
  604. Rel;
  605. {ok, Vsn} ->
  606. %% It's fine to rely on the binary module here because we can
  607. %% be sure that it's available when the otp_release string does
  608. %% not begin with $R.
  609. Size = byte_size(Vsn),
  610. %% The shortest vsn string consists of at least two digits
  611. %% followed by "\n". Therefore, it's safe to assume Size >= 3.
  612. case binary:part(Vsn, {Size, -3}) of
  613. <<"**\n">> ->
  614. %% The OTP documentation mentions that a system patched
  615. %% using the otp_patch_apply tool available to licensed
  616. %% customers will leave a '**' suffix in the version as a
  617. %% flag saying the system consists of application versions
  618. %% from multiple OTP versions. We ignore this flag and
  619. %% drop the suffix, given for all intents and purposes, we
  620. %% cannot obtain relevant information from it as far as
  621. %% tooling is concerned.
  622. binary:bin_to_list(Vsn, {0, Size - 3});
  623. _ ->
  624. binary:bin_to_list(Vsn, {0, Size - 1})
  625. end
  626. end.
  627. set_proxy_auth([]) ->
  628. ok;
  629. set_proxy_auth(UserInfo) ->
  630. [Username, Password] = re:split(UserInfo, ":",
  631. [{return, list}, {parts,2}, unicode]),
  632. %% password may contain url encoded characters, need to decode them first
  633. put(proxy_auth, [{proxy_auth, {Username, http_uri:decode(Password)}}]).
  634. get_proxy_auth() ->
  635. case get(proxy_auth) of
  636. undefined -> [];
  637. ProxyAuth -> ProxyAuth
  638. end.
  639. %% string:join/2 copy; string:join/2 is getting obsoleted
  640. %% and replaced by lists:join/2, but lists:join/2 is too new
  641. %% for version support (only appeared in 19.0) so it cannot be
  642. %% used. Instead we just adopt join/2 locally and hope it works
  643. %% for most unicode use cases anyway.
  644. join([], Sep) when is_list(Sep) ->
  645. [];
  646. join([H|T], Sep) ->
  647. H ++ lists:append([Sep ++ X || X <- T]).
  648. %% Same for chr; no non-deprecated equivalent in OTP20+
  649. chr(S, C) when is_integer(C) -> chr(S, C, 1).
  650. chr([C|_Cs], C, I) -> I;
  651. chr([_|Cs], C, I) -> chr(Cs, C, I+1);
  652. chr([], _C, _I) -> 0.