您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

749 行
27 KiB

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