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.

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