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.

650 regels
24 KiB

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