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.

643 line
24 KiB

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