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.

656 rivejä
24 KiB

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