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.

754 lines
28 KiB

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