Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

710 řádky
26 KiB

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