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.

746 lines
27 KiB

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