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.

737 regels
27 KiB

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