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.

738 lines
27 KiB

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