!1 Add package erlang-rebar

From: @wang--ge
Reviewed-by: 
Signed-off-by:
This commit is contained in:
openeuler-ci-bot 2020-09-18 18:33:10 +08:00 committed by Gitee
commit 22a606e73e
16 changed files with 2180 additions and 0 deletions

96
erlang-rebar.spec Normal file
View File

@ -0,0 +1,96 @@
%global realname rebar
%global upstream rebar
%global need_bootstrap_set 0
%{!?need_bootstrap: %global need_bootstrap %{need_bootstrap_set}}
Name: erlang-%{realname}
Version: 2.6.4
Release: 1
BuildArch: noarch
Summary: Erlang Build Tools
License: MIT
URL: https://github.com/%{upstream}/%{realname}
Source0: https://github.com/%{upstream}/%{realname}/archive/%{version}/%{realname}-%{version}.tar.gz
Patch1: rebar-0001-Load-templates-from-the-filesystem-first.patch
Patch2: rebar-0002-Remove-bundled-mustache.patch
Patch3: rebar-0003-Remove-bundled-getopt.patch
Patch4: rebar-0004-Allow-discarding-building-ports.patch
Patch5: rebar-0005-Remove-any-traces-of-long-time-obsolete-escript-fold.patch
Patch6: rebar-0006-remove-abnfc.patch
Patch7: rebar-0007-Remove-support-for-gpb-compiler.patch
Patch8: rebar-0008-Remove-pre-R15B02-workaround.patch
Patch9: rebar-0009-Use-erlang-timestamp-0-explicitly.patch
Patch10: rebar-0010-Try-shell-variable-VSN-first.patch
Patch11: rebar-0011-Allow-ignoring-missing-deps.patch
Patch12: rebar-0012-Drop-obsolete-crypto-rand_uniform-2.patch
Patch13: rebar-0013-Remove-compat-random-modules.patch
%if 0%{?need_bootstrap} < 1
BuildRequires: erlang-rebar erlang-getopt
%else
BuildRequires: erlang-asn1 erlang-common_test erlang-compiler erlang-crypto
BuildRequires: erlang-dialyzer erlang-diameter erlang-edoc erlang-eflame
BuildRequires: erlang-erl_interface erlang-erlydtl erlang-erts erlang-eunit erlang-getopt
BuildRequires: erlang-kernel erlang-lfe erlang-mustache erlang-neotoma erlang-parsetools
BuildRequires: erlang-protobuffs erlang-reltool erlang-rpm-macros erlang-sasl erlang-snmp
BuildRequires: erlang-stdlib erlang-syntax_tools erlang-tools erlang-triq
%endif
Requires: erlang-common_test erlang-erl_interface erlang-parsetools
Requires: erlang-rpm-macros >= 0.2.4
Provides: %{realname} = %{version}-%{release}
%description
Erlang Build Tools.
%prep
%setup -q -n %{realname}-%{version}
touch ./rebar.escript
cat <<EOT >>./rebar.escript
#!/usr/bin/env escript
%%%%! -noshell -noinput
main (Args) ->
rebar:main(Args).
EOT
%patch1 -p1 -b .load_templates_from_fs
%patch2 -p1 -b .remove_bundled_mustache
%if 0%{?need_bootstrap} < 1
%patch3 -p1 -b .remove_bundled_getopt
%endif
%patch4 -p1 -b .allow_discarding_ports
%patch5 -p1 -b .remove_escript_foldl_3
%patch6 -p1 -b .remove_abnfc
%patch7 -p1 -b .remove_gpb
%patch8 -p1 -b .remove_pre_R15B02
%patch9 -p1 -b .erlang_timestamp_0
%patch10 -p1 -b .vsn_override
%patch11 -p1 -b .skip_deps_checking
%patch12 -p1 -b .erl20
%patch13 -p1 -b .erl22_compat
%build
%if 0%{?need_bootstrap} < 1
%{erlang_compile}
%else
./bootstrap
./rebar compile -v
%endif
%install
%{erlang_install}
install -D -p -m 0755 %{_builddir}/%{realname}-%{version}/rebar.escript %{buildroot}%{_bindir}/rebar
cp -a priv %{buildroot}%{_erllibdir}/%{realname}-%{version}/
%check
%if 0%{?need_bootstrap} < 1
install -D -p -m 0755 %{_builddir}/%{realname}-%{version}/rebar.escript ./rebar
sed -i -e "s,-noshell -noinput,-noshell -noinput -pa .,g" ./rebar
%{rebar_eunit}
%endif
%files
%doc README.md THANKS rebar.config.sample
%license LICENSE
%{_bindir}/rebar
%{erlang_appdir}/
%changelog
* Fri Sep 4 2020 Ge Wang <wangge20@huawei.com> - 2.6.4-1
- Package init

4
erlang-rebar.yaml Normal file
View File

@ -0,0 +1,4 @@
version_contrl: github
src_repo: rebar/rebar
tag_prefix: NA
seperator: "."

View File

@ -0,0 +1,25 @@
From: Peter Lemenkov <lemenkov@gmail.com>
Date: Mon, 4 Mar 2013 19:03:03 +0400
Subject: [PATCH] Load templates from the filesystem first.
Signed-off-by: Peter Lemenkov <lemenkov@gmail.com>
diff --git a/src/rebar_templater.erl b/src/rebar_templater.erl
index 085ac1c..7e8554e 100644
--- a/src/rebar_templater.erl
+++ b/src/rebar_templater.erl
@@ -241,12 +241,13 @@ find_escript_templates(Files) ->
re:run(Name, ?TEMPLATE_RE, [{capture, none}]) == match].
find_disk_templates(Config) ->
+ BaseTemplates = rebar_utils:find_files(code:priv_dir(rebar) ++ "/templates", ?TEMPLATE_RE),
OtherTemplates = find_other_templates(Config),
HomeTemplates = filename:join([os:getenv("HOME"), ".rebar", "templates"]),
HomeFiles = rebar_utils:find_files_by_ext(HomeTemplates, ".template"),
Recursive = rebar_config:is_recursive(Config),
LocalFiles = rebar_utils:find_files_by_ext(".", ".template", Recursive),
- [{file, F} || F <- OtherTemplates ++ HomeFiles ++ LocalFiles].
+ [{file, F} || F <- BaseTemplates ++ OtherTemplates ++ HomeFiles ++ LocalFiles].
find_other_templates(Config) ->
case rebar_config:get_global(Config, template_dir, undefined) of

View File

@ -0,0 +1,267 @@
From: Filip Andres <filip@andresovi.net>
Date: Fri, 3 Jul 2015 10:46:48 +0200
Subject: [PATCH] Remove bundled mustache
diff --git a/ebin/rebar.app b/ebin/rebar.app
index 9449e1e..d3f8e42 100644
--- a/ebin/rebar.app
+++ b/ebin/rebar.app
@@ -45,7 +45,6 @@
rebar_xref,
rebar_metacmds,
rebar_getopt,
- rebar_mustache,
rmemo,
rebar_rand_compat ]},
{registered, []},
diff --git a/src/rebar_mustache.erl b/src/rebar_mustache.erl
deleted file mode 100644
index 9016c0f..0000000
--- a/src/rebar_mustache.erl
+++ /dev/null
@@ -1,230 +0,0 @@
-%% The MIT License
-%%
-%% Copyright (c) 2009 Tom Preston-Werner <tom@mojombo.com>
-%%
-%% Permission is hereby granted, free of charge, to any person obtaining a copy
-%% of this software and associated documentation files (the "Software"), to deal
-%% in the Software without restriction, including without limitation the rights
-%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-%% copies of the Software, and to permit persons to whom the Software is
-%% furnished to do so, subject to the following conditions:
-%%
-%% The above copyright notice and this permission notice shall be included in
-%% all copies or substantial portions of the Software.
-%%
-%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-%% THE SOFTWARE.
-
-%% See the README at http://github.com/mojombo/mustache.erl for additional
-%% documentation and usage examples.
-
--module(rebar_mustache). %% v0.1.0
--author("Tom Preston-Werner").
--export([compile/1, compile/2, render/1, render/2, render/3, get/2, get/3, escape/1, start/1]).
-
--record(mstate, {mod = undefined,
- section_re = undefined,
- tag_re = undefined}).
-
--define(MUSTACHE_STR, "rebar_mustache").
-
-compile(Body) when is_list(Body) ->
- State = #mstate{},
- CompiledTemplate = pre_compile(Body, State),
- % io:format("~p~n~n", [CompiledTemplate]),
- % io:format(CompiledTemplate ++ "~n", []),
- {ok, Tokens, _} = erl_scan:string(CompiledTemplate),
- {ok, [Form]} = erl_parse:parse_exprs(Tokens),
- Bindings = erl_eval:new_bindings(),
- {value, Fun, _} = erl_eval:expr(Form, Bindings),
- Fun;
-compile(Mod) ->
- TemplatePath = template_path(Mod),
- compile(Mod, TemplatePath).
-
-compile(Mod, File) ->
- code:purge(Mod),
- {module, _} = code:load_file(Mod),
- {ok, TemplateBin} = file:read_file(File),
- Template = re:replace(TemplateBin, "\"", "\\\\\"", [global, {return,list}]),
- State = #mstate{mod = Mod},
- CompiledTemplate = pre_compile(Template, State),
- % io:format("~p~n~n", [CompiledTemplate]),
- % io:format(CompiledTemplate ++ "~n", []),
- {ok, Tokens, _} = erl_scan:string(CompiledTemplate),
- {ok, [Form]} = erl_parse:parse_exprs(Tokens),
- Bindings = erl_eval:new_bindings(),
- {value, Fun, _} = erl_eval:expr(Form, Bindings),
- Fun.
-
-render(Mod) ->
- TemplatePath = template_path(Mod),
- render(Mod, TemplatePath).
-
-render(Body, Ctx) when is_list(Body) ->
- TFun = compile(Body),
- render(undefined, TFun, Ctx);
-render(Mod, File) when is_list(File) ->
- render(Mod, File, dict:new());
-render(Mod, CompiledTemplate) ->
- render(Mod, CompiledTemplate, dict:new()).
-
-render(Mod, File, Ctx) when is_list(File) ->
- CompiledTemplate = compile(Mod, File),
- render(Mod, CompiledTemplate, Ctx);
-render(Mod, CompiledTemplate, Ctx) ->
- Ctx2 = dict:store('__mod__', Mod, Ctx),
- lists:flatten(CompiledTemplate(Ctx2)).
-
-pre_compile(T, State) ->
- SectionRE = "\{\{\#([^\}]*)}}\s*(.+?){{\/\\1\}\}\s*",
- {ok, CompiledSectionRE} = re:compile(SectionRE, [dotall]),
- TagRE = "\{\{(#|=|!|<|>|\{)?(.+?)\\1?\}\}+",
- {ok, CompiledTagRE} = re:compile(TagRE, [dotall]),
- State2 = State#mstate{section_re = CompiledSectionRE, tag_re = CompiledTagRE},
- "fun(Ctx) -> " ++
- "CFun = fun(A, B) -> A end, " ++
- compiler(T, State2) ++ " end.".
-
-compiler(T, State) ->
- Res = re:run(T, State#mstate.section_re),
- case Res of
- {match, [{M0, M1}, {N0, N1}, {C0, C1}]} ->
- Front = string:substr(T, 1, M0),
- Back = string:substr(T, M0 + M1 + 1),
- Name = string:substr(T, N0 + 1, N1),
- Content = string:substr(T, C0 + 1, C1),
- "[" ++ compile_tags(Front, State) ++
- " | [" ++ compile_section(Name, Content, State) ++
- " | [" ++ compiler(Back, State) ++ "]]]";
- nomatch ->
- compile_tags(T, State)
- end.
-
-compile_section(Name, Content, State) ->
- Mod = State#mstate.mod,
- Result = compiler(Content, State),
- "fun() -> " ++
- "case " ++ ?MUSTACHE_STR ++ ":get(" ++ Name ++ ", Ctx, " ++ atom_to_list(Mod) ++ ") of " ++
- "\"true\" -> " ++
- Result ++ "; " ++
- "\"false\" -> " ++
- "[]; " ++
- "List when is_list(List) -> " ++
- "[fun(Ctx) -> " ++ Result ++ " end(dict:merge(CFun, SubCtx, Ctx)) || SubCtx <- List]; " ++
- "Else -> " ++
- "throw({template, io_lib:format(\"Bad context for ~p: ~p\", [" ++ Name ++ ", Else])}) " ++
- "end " ++
- "end()".
-
-compile_tags(T, State) ->
- Res = re:run(T, State#mstate.tag_re),
- case Res of
- {match, [{M0, M1}, K, {C0, C1}]} ->
- Front = string:substr(T, 1, M0),
- Back = string:substr(T, M0 + M1 + 1),
- Content = string:substr(T, C0 + 1, C1),
- Kind = tag_kind(T, K),
- Result = compile_tag(Kind, Content, State),
- "[\"" ++ Front ++
- "\" | [" ++ Result ++
- " | " ++ compile_tags(Back, State) ++ "]]";
- nomatch ->
- "[\"" ++ T ++ "\"]"
- end.
-
-tag_kind(_T, {-1, 0}) ->
- none;
-tag_kind(T, {K0, K1}) ->
- string:substr(T, K0 + 1, K1).
-
-compile_tag(none, Content, State) ->
- Mod = State#mstate.mod,
- ?MUSTACHE_STR ++ ":escape(" ++ ?MUSTACHE_STR ++ ":get(" ++ Content ++ ", Ctx, " ++ atom_to_list(Mod) ++ "))";
-compile_tag("{", Content, State) ->
- Mod = State#mstate.mod,
- ?MUSTACHE_STR ++ ":get(" ++ Content ++ ", Ctx, " ++ atom_to_list(Mod) ++ ")";
-compile_tag("!", _Content, _State) ->
- "[]".
-
-template_dir(Mod) ->
- DefaultDirPath = filename:dirname(code:which(Mod)),
- case application:get_env(mustache, templates_dir) of
- {ok, DirPath} when is_list(DirPath) ->
- case filelib:ensure_dir(DirPath) of
- ok -> DirPath;
- _ -> DefaultDirPath
- end;
- _ ->
- DefaultDirPath
- end.
-template_path(Mod) ->
- DirPath = template_dir(Mod),
- Basename = atom_to_list(Mod),
- filename:join(DirPath, Basename ++ ".mustache").
-
-get(Key, Ctx) when is_list(Key) ->
- {ok, Mod} = dict:find('__mod__', Ctx),
- get(list_to_atom(Key), Ctx, Mod);
-get(Key, Ctx) ->
- {ok, Mod} = dict:find('__mod__', Ctx),
- get(Key, Ctx, Mod).
-
-get(Key, Ctx, Mod) when is_list(Key) ->
- get(list_to_atom(Key), Ctx, Mod);
-get(Key, Ctx, Mod) ->
- case dict:find(Key, Ctx) of
- {ok, Val} ->
- % io:format("From Ctx {~p, ~p}~n", [Key, Val]),
- to_s(Val);
- error ->
- case erlang:function_exported(Mod, Key, 1) of
- true ->
- Val = to_s(Mod:Key(Ctx)),
- % io:format("From Mod/1 {~p, ~p}~n", [Key, Val]),
- Val;
- false ->
- case erlang:function_exported(Mod, Key, 0) of
- true ->
- Val = to_s(Mod:Key()),
- % io:format("From Mod/0 {~p, ~p}~n", [Key, Val]),
- Val;
- false ->
- []
- end
- end
- end.
-
-to_s(Val) when is_integer(Val) ->
- integer_to_list(Val);
-to_s(Val) when is_float(Val) ->
- io_lib:format("~.2f", [Val]);
-to_s(Val) when is_atom(Val) ->
- atom_to_list(Val);
-to_s(Val) ->
- Val.
-
-escape(HTML) ->
- escape(HTML, []).
-
-escape([], Acc) ->
- lists:reverse(Acc);
-escape(["<" | Rest], Acc) ->
- escape(Rest, lists:reverse("&lt;", Acc));
-escape([">" | Rest], Acc) ->
- escape(Rest, lists:reverse("&gt;", Acc));
-escape(["&" | Rest], Acc) ->
- escape(Rest, lists:reverse("&amp;", Acc));
-escape([X | Rest], Acc) ->
- escape(Rest, [X | Acc]).
-
-%%---------------------------------------------------------------------------
-
-start([T]) ->
- Out = render(list_to_atom(T)),
- io:format(Out ++ "~n", []).
diff --git a/src/rebar_templater.erl b/src/rebar_templater.erl
index 7e8554e..2d20e86 100644
--- a/src/rebar_templater.erl
+++ b/src/rebar_templater.erl
@@ -102,8 +102,7 @@ render(Bin, Context) ->
%% Be sure to escape any double-quotes before rendering...
ReOpts = [global, {return, list}],
Str0 = re:replace(Bin, "\\\\", "\\\\\\", ReOpts),
- Str1 = re:replace(Str0, "\"", "\\\\\"", ReOpts),
- rebar_mustache:render(Str1, Context).
+ mustache:render(Str0, Context).
%% ===================================================================
%% Internal functions

View File

@ -0,0 +1,959 @@
From: Filip Andres <filip@andresovi.net>
Date: Fri, 3 Jul 2015 10:56:26 +0200
Subject: [PATCH] Remove bundled getopt
diff --git a/ebin/rebar.app b/ebin/rebar.app
index d3f8e42..986f12f 100644
--- a/ebin/rebar.app
+++ b/ebin/rebar.app
@@ -44,7 +44,6 @@
rebar_utils,
rebar_xref,
rebar_metacmds,
- rebar_getopt,
rmemo,
rebar_rand_compat ]},
{registered, []},
diff --git a/src/rebar.erl b/src/rebar.erl
index 2eb608d..91593c2 100644
--- a/src/rebar.erl
+++ b/src/rebar.erl
@@ -236,7 +236,7 @@ run_aux(BaseConfig, Commands) ->
%%
help() ->
OptSpecList = option_spec_list(),
- rebar_getopt:usage(OptSpecList, "rebar",
+ getopt:usage(OptSpecList, "rebar",
"[var=value,...] <command,...>",
[{"var=value", "rebar global variables (e.g. force=1)"},
{"command", "Command to run (e.g. compile)"}]),
@@ -301,7 +301,7 @@ help() ->
parse_args(RawArgs) ->
%% Parse getopt options
OptSpecList = option_spec_list(),
- case rebar_getopt:parse(OptSpecList, RawArgs) of
+ case getopt:parse(OptSpecList, RawArgs) of
{ok, Args} ->
Args;
{error, {Reason, Data}} ->
diff --git a/src/rebar_getopt.erl b/src/rebar_getopt.erl
deleted file mode 100644
index 79b871d..0000000
--- a/src/rebar_getopt.erl
+++ /dev/null
@@ -1,914 +0,0 @@
-%%%-------------------------------------------------------------------
-%%% @author Juan Jose Comellas <juanjo@comellas.org>
-%%% @copyright (C) 2009 Juan Jose Comellas
-%%% @doc Parses command line options with a format similar to that of GNU getopt.
-%%% @end
-%%%
-%%% This source file is subject to the New BSD License. You should have received
-%%% a copy of the New BSD license with this software. If not, it can be
-%%% retrieved from: http://www.opensource.org/licenses/bsd-license.php
-%%%-------------------------------------------------------------------
--module(rebar_getopt).
--author('juanjo@comellas.org').
-
--export([parse/2, check/2, parse_and_check/2, format_error/2,
- usage/2, usage/3, usage/4, tokenize/1]).
--export([usage_cmd_line/2]).
-
--define(LINE_LENGTH, 75).
--define(MIN_USAGE_COMMAND_LINE_OPTION_LENGTH, 25).
-
-%% Position of each field in the option specification tuple.
--define(OPT_NAME, 1).
--define(OPT_SHORT, 2).
--define(OPT_LONG, 3).
--define(OPT_ARG, 4).
--define(OPT_HELP, 5).
-
--define(IS_OPT_SPEC(Opt), (tuple_size(Opt) =:= ?OPT_HELP)).
--define(IS_WHITESPACE(Char), ((Char) =:= $\s orelse (Char) =:= $\t orelse
- (Char) =:= $\n orelse (Char) =:= $\r)).
-
-%% Atom indicating the data type that an argument can be converted to.
--type arg_type() :: 'atom' | 'binary' | 'boolean' | 'float' | 'integer' | 'string'.
-%% Data type that an argument can be converted to.
--type arg_value() :: atom() | binary() | boolean() | float() | integer() | string().
-%% Argument specification.
--type arg_spec() :: arg_type() | {arg_type(), arg_value()} | undefined.
-%% Option type and optional default argument.
--type simple_option() :: atom().
--type compound_option() :: {atom(), arg_value()}.
--type option() :: simple_option() | compound_option().
-%% Command line option specification.
--type option_spec() :: {
- Name :: atom(),
- Short :: char() | undefined,
- Long :: string() | undefined,
- ArgSpec :: arg_spec(),
- Help :: string() | undefined
- }.
-%% Output streams
--type output_stream() :: 'standard_io' | 'standard_error'.
-
-%% For internal use
--type usage_line() :: {OptionText :: string(), HelpText :: string()}.
--type usage_line_with_length() :: {OptionLength :: non_neg_integer(), OptionText :: string(), HelpText :: string()}.
-
-
--export_type([arg_type/0, arg_value/0, arg_spec/0, simple_option/0, compound_option/0, option/0, option_spec/0]).
-
-
-%% @doc Parse the command line options and arguments returning a list of tuples
-%% and/or atoms using the Erlang convention for sending options to a
-%% function. Additionally perform check if all required options (the ones
-%% without default values) are present. The function is a combination of
-%% two calls: parse/2 and check/2.
--spec parse_and_check([option_spec()], string() | [string()]) ->
- {ok, {[option()], [string()]}} | {error, {Reason :: atom(), Data :: term()}}.
-parse_and_check(OptSpecList, CmdLine) when is_list(OptSpecList), is_list(CmdLine) ->
- case parse(OptSpecList, CmdLine) of
- {ok, {Opts, _}} = Result ->
- case check(OptSpecList, Opts) of
- ok -> Result;
- Error -> Error
- end;
- Error ->
- Error
- end.
-
-%% @doc Check the parsed command line arguments returning ok if all required
-%% options (i.e. that don't have defaults) are present, and returning
-%% error otherwise.
--spec check([option_spec()], [option()]) ->
- ok | {error, {Reason :: atom(), Option :: atom()}}.
-check(OptSpecList, ParsedOpts) when is_list(OptSpecList), is_list(ParsedOpts) ->
- try
- RequiredOpts = [Name || {Name, _, _, Arg, _} <- OptSpecList,
- not is_tuple(Arg) andalso Arg =/= undefined],
- lists:foreach(fun (Option) ->
- case proplists:is_defined(Option, ParsedOpts) of
- true ->
- ok;
- false ->
- throw({error, {missing_required_option, Option}})
- end
- end, RequiredOpts)
- catch
- _:Error ->
- Error
- end.
-
-
-%% @doc Parse the command line options and arguments returning a list of tuples
-%% and/or atoms using the Erlang convention for sending options to a
-%% function.
--spec parse([option_spec()], string() | [string()]) ->
- {ok, {[option()], [string()]}} | {error, {Reason :: atom(), Data :: term()}}.
-parse(OptSpecList, CmdLine) when is_list(CmdLine) ->
- try
- Args = if
- is_integer(hd(CmdLine)) -> tokenize(CmdLine);
- true -> CmdLine
- end,
- parse(OptSpecList, [], [], 0, Args)
- catch
- throw: {error, {_Reason, _Data}} = Error ->
- Error
- end.
-
-
--spec parse([option_spec()], [option()], [string()], integer(), [string()]) ->
- {ok, {[option()], [string()]}}.
-%% Process the option terminator.
-parse(OptSpecList, OptAcc, ArgAcc, _ArgPos, ["--" | Tail]) ->
- %% Any argument present after the terminator is not considered an option.
- {ok, {lists:reverse(append_default_options(OptSpecList, OptAcc)), lists:reverse(ArgAcc, Tail)}};
-%% Process long options.
-parse(OptSpecList, OptAcc, ArgAcc, ArgPos, ["--" ++ OptArg = OptStr | Tail]) ->
- parse_long_option(OptSpecList, OptAcc, ArgAcc, ArgPos, Tail, OptStr, OptArg);
-%% Process short options.
-parse(OptSpecList, OptAcc, ArgAcc, ArgPos, ["-" ++ ([_Char | _] = OptArg) = OptStr | Tail]) ->
- parse_short_option(OptSpecList, OptAcc, ArgAcc, ArgPos, Tail, OptStr, OptArg);
-%% Process non-option arguments.
-parse(OptSpecList, OptAcc, ArgAcc, ArgPos, [Arg | Tail]) ->
- case find_non_option_arg(OptSpecList, ArgPos) of
- {value, OptSpec} when ?IS_OPT_SPEC(OptSpec) ->
- parse(OptSpecList, add_option_with_arg(OptSpec, Arg, OptAcc), ArgAcc, ArgPos + 1, Tail);
- false ->
- parse(OptSpecList, OptAcc, [Arg | ArgAcc], ArgPos, Tail)
- end;
-parse(OptSpecList, OptAcc, ArgAcc, _ArgPos, []) ->
- %% Once we have completed gathering the options we add the ones that were
- %% not present but had default arguments in the specification.
- {ok, {lists:reverse(append_default_options(OptSpecList, OptAcc)), lists:reverse(ArgAcc)}}.
-
-
-%% @doc Format the error code returned by prior call to parse/2 or check/2.
--spec format_error([option_spec()], {error, {Reason :: atom(), Data :: term()}} |
- {Reason :: term(), Data :: term()}) -> string().
-format_error(OptSpecList, {error, Reason}) ->
- format_error(OptSpecList, Reason);
-format_error(OptSpecList, {missing_required_option, Name}) ->
- {_Name, Short, Long, _Type, _Help} = lists:keyfind(Name, 1, OptSpecList),
- lists:flatten(["missing required option: -", [Short], " (", to_string(Long), ")"]);
-format_error(_OptSpecList, {invalid_option, OptStr}) ->
- lists:flatten(["invalid option: ", to_string(OptStr)]);
-format_error(_OptSpecList, {invalid_option_arg, {Name, Arg}}) ->
- lists:flatten(["option \'", to_string(Name) ++ "\' has invalid argument: ", to_string(Arg)]);
-format_error(_OptSpecList, {invalid_option_arg, OptStr}) ->
- lists:flatten(["invalid option argument: ", to_string(OptStr)]);
-format_error(_OptSpecList, {Reason, Data}) ->
- lists:flatten([to_string(Reason), " ", to_string(Data)]).
-
-
-%% @doc Parse a long option, add it to the option accumulator and continue
-%% parsing the rest of the arguments recursively.
-%% A long option can have the following syntax:
-%% --foo Single option 'foo', no argument
-%% --foo=bar Single option 'foo', argument "bar"
-%% --foo bar Single option 'foo', argument "bar"
--spec parse_long_option([option_spec()], [option()], [string()], integer(), [string()], string(), string()) ->
- {ok, {[option()], [string()]}}.
-parse_long_option(OptSpecList, OptAcc, ArgAcc, ArgPos, Args, OptStr, OptArg) ->
- case split_assigned_arg(OptArg) of
- {Long, Arg} ->
- %% Get option that has its argument within the same string
- %% separated by an equal ('=') character (e.g. "--port=1000").
- parse_long_option_assigned_arg(OptSpecList, OptAcc, ArgAcc, ArgPos, Args, OptStr, Long, Arg);
-
- Long ->
- case lists:keyfind(Long, ?OPT_LONG, OptSpecList) of
- {Name, _Short, Long, undefined, _Help} ->
- parse(OptSpecList, [Name | OptAcc], ArgAcc, ArgPos, Args);
-
- {_Name, _Short, Long, _ArgSpec, _Help} = OptSpec ->
- %% The option argument string is empty, but the option requires
- %% an argument, so we look into the next string in the list.
- %% e.g ["--port", "1000"]
- parse_long_option_next_arg(OptSpecList, OptAcc, ArgAcc, ArgPos, Args, OptSpec);
- false ->
- throw({error, {invalid_option, OptStr}})
- end
- end.
-
-
-%% @doc Parse an option where the argument is 'assigned' in the same string using
-%% the '=' character, add it to the option accumulator and continue parsing the
-%% rest of the arguments recursively. This syntax is only valid for long options.
--spec parse_long_option_assigned_arg([option_spec()], [option()], [string()], integer(),
- [string()], string(), string(), string()) ->
- {ok, {[option()], [string()]}}.
-parse_long_option_assigned_arg(OptSpecList, OptAcc, ArgAcc, ArgPos, Args, OptStr, Long, Arg) ->
- case lists:keyfind(Long, ?OPT_LONG, OptSpecList) of
- {_Name, _Short, Long, ArgSpec, _Help} = OptSpec ->
- case ArgSpec of
- undefined ->
- throw({error, {invalid_option_arg, OptStr}});
- _ ->
- parse(OptSpecList, add_option_with_assigned_arg(OptSpec, Arg, OptAcc), ArgAcc, ArgPos, Args)
- end;
- false ->
- throw({error, {invalid_option, OptStr}})
- end.
-
-
-%% @doc Split an option string that may contain an option with its argument
-%% separated by an equal ('=') character (e.g. "port=1000").
--spec split_assigned_arg(string()) -> {Name :: string(), Arg :: string()} | string().
-split_assigned_arg(OptStr) ->
- split_assigned_arg(OptStr, OptStr, []).
-
-split_assigned_arg(_OptStr, "=" ++ Tail, Acc) ->
- {lists:reverse(Acc), Tail};
-split_assigned_arg(OptStr, [Char | Tail], Acc) ->
- split_assigned_arg(OptStr, Tail, [Char | Acc]);
-split_assigned_arg(OptStr, [], _Acc) ->
- OptStr.
-
-
-%% @doc Retrieve the argument for an option from the next string in the list of
-%% command-line parameters or set the value of the argument from the argument
-%% specification (for boolean and integer arguments), if possible.
-parse_long_option_next_arg(OptSpecList, OptAcc, ArgAcc, ArgPos, Args, {Name, _Short, _Long, ArgSpec, _Help} = OptSpec) ->
- ArgSpecType = arg_spec_type(ArgSpec),
- case Args =:= [] orelse is_implicit_arg(ArgSpecType, hd(Args)) of
- true ->
- parse(OptSpecList, add_option_with_implicit_arg(OptSpec, OptAcc), ArgAcc, ArgPos, Args);
- false ->
- [Arg | Tail] = Args,
- try
- parse(OptSpecList, [{Name, to_type(ArgSpecType, Arg)} | OptAcc], ArgAcc, ArgPos, Tail)
- catch
- error:_ ->
- throw({error, {invalid_option_arg, {Name, Arg}}})
- end
- end.
-
-
-%% @doc Parse a short option, add it to the option accumulator and continue
-%% parsing the rest of the arguments recursively.
-%% A short option can have the following syntax:
-%% -a Single option 'a', no argument or implicit boolean argument
-%% -a foo Single option 'a', argument "foo"
-%% -afoo Single option 'a', argument "foo"
-%% -abc Multiple options: 'a'; 'b'; 'c'
-%% -bcafoo Multiple options: 'b'; 'c'; 'a' with argument "foo"
-%% -aaa Multiple repetitions of option 'a' (only valid for options with integer arguments)
--spec parse_short_option([option_spec()], [option()], [string()], integer(), [string()], string(), string()) ->
- {ok, {[option()], [string()]}}.
-parse_short_option(OptSpecList, OptAcc, ArgAcc, ArgPos, Args, OptStr, OptArg) ->
- parse_short_option(OptSpecList, OptAcc, ArgAcc, ArgPos, Args, OptStr, first, OptArg).
-
-parse_short_option(OptSpecList, OptAcc, ArgAcc, ArgPos, Args, OptStr, OptPos, [Short | Arg]) ->
- case lists:keyfind(Short, ?OPT_SHORT, OptSpecList) of
- {Name, Short, _Long, undefined, _Help} ->
- parse_short_option(OptSpecList, [Name | OptAcc], ArgAcc, ArgPos, Args, OptStr, first, Arg);
-
- {_Name, Short, _Long, ArgSpec, _Help} = OptSpec ->
- %% The option has a specification, so it requires an argument.
- case Arg of
- [] ->
- %% The option argument string is empty, but the option requires
- %% an argument, so we look into the next string in the list.
- parse_short_option_next_arg(OptSpecList, OptAcc, ArgAcc, ArgPos, Args, OptSpec, OptPos);
-
- _ ->
- case is_valid_arg(ArgSpec, Arg) of
- true ->
- parse(OptSpecList, add_option_with_arg(OptSpec, Arg, OptAcc), ArgAcc, ArgPos, Args);
- _ ->
- NewOptAcc = case OptPos of
- first -> add_option_with_implicit_arg(OptSpec, OptAcc);
- _ -> add_option_with_implicit_incrementable_arg(OptSpec, OptAcc)
- end,
- parse_short_option(OptSpecList, NewOptAcc, ArgAcc, ArgPos, Args, OptStr, next, Arg)
- end
- end;
-
- false ->
- throw({error, {invalid_option, OptStr}})
- end;
-parse_short_option(OptSpecList, OptAcc, ArgAcc, ArgPos, Args, _OptStr, _OptPos, []) ->
- parse(OptSpecList, OptAcc, ArgAcc, ArgPos, Args).
-
-
-%% @doc Retrieve the argument for an option from the next string in the list of
-%% command-line parameters or set the value of the argument from the argument
-%% specification (for boolean and integer arguments), if possible.
-parse_short_option_next_arg(OptSpecList, OptAcc, ArgAcc, ArgPos, Args, {Name, _Short, _Long, ArgSpec, _Help} = OptSpec, OptPos) ->
- case Args =:= [] orelse is_implicit_arg(ArgSpec, hd(Args)) of
- true when OptPos =:= first ->
- parse(OptSpecList, add_option_with_implicit_arg(OptSpec, OptAcc), ArgAcc, ArgPos, Args);
- true ->
- parse(OptSpecList, add_option_with_implicit_incrementable_arg(OptSpec, OptAcc), ArgAcc, ArgPos, Args);
- false ->
- [Arg | Tail] = Args,
- try
- parse(OptSpecList, [{Name, to_type(ArgSpec, Arg)} | OptAcc], ArgAcc, ArgPos, Tail)
- catch
- error:_ ->
- throw({error, {invalid_option_arg, {Name, Arg}}})
- end
- end.
-
-
-%% @doc Find the option for the discrete argument in position specified in the
-%% Pos argument.
--spec find_non_option_arg([option_spec()], integer()) -> {value, option_spec()} | false.
-find_non_option_arg([{_Name, undefined, undefined, _ArgSpec, _Help} = OptSpec | _Tail], 0) ->
- {value, OptSpec};
-find_non_option_arg([{_Name, undefined, undefined, _ArgSpec, _Help} | Tail], Pos) ->
- find_non_option_arg(Tail, Pos - 1);
-find_non_option_arg([_Head | Tail], Pos) ->
- find_non_option_arg(Tail, Pos);
-find_non_option_arg([], _Pos) ->
- false.
-
-
-%% @doc Append options that were not present in the command line arguments with
-%% their default arguments.
--spec append_default_options([option_spec()], [option()]) -> [option()].
-append_default_options([{Name, _Short, _Long, {_Type, DefaultArg}, _Help} | Tail], OptAcc) ->
- append_default_options(Tail,
- case lists:keymember(Name, 1, OptAcc) of
- false ->
- [{Name, DefaultArg} | OptAcc];
- _ ->
- OptAcc
- end);
-%% For options with no default argument.
-append_default_options([_Head | Tail], OptAcc) ->
- append_default_options(Tail, OptAcc);
-append_default_options([], OptAcc) ->
- OptAcc.
-
-
-%% @doc Add an option with argument converting it to the data type indicated by the
-%% argument specification.
--spec add_option_with_arg(option_spec(), string(), [option()]) -> [option()].
-add_option_with_arg({Name, _Short, _Long, ArgSpec, _Help} = OptSpec, Arg, OptAcc) ->
- case is_valid_arg(ArgSpec, Arg) of
- true ->
- try
- [{Name, to_type(ArgSpec, Arg)} | OptAcc]
- catch
- error:_ ->
- throw({error, {invalid_option_arg, {Name, Arg}}})
- end;
- false ->
- add_option_with_implicit_arg(OptSpec, OptAcc)
- end.
-
-
-%% @doc Add an option with argument that was part of an assignment expression
-%% (e.g. "--verbose=3") converting it to the data type indicated by the
-%% argument specification.
--spec add_option_with_assigned_arg(option_spec(), string(), [option()]) -> [option()].
-add_option_with_assigned_arg({Name, _Short, _Long, ArgSpec, _Help}, Arg, OptAcc) ->
- try
- [{Name, to_type(ArgSpec, Arg)} | OptAcc]
- catch
- error:_ ->
- throw({error, {invalid_option_arg, {Name, Arg}}})
- end.
-
-
-%% @doc Add an option that required an argument but did not have one. Some data
-%% types (boolean, integer) allow implicit or assumed arguments.
--spec add_option_with_implicit_arg(option_spec(), [option()]) -> [option()].
-add_option_with_implicit_arg({Name, _Short, _Long, ArgSpec, _Help}, OptAcc) ->
- case arg_spec_type(ArgSpec) of
- boolean ->
- %% Special case for boolean arguments: if there is no argument we
- %% set the value to 'true'.
- [{Name, true} | OptAcc];
- integer ->
- %% Special case for integer arguments: if the option had not been set
- %% before we set the value to 1. This is needed to support options like
- %% "-v" to return something like {verbose, 1}.
- [{Name, 1} | OptAcc];
- _ ->
- throw({error, {missing_option_arg, Name}})
- end.
-
-
-%% @doc Add an option with an implicit or assumed argument.
--spec add_option_with_implicit_incrementable_arg(option_spec() | arg_spec(), [option()]) -> [option()].
-add_option_with_implicit_incrementable_arg({Name, _Short, _Long, ArgSpec, _Help}, OptAcc) ->
- case arg_spec_type(ArgSpec) of
- boolean ->
- %% Special case for boolean arguments: if there is no argument we
- %% set the value to 'true'.
- [{Name, true} | OptAcc];
- integer ->
- %% Special case for integer arguments: if the option had not been set
- %% before we set the value to 1; if not we increment the previous value
- %% the option had. This is needed to support options like "-vvv" to
- %% return something like {verbose, 3}.
- case OptAcc of
- [{Name, Count} | Tail] ->
- [{Name, Count + 1} | Tail];
- _ ->
- [{Name, 1} | OptAcc]
- end;
- _ ->
- throw({error, {missing_option_arg, Name}})
- end.
-
-
-%% @doc Retrieve the data type form an argument specification.
--spec arg_spec_type(arg_spec()) -> arg_type() | undefined.
-arg_spec_type({Type, _DefaultArg}) ->
- Type;
-arg_spec_type(Type) when is_atom(Type) ->
- Type.
-
-
-%% @doc Convert an argument string to its corresponding data type.
--spec to_type(arg_spec() | arg_type(), string()) -> arg_value().
-to_type({Type, _DefaultArg}, Arg) ->
- to_type(Type, Arg);
-to_type(binary, Arg) ->
- list_to_binary(Arg);
-to_type(atom, Arg) ->
- list_to_atom(Arg);
-to_type(integer, Arg) ->
- list_to_integer(Arg);
-to_type(float, Arg) ->
- list_to_float(Arg);
-to_type(boolean, Arg) ->
- LowerArg = string:to_lower(Arg),
- case is_arg_true(LowerArg) of
- true ->
- true;
- _ ->
- case is_arg_false(LowerArg) of
- true ->
- false;
- false ->
- erlang:error(badarg)
- end
- end;
-to_type(_Type, Arg) ->
- Arg.
-
-
--spec is_arg_true(string()) -> boolean().
-is_arg_true(Arg) ->
- (Arg =:= "true") orelse (Arg =:= "t") orelse
- (Arg =:= "yes") orelse (Arg =:= "y") orelse
- (Arg =:= "on") orelse (Arg =:= "enabled") orelse
- (Arg =:= "1").
-
-
--spec is_arg_false(string()) -> boolean().
-is_arg_false(Arg) ->
- (Arg =:= "false") orelse (Arg =:= "f") orelse
- (Arg =:= "no") orelse (Arg =:= "n") orelse
- (Arg =:= "off") orelse (Arg =:= "disabled") orelse
- (Arg =:= "0").
-
-
--spec is_valid_arg(arg_spec(), nonempty_string()) -> boolean().
-is_valid_arg({Type, _DefaultArg}, Arg) ->
- is_valid_arg(Type, Arg);
-is_valid_arg(boolean, Arg) ->
- is_boolean_arg(Arg);
-is_valid_arg(integer, Arg) ->
- is_non_neg_integer_arg(Arg);
-is_valid_arg(float, Arg) ->
- is_non_neg_float_arg(Arg);
-is_valid_arg(_Type, _Arg) ->
- true.
-
-
--spec is_implicit_arg(arg_spec(), nonempty_string()) -> boolean().
-is_implicit_arg({Type, _DefaultArg}, Arg) ->
- is_implicit_arg(Type, Arg);
-is_implicit_arg(boolean, Arg) ->
- not is_boolean_arg(Arg);
-is_implicit_arg(integer, Arg) ->
- not is_integer_arg(Arg);
-is_implicit_arg(_Type, _Arg) ->
- false.
-
-
--spec is_boolean_arg(string()) -> boolean().
-is_boolean_arg(Arg) ->
- LowerArg = string:to_lower(Arg),
- is_arg_true(LowerArg) orelse is_arg_false(LowerArg).
-
-
--spec is_integer_arg(string()) -> boolean().
-is_integer_arg("-" ++ Tail) ->
- is_non_neg_integer_arg(Tail);
-is_integer_arg(Arg) ->
- is_non_neg_integer_arg(Arg).
-
-
--spec is_non_neg_integer_arg(string()) -> boolean().
-is_non_neg_integer_arg([Head | Tail]) when Head >= $0, Head =< $9 ->
- is_non_neg_integer_arg(Tail);
-is_non_neg_integer_arg([_Head | _Tail]) ->
- false;
-is_non_neg_integer_arg([]) ->
- true.
-
-
--spec is_non_neg_float_arg(string()) -> boolean().
-is_non_neg_float_arg([Head | Tail]) when (Head >= $0 andalso Head =< $9) orelse Head =:= $. ->
- is_non_neg_float_arg(Tail);
-is_non_neg_float_arg([_Head | _Tail]) ->
- false;
-is_non_neg_float_arg([]) ->
- true.
-
-
-%% @doc Show a message on standard_error indicating the command line options and
-%% arguments that are supported by the program.
--spec usage([option_spec()], string()) -> ok.
-usage(OptSpecList, ProgramName) ->
- usage(OptSpecList, ProgramName, standard_error).
-
-
-%% @doc Show a message on standard_error or standard_io indicating the command line options and
-%% arguments that are supported by the program.
--spec usage([option_spec()], string(), output_stream() | string()) -> ok.
-usage(OptSpecList, ProgramName, OutputStream) when is_atom(OutputStream) ->
- io:format(OutputStream, "~s~n~n~s~n",
- [usage_cmd_line(ProgramName, OptSpecList), usage_options(OptSpecList)]);
-%% @doc Show a message on standard_error indicating the command line options and
-%% arguments that are supported by the program. The CmdLineTail argument
-%% is a string that is added to the end of the usage command line.
-usage(OptSpecList, ProgramName, CmdLineTail) ->
- usage(OptSpecList, ProgramName, CmdLineTail, standard_error).
-
-
-%% @doc Show a message on standard_error or standard_io indicating the command line options and
-%% arguments that are supported by the program. The CmdLineTail argument
-%% is a string that is added to the end of the usage command line.
--spec usage([option_spec()], ProgramName :: string(), CmdLineTail :: string(), output_stream() | [{string(), string()}]) -> ok.
-usage(OptSpecList, ProgramName, CmdLineTail, OutputStream) when is_atom(OutputStream) ->
- io:format(OutputStream, "~s~n~n~s~n",
- [usage_cmd_line(ProgramName, OptSpecList, CmdLineTail), usage_options(OptSpecList)]);
-%% @doc Show a message on standard_error indicating the command line options and
-%% arguments that are supported by the program. The CmdLineTail and OptionsTail
-%% arguments are a string that is added to the end of the usage command line
-%% and a list of tuples that are added to the end of the options' help lines.
-usage(OptSpecList, ProgramName, CmdLineTail, OptionsTail) ->
- usage(OptSpecList, ProgramName, CmdLineTail, OptionsTail, standard_error).
-
-
-%% @doc Show a message on standard_error or standard_io indicating the command line options and
-%% arguments that are supported by the program. The CmdLineTail and OptionsTail
-%% arguments are a string that is added to the end of the usage command line
-%% and a list of tuples that are added to the end of the options' help lines.
--spec usage([option_spec()], ProgramName :: string(), CmdLineTail :: string(),
- [{OptionName :: string(), Help :: string()}], output_stream()) -> ok.
-usage(OptSpecList, ProgramName, CmdLineTail, OptionsTail, OutputStream) ->
- io:format(OutputStream, "~s~n~n~s~n",
- [usage_cmd_line(ProgramName, OptSpecList, CmdLineTail), usage_options(OptSpecList, OptionsTail)]).
-
-
--spec usage_cmd_line(ProgramName :: string(), [option_spec()]) -> iolist().
-usage_cmd_line(ProgramName, OptSpecList) ->
- usage_cmd_line(ProgramName, OptSpecList, "").
-
--spec usage_cmd_line(ProgramName :: string(), [option_spec()], CmdLineTail :: string()) -> iolist().
-usage_cmd_line(ProgramName, OptSpecList, CmdLineTail) ->
- Prefix = "Usage: " ++ ProgramName,
- PrefixLength = length(Prefix),
- LineLength = line_length(),
- %% Only align the command line options after the program name when there is
- %% enough room to do so (i.e. at least 25 characters). If not, show the
- %% command line options below the program name with a 2-character indentation.
- if
- (LineLength - PrefixLength) > ?MIN_USAGE_COMMAND_LINE_OPTION_LENGTH ->
- Indentation = lists:duplicate(PrefixLength, $\s),
- [FirstOptLine | OptLines] = usage_cmd_line_options(LineLength - PrefixLength, OptSpecList, CmdLineTail),
- IndentedOptLines = [[Indentation | OptLine] || OptLine <- OptLines],
- [Prefix, FirstOptLine | IndentedOptLines];
- true ->
- IndentedOptLines = [[" " | OptLine] || OptLine <- usage_cmd_line_options(LineLength, OptSpecList, CmdLineTail)],
- [Prefix, $\n, IndentedOptLines]
- end.
-
-
-%% @doc Return a list of the lines corresponding to the usage command line
-%% already wrapped according to the maximum MaxLineLength.
--spec usage_cmd_line_options(MaxLineLength :: non_neg_integer(), [option_spec()], CmdLineTail :: string()) -> iolist().
-usage_cmd_line_options(MaxLineLength, OptSpecList, CmdLineTail) ->
- usage_cmd_line_options(MaxLineLength, OptSpecList ++ string:tokens(CmdLineTail, " "), [], 0, []).
-
-usage_cmd_line_options(MaxLineLength, [OptSpec | Tail], LineAcc, LineAccLength, Acc) ->
- Option = [$\s | lists:flatten(usage_cmd_line_option(OptSpec))],
- OptionLength = length(Option),
- %% We accumulate the options in LineAcc until its length is over the
- %% maximum allowed line length. When that happens, we append the line in
- %% LineAcc to the list with all the lines in the command line (Acc).
- NewLineAccLength = LineAccLength + OptionLength,
- if
- NewLineAccLength < MaxLineLength ->
- usage_cmd_line_options(MaxLineLength, Tail, [Option | LineAcc], NewLineAccLength, Acc);
- true ->
- usage_cmd_line_options(MaxLineLength, Tail, [Option], OptionLength + 1,
- [lists:reverse([$\n | LineAcc]) | Acc])
- end;
-usage_cmd_line_options(MaxLineLength, [], [_ | _] = LineAcc, _LineAccLength, Acc) ->
- %% If there was a non-empty line in LineAcc when there are no more options
- %% to process, we add it to the list of lines to return.
- usage_cmd_line_options(MaxLineLength, [], [], 0, [lists:reverse(LineAcc) | Acc]);
-usage_cmd_line_options(_MaxLineLength, [], [], _LineAccLength, Acc) ->
- lists:reverse(Acc).
-
-
--spec usage_cmd_line_option(option_spec()) -> string().
-usage_cmd_line_option({_Name, Short, _Long, undefined, _Help}) when Short =/= undefined ->
- %% For options with short form and no argument.
- [$[, $-, Short, $]];
-usage_cmd_line_option({_Name, _Short, Long, undefined, _Help}) when Long =/= undefined ->
- %% For options with only long form and no argument.
- [$[, $-, $-, Long, $]];
-usage_cmd_line_option({_Name, _Short, _Long, undefined, _Help}) ->
- [];
-usage_cmd_line_option({Name, Short, Long, ArgSpec, _Help}) when is_atom(ArgSpec) ->
- %% For options with no default argument.
- if
- %% For options with short form and argument.
- Short =/= undefined -> [$[, $-, Short, $\s, $<, atom_to_list(Name), $>, $]];
- %% For options with only long form and argument.
- Long =/= undefined -> [$[, $-, $-, Long, $\s, $<, atom_to_list(Name), $>, $]];
- %% For options with neither short nor long form and argument.
- true -> [$[, $<, atom_to_list(Name), $>, $]]
- end;
-usage_cmd_line_option({Name, Short, Long, ArgSpec, _Help}) when is_tuple(ArgSpec) ->
- %% For options with default argument.
- if
- %% For options with short form and default argument.
- Short =/= undefined -> [$[, $-, Short, $\s, $[, $<, atom_to_list(Name), $>, $], $]];
- %% For options with only long form and default argument.
- Long =/= undefined -> [$[, $-, $-, Long, $\s, $[, $<, atom_to_list(Name), $>, $], $]];
- %% For options with neither short nor long form and default argument.
- true -> [$[, $<, atom_to_list(Name), $>, $]]
- end;
-usage_cmd_line_option(Option) when is_list(Option) ->
- %% For custom options that are added to the command line.
- Option.
-
-
-%% @doc Return a list of help messages to print for each of the options and arguments.
--spec usage_options([option_spec()]) -> [string()].
-usage_options(OptSpecList) ->
- usage_options(OptSpecList, []).
-
-
-%% @doc Return a list of usage lines to print for each of the options and arguments.
--spec usage_options([option_spec()], [{OptionName :: string(), Help :: string()}]) -> [string()].
-usage_options(OptSpecList, CustomHelp) ->
- %% Add the usage lines corresponding to the option specifications.
- {MaxOptionLength0, UsageLines0} = add_option_spec_help_lines(OptSpecList, 0, []),
- %% Add the custom usage lines.
- {MaxOptionLength, UsageLines} = add_custom_help_lines(CustomHelp, MaxOptionLength0, UsageLines0),
- MaxLineLength = line_length(),
- lists:reverse([format_usage_line(MaxOptionLength + 1, MaxLineLength, UsageLine) || UsageLine <- UsageLines]).
-
-
--spec add_option_spec_help_lines([option_spec()], PrevMaxOptionLength :: non_neg_integer(), [usage_line_with_length()]) ->
- {MaxOptionLength :: non_neg_integer(), [usage_line_with_length()]}.
-add_option_spec_help_lines([OptSpec | Tail], PrevMaxOptionLength, Acc) ->
- OptionText = usage_option_text(OptSpec),
- HelpText = usage_help_text(OptSpec),
- {MaxOptionLength, ColsWithLength} = get_max_option_length({OptionText, HelpText}, PrevMaxOptionLength),
- add_option_spec_help_lines(Tail, MaxOptionLength, [ColsWithLength | Acc]);
-add_option_spec_help_lines([], MaxOptionLength, Acc) ->
- {MaxOptionLength, Acc}.
-
-
--spec add_custom_help_lines([usage_line()], PrevMaxOptionLength :: non_neg_integer(), [usage_line_with_length()]) ->
- {MaxOptionLength :: non_neg_integer(), [usage_line_with_length()]}.
-add_custom_help_lines([CustomCols | Tail], PrevMaxOptionLength, Acc) ->
- {MaxOptionLength, ColsWithLength} = get_max_option_length(CustomCols, PrevMaxOptionLength),
- add_custom_help_lines(Tail, MaxOptionLength, [ColsWithLength | Acc]);
-add_custom_help_lines([], MaxOptionLength, Acc) ->
- {MaxOptionLength, Acc}.
-
-
--spec usage_option_text(option_spec()) -> string().
-usage_option_text({Name, undefined, undefined, _ArgSpec, _Help}) ->
- %% Neither short nor long form (non-option argument).
- "<" ++ atom_to_list(Name) ++ ">";
-usage_option_text({_Name, Short, undefined, _ArgSpec, _Help}) ->
- %% Only short form.
- [$-, Short];
-usage_option_text({_Name, undefined, Long, _ArgSpec, _Help}) ->
- %% Only long form.
- [$-, $- | Long];
-usage_option_text({_Name, Short, Long, _ArgSpec, _Help}) ->
- %% Both short and long form.
- [$-, Short, $,, $\s, $-, $- | Long].
-
-
--spec usage_help_text(option_spec()) -> string().
-usage_help_text({_Name, _Short, _Long, {_ArgType, ArgValue}, [_ | _] = Help}) ->
- Help ++ " [default: " ++ default_arg_value_to_string(ArgValue) ++ "]";
-usage_help_text({_Name, _Short, _Long, _ArgSpec, Help}) ->
- Help.
-
-
-%% @doc Calculate the maximum width of the column that shows the option's short
-%% and long form.
--spec get_max_option_length(usage_line(), PrevMaxOptionLength :: non_neg_integer()) ->
- {MaxOptionLength :: non_neg_integer(), usage_line_with_length()}.
-get_max_option_length({OptionText, HelpText}, PrevMaxOptionLength) ->
- OptionLength = length(OptionText),
- {erlang:max(OptionLength, PrevMaxOptionLength), {OptionLength, OptionText, HelpText}}.
-
-
-%% @doc Format the usage line that is shown for the options' usage. Each usage
-%% line has 2 columns. The first column shows the options in their short
-%% and long form. The second column shows the wrapped (if necessary) help
-%% text lines associated with each option. e.g.:
-%%
-%% -h, --host Database server host name or IP address; this is the
-%% hostname of the server where the database is running
-%% [default: localhost]
-%% -p, --port Database server port [default: 1000]
-%%
--spec format_usage_line(MaxOptionLength :: non_neg_integer(), MaxLineLength :: non_neg_integer(),
- usage_line_with_length()) -> iolist().
-format_usage_line(MaxOptionLength, MaxLineLength, {OptionLength, OptionText, [_ | _] = HelpText})
- when MaxOptionLength < (MaxLineLength div 2) ->
- %% If the width of the column where the options are shown is smaller than
- %% half the width of a console line then we show the help text line aligned
- %% next to its corresponding option, with a separation of at least 2
- %% characters.
- [Head | Tail] = wrap_text_line(MaxLineLength - MaxOptionLength - 3, HelpText),
- FirstLineIndentation = lists:duplicate(MaxOptionLength - OptionLength + 1, $\s),
- Indentation = [$\n | lists:duplicate(MaxOptionLength + 3, $\s)],
- [" ", OptionText, FirstLineIndentation, Head,
- [[Indentation, Line] || Line <- Tail], $\n];
-format_usage_line(_MaxOptionLength, MaxLineLength, {_OptionLength, OptionText, [_ | _] = HelpText}) ->
- %% If the width of the first column is bigger than the width of a console
- %% line, we show the help text on the next line with an indentation of 6
- %% characters.
- HelpLines = wrap_text_line(MaxLineLength - 6, HelpText),
- [" ", OptionText, [["\n ", Line] || Line <- HelpLines], $\n];
-format_usage_line(_MaxOptionLength, _MaxLineLength, {_OptionLength, OptionText, _HelpText}) ->
- [" ", OptionText, $\n].
-
-
-%% @doc Wrap a text line converting it into several text lines so that the
-%% length of each one of them is never over Length characters.
--spec wrap_text_line(Length :: non_neg_integer(), Text :: string()) -> [string()].
-wrap_text_line(Length, Text) ->
- wrap_text_line(Length, Text, [], 0, []).
-
-wrap_text_line(Length, [Char | Tail], Acc, Count, CurrentLineAcc) when Count < Length ->
- wrap_text_line(Length, Tail, Acc, Count + 1, [Char | CurrentLineAcc]);
-wrap_text_line(Length, [_ | _] = Help, Acc, Count, CurrentLineAcc) ->
- %% Look for the first whitespace character in the current (reversed) line
- %% buffer to get a wrapped line. If there is no whitespace just cut the
- %% line at the position corresponding to the maximum length.
- {NextLineAcc, WrappedLine} = case string:cspan(CurrentLineAcc, " \t") of
- WhitespacePos when WhitespacePos < Count ->
- lists:split(WhitespacePos, CurrentLineAcc);
- _ ->
- {[], CurrentLineAcc}
- end,
- wrap_text_line(Length, Help, [lists:reverse(WrappedLine) | Acc], length(NextLineAcc), NextLineAcc);
-wrap_text_line(_Length, [], Acc, _Count, [_ | _] = CurrentLineAcc) ->
- %% If there was a non-empty line when we reached the buffer, add it to the accumulator
- lists:reverse([lists:reverse(CurrentLineAcc) | Acc]);
-wrap_text_line(_Length, [], Acc, _Count, _CurrentLineAcc) ->
- lists:reverse(Acc).
-
-
-default_arg_value_to_string(Value) when is_atom(Value) ->
- atom_to_list(Value);
-default_arg_value_to_string(Value) when is_binary(Value) ->
- binary_to_list(Value);
-default_arg_value_to_string(Value) when is_integer(Value) ->
- integer_to_list(Value);
-default_arg_value_to_string(Value) when is_float(Value) ->
- lists:flatten(io_lib:format("~w", [Value]));
-default_arg_value_to_string(Value) ->
- Value.
-
-
-%% @doc Tokenize a command line string with support for single and double
-%% quoted arguments (needed for arguments that have embedded whitespace).
-%% The function also supports the expansion of environment variables in
-%% both the Unix (${VAR}; $VAR) and Windows (%VAR%) formats. It does NOT
-%% support wildcard expansion of paths.
--spec tokenize(CmdLine :: string()) -> [nonempty_string()].
-tokenize(CmdLine) ->
- tokenize(CmdLine, [], []).
-
--spec tokenize(CmdLine :: string(), Acc :: [string()], ArgAcc :: string()) -> [string()].
-tokenize([Sep | Tail], Acc, ArgAcc) when ?IS_WHITESPACE(Sep) ->
- NewAcc = case ArgAcc of
- [_ | _] ->
- %% Found separator: add to the list of arguments.
- [lists:reverse(ArgAcc) | Acc];
- [] ->
- %% Found separator with no accumulated argument; discard it.
- Acc
- end,
- tokenize(Tail, NewAcc, []);
-tokenize([QuotationMark | Tail], Acc, ArgAcc) when QuotationMark =:= $"; QuotationMark =:= $' ->
- %% Quoted argument (might contain spaces, tabs, etc.)
- tokenize_quoted_arg(QuotationMark, Tail, Acc, ArgAcc);
-tokenize([Char | _Tail] = CmdLine, Acc, ArgAcc) when Char =:= $$; Char =:= $% ->
- %% Unix and Windows environment variable expansion: ${VAR}; $VAR; %VAR%
- {NewCmdLine, Var} = expand_env_var(CmdLine),
- tokenize(NewCmdLine, Acc, lists:reverse(Var, ArgAcc));
-tokenize([$\\, Char | Tail], Acc, ArgAcc) ->
- %% Escaped char.
- tokenize(Tail, Acc, [Char | ArgAcc]);
-tokenize([Char | Tail], Acc, ArgAcc) ->
- tokenize(Tail, Acc, [Char | ArgAcc]);
-tokenize([], Acc, []) ->
- lists:reverse(Acc);
-tokenize([], Acc, ArgAcc) ->
- lists:reverse([lists:reverse(ArgAcc) | Acc]).
-
--spec tokenize_quoted_arg(QuotationMark :: char(), CmdLine :: string(), Acc :: [string()], ArgAcc :: string()) -> [string()].
-tokenize_quoted_arg(QuotationMark, [QuotationMark | Tail], Acc, ArgAcc) ->
- %% End of quoted argument
- tokenize(Tail, Acc, ArgAcc);
-tokenize_quoted_arg(QuotationMark, [$\\, Char | Tail], Acc, ArgAcc) ->
- %% Escaped char.
- tokenize_quoted_arg(QuotationMark, Tail, Acc, [Char | ArgAcc]);
-tokenize_quoted_arg($" = QuotationMark, [Char | _Tail] = CmdLine, Acc, ArgAcc) when Char =:= $$; Char =:= $% ->
- %% Unix and Windows environment variable expansion (only for double-quoted arguments): ${VAR}; $VAR; %VAR%
- {NewCmdLine, Var} = expand_env_var(CmdLine),
- tokenize_quoted_arg(QuotationMark, NewCmdLine, Acc, lists:reverse(Var, ArgAcc));
-tokenize_quoted_arg(QuotationMark, [Char | Tail], Acc, ArgAcc) ->
- tokenize_quoted_arg(QuotationMark, Tail, Acc, [Char | ArgAcc]);
-tokenize_quoted_arg(_QuotationMark, CmdLine, Acc, ArgAcc) ->
- tokenize(CmdLine, Acc, ArgAcc).
-
-
--spec expand_env_var(CmdLine :: nonempty_string()) -> {string(), string()}.
-expand_env_var(CmdLine) ->
- case CmdLine of
- "${" ++ Tail ->
- expand_env_var("${", $}, Tail, []);
- "$" ++ Tail ->
- expand_env_var("$", Tail, []);
- "%" ++ Tail ->
- expand_env_var("%", $%, Tail, [])
- end.
-
--spec expand_env_var(Prefix :: string(), EndMark :: char(), CmdLine :: string(), Acc :: string()) -> {string(), string()}.
-expand_env_var(Prefix, EndMark, [Char | Tail], Acc)
- when (Char >= $A andalso Char =< $Z) orelse (Char >= $a andalso Char =< $z) orelse
- (Char >= $0 andalso Char =< $9) orelse (Char =:= $_) ->
- expand_env_var(Prefix, EndMark, Tail, [Char | Acc]);
-expand_env_var(Prefix, EndMark, [EndMark | Tail], Acc) ->
- {Tail, get_env_var(Prefix, [EndMark], Acc)};
-expand_env_var(Prefix, _EndMark, CmdLine, Acc) ->
- {CmdLine, Prefix ++ lists:reverse(Acc)}.
-
-
--spec expand_env_var(Prefix :: string(), CmdLine :: string(), Acc :: string()) -> {string(), string()}.
-expand_env_var(Prefix, [Char | Tail], Acc)
- when (Char >= $A andalso Char =< $Z) orelse (Char >= $a andalso Char =< $z) orelse
- (Char >= $0 andalso Char =< $9) orelse (Char =:= $_) ->
- expand_env_var(Prefix, Tail, [Char | Acc]);
-expand_env_var(Prefix, CmdLine, Acc) ->
- {CmdLine, get_env_var(Prefix, "", Acc)}.
-
-
--spec get_env_var(Prefix :: string(), Suffix :: string(), Acc :: string()) -> string().
-get_env_var(Prefix, Suffix, [_ | _] = Acc) ->
- Name = lists:reverse(Acc),
- %% Only expand valid/existing variables.
- case os:getenv(Name) of
- false -> Prefix ++ Name ++ Suffix;
- Value -> Value
- end;
-get_env_var(Prefix, Suffix, []) ->
- Prefix ++ Suffix.
-
-
--spec line_length() -> 0..?LINE_LENGTH.
-line_length() ->
- case io:columns() of
- {ok, Columns} when Columns < ?LINE_LENGTH ->
- Columns - 1;
- _ ->
- ?LINE_LENGTH
- end.
-
-
--spec to_string(term()) -> string().
-to_string(List) when is_list(List) ->
- case io_lib:printable_list(List) of
- true -> List;
- false -> io_lib:format("~p", [List])
- end;
-to_string(Atom) when is_atom(Atom) ->
- atom_to_list(Atom);
-to_string(Value) ->
- io_lib:format("~p", [Value]).

View File

@ -0,0 +1,26 @@
From: Peter Lemenkov <lemenkov@gmail.com>
Date: Tue, 5 Jun 2012 15:10:12 +0400
Subject: [PATCH] Allow discarding building ports
Signed-off-by: Peter Lemenkov <lemenkov@gmail.com>
Conflicts:
src/rebar_port_compiler.erl
diff --git a/src/rebar_port_compiler.erl b/src/rebar_port_compiler.erl
index 9679c80..0ba9e84 100644
--- a/src/rebar_port_compiler.erl
+++ b/src/rebar_port_compiler.erl
@@ -348,6 +348,12 @@ get_specs(Config, AppFile) ->
%% No spec provided. Construct a spec
%% from old-school so_name and sources
[port_spec_from_legacy(Config, AppFile)];
+ [{null,[]}] ->
+ [];
+ [null] ->
+ [];
+ [skip] ->
+ [];
PortSpecs ->
Filtered = filter_port_specs(PortSpecs),
OsType = os:type(),

View File

@ -0,0 +1,24 @@
From: Peter Lemenkov <lemenkov@gmail.com>
Date: Sat, 2 Mar 2013 13:35:36 +0400
Subject: [PATCH] Remove any traces of long-time obsolete escript:foldl/3
Signed-off-by: Peter Lemenkov <lemenkov@gmail.com>
diff --git a/src/rebar_utils.erl b/src/rebar_utils.erl
index a5cc0ff..5947277 100644
--- a/src/rebar_utils.erl
+++ b/src/rebar_utils.erl
@@ -225,12 +225,7 @@ abort(String, Args) ->
%% undocumented exported fun and has been removed in R14.
escript_foldl(Fun, Acc, File) ->
{module, zip} = code:ensure_loaded(zip),
- case erlang:function_exported(zip, foldl, 3) of
- true ->
- emulate_escript_foldl(Fun, Acc, File);
- false ->
- escript:foldl(Fun, Acc, File)
- end.
+ emulate_escript_foldl(Fun, Acc, File).
find_executable(Name) ->
case os:find_executable(Name) of

View File

@ -0,0 +1,166 @@
From: Filip Andres <filip@andresovi.net>
Date: Mon, 29 Jun 2015 14:05:01 +0200
Subject: [PATCH] remove abnfc
diff --git a/ebin/rebar.app b/ebin/rebar.app
index 986f12f..167dad8 100644
--- a/ebin/rebar.app
+++ b/ebin/rebar.app
@@ -5,7 +5,6 @@
[{description, "Rebar: Erlang Build Tool"},
{vsn, "2.6.4"},
{modules, [ rebar,
- rebar_abnfc_compiler,
rebar_app_utils,
rebar_appups,
rebar_asn1_compiler,
@@ -82,7 +81,6 @@
%% Dir specific processing modules
{modules, [
{app_dir, [
- rebar_abnfc_compiler,
rebar_proto_compiler,
rebar_protobuffs_compiler,
rebar_proto_gpb_compiler,
diff --git a/rebar.config b/rebar.config
index eda5a2c..7d0870e 100644
--- a/rebar.config
+++ b/rebar.config
@@ -20,7 +20,6 @@
- (\"escript\":\"foldl\"/\"3\")
- (\"eunit_test\":\"function_wrapper\"/\"2\")
- (\"eflame\":\"apply\"/\"5\")
- - (\"abnfc\":\"file\"/\"2\")
- (\"erlydtl\":\"compile\"/\"3\")
- (\"lfe_comp\":\"file\"/\"2\")
- (\"neotoma\":\"file\"/\"2\")
diff --git a/src/rebar_abnfc_compiler.erl b/src/rebar_abnfc_compiler.erl
deleted file mode 100644
index 37731b5..0000000
--- a/src/rebar_abnfc_compiler.erl
+++ /dev/null
@@ -1,123 +0,0 @@
-%% -*- erlang-indent-level: 4;indent-tabs-mode: nil -*-
-%% ex: ts=4 sw=4 et
-%% -------------------------------------------------------------------
-%%
-%% rebar: Erlang Build Tools
-%%
-%% Copyright (c) 2010 Anthony Ramine (nox@dev-extend.eu),
-%%
-%% Permission is hereby granted, free of charge, to any person obtaining a copy
-%% of this software and associated documentation files (the "Software"), to deal
-%% in the Software without restriction, including without limitation the rights
-%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-%% copies of the Software, and to permit persons to whom the Software is
-%% furnished to do so, subject to the following conditions:
-%%
-%% The above copyright notice and this permission notice shall be included in
-%% all copies or substantial portions of the Software.
-%%
-%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-%% THE SOFTWARE.
-%% -------------------------------------------------------------------
-
-%% The rebar_abnfc_compiler module is a plugin for rebar that compiles
-%% ABNF grammars into parsers. By default, it compiles all src/*.abnf
-%% to src/*.erl.
-%%
-%% Configuration options should be placed in rebar.config under
-%% 'abnfc_opts'. Available options include:
-%%
-%% doc_root: where to find the ABNF grammars to compile
-%% "src" by default
-%%
-%% out_dir: where to put the generated files.
-%% "src" by default
-%%
-%% source_ext: the file extension the ABNF grammars have.
-%% ".abnf" by default
-%%
-%% module_ext: characters to append to the parser's module name
-%% "" by default
--module(rebar_abnfc_compiler).
-
--export([compile/2]).
-
-%% for internal use only
--export([info/2]).
-
--include("rebar.hrl").
-
-%% ===================================================================
-%% Public API
-%% ===================================================================
-
-compile(Config, _AppFile) ->
- DtlOpts = abnfc_opts(Config),
- rebar_base_compiler:run(Config, [],
- option(doc_root, DtlOpts),
- option(source_ext, DtlOpts),
- option(out_dir, DtlOpts),
- option(module_ext, DtlOpts) ++ ".erl",
- fun compile_abnfc/3).
-
-%% ===================================================================
-%% Internal functions
-%% ===================================================================
-
-info(help, compile) ->
- ?CONSOLE(
- "Build ABNF (*.abnf) sources.~n"
- "~n"
- "Valid rebar.config options:~n"
- " ~p~n",
- [
- {abnfc_opts, [{doc_root, "src"},
- {out_dir, "src"},
- {source_ext, ".abnfc"},
- {module_ext, ""}]}
- ]).
-
-abnfc_opts(Config) ->
- rebar_config:get(Config, abnfc_opts, []).
-
-option(Opt, DtlOpts) ->
- proplists:get_value(Opt, DtlOpts, default(Opt)).
-
-default(doc_root) -> "src";
-default(out_dir) -> "src";
-default(source_ext) -> ".abnf";
-default(module_ext) -> "".
-
-abnfc_is_present() ->
- code:which(abnfc) =/= non_existing.
-
-compile_abnfc(Source, _Target, Config) ->
- case abnfc_is_present() of
- false ->
- ?ERROR("~n===============================================~n"
- " You need to install abnfc to compile ABNF grammars~n"
- " Download the latest tarball release from github~n"
- " https://github.com/nygge/abnfc~n"
- " and install it into your erlang library dir~n"
- "===============================================~n~n", []),
- ?FAIL;
- true ->
- AbnfcOpts = abnfc_opts(Config),
- SourceExt = option(source_ext, AbnfcOpts),
- Opts = [noobj,
- {o, option(out_dir, AbnfcOpts)},
- {mod, filename:basename(Source, SourceExt) ++
- option(module_ext, AbnfcOpts)}],
- case abnfc:file(Source, Opts) of
- ok -> ok;
- Error ->
- ?ERROR("Compiling grammar ~s failed:~n ~p~n",
- [Source, Error]),
- ?FAIL
- end
- end.

View File

@ -0,0 +1,174 @@
From: Peter Lemenkov <lemenkov@gmail.com>
Date: Wed, 2 Mar 2016 15:03:13 +0300
Subject: [PATCH] Remove support for gpb compiler
Signed-off-by: Peter Lemenkov <lemenkov@gmail.com>
diff --git a/ebin/rebar.app b/ebin/rebar.app
index 167dad8..e22ad72 100644
--- a/ebin/rebar.app
+++ b/ebin/rebar.app
@@ -31,7 +31,6 @@
rebar_port_compiler,
rebar_proto_compiler,
rebar_protobuffs_compiler,
- rebar_proto_gpb_compiler,
rebar_qc,
rebar_rel_utils,
rebar_reltool,
@@ -83,7 +82,6 @@
{app_dir, [
rebar_proto_compiler,
rebar_protobuffs_compiler,
- rebar_proto_gpb_compiler,
rebar_neotoma_compiler,
rebar_asn1_compiler,
rebar_dia_compiler,
diff --git a/src/rebar_proto_gpb_compiler.erl b/src/rebar_proto_gpb_compiler.erl
deleted file mode 100644
index c528a4a..0000000
--- a/src/rebar_proto_gpb_compiler.erl
+++ /dev/null
@@ -1,142 +0,0 @@
-%% -*- erlang-indent-level: 4;indent-tabs-mode: nil -*-
-%% ex: ts=4 sw=4 et
-%% -------------------------------------------------------------------
-%%
-%% rebar: Erlang Build Tools
-%%
-%% Copyright (c) 2014 Tomas Abrahamsson (tomas.abrahamsson@gmail.com)
-%%
-%% Permission is hereby granted, free of charge, to any person obtaining a copy
-%% of this software and associated documentation files (the "Software"), to deal
-%% in the Software without restriction, including without limitation the rights
-%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-%% copies of the Software, and to permit persons to whom the Software is
-%% furnished to do so, subject to the following conditions:
-%%
-%% The above copyright notice and this permission notice shall be included in
-%% all copies or substantial portions of the Software.
-%%
-%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-%% THE SOFTWARE.
-%% -------------------------------------------------------------------
--module(rebar_proto_gpb_compiler).
-
--export([key/0,
- proto_compile/3,
- proto_clean/3]).
-
-%% for internal use only
--export([proto_info/2]).
-
--include("rebar.hrl").
-
-%% ===================================================================
-%% Public API
-%% ===================================================================
-
-key() ->
- gpb.
-
-proto_compile(Config, _AppFile, Files) ->
- %% Check for gpb library -- if it's not present, fail
- %% since we have.proto files that need building
- case gpb_is_present() of
- true ->
- GpbOpts = user_gpb_opts(Config),
- Targets = [filename:join("src", target_filename(F, GpbOpts))
- || F <- Files],
- rebar_base_compiler:run(Config, [],
- lists:zip(Files, Targets),
- fun compile_gpb/3,
- [{check_last_mod, true}]);
- false ->
- ?ERROR("The gpb library is not present in code path!\n", []),
- ?FAIL
- end.
-
-target_filename(ProtoFileName, GpbOpts) ->
- ModulePrefix = proplists:get_value(module_name_prefix, GpbOpts, ""),
- ModuleSuffix = proplists:get_value(module_name_suffix, GpbOpts, ""),
- Base = filename:basename(ProtoFileName, ".proto"),
- ModulePrefix ++ Base ++ ModuleSuffix ++ ".erl".
-
-proto_clean(Config, _AppFile, ProtoFiles) ->
- GpbOpts = user_gpb_opts(Config) ++ default_dest_opts(),
- rebar_file_utils:delete_each(
- [beam_file(F, GpbOpts) || F <- ProtoFiles]
- ++ [erl_file(F, GpbOpts) || F <- ProtoFiles]
- ++ [hrl_file(F, GpbOpts) || F <- ProtoFiles]),
- ok.
-
-%% ===================================================================
-%% Internal functions
-%% ===================================================================
-
-proto_info(help, compile) ->
- ?CONSOLE(
- " gpb_opts is passed as options to gpb_compile:file/2.~n"
- " erl_opts is used when compiling the generated erlang files,~n"
- " so you might want to add an include path to gpb here,~n"
- " for gpb.hrl, or else use the include_as_lib gpb_opts option,~n"
- " or the defs_as_proplists gpb_opts option.~n",
- []);
-proto_info(help, clean) ->
- ?CONSOLE("", []).
-
-gpb_is_present() ->
- code:which(gpb) =/= non_existing.
-
-user_gpb_opts(Config) ->
- rebar_config:get_local(Config, gpb_opts, []).
-
-default_dest_opts() ->
- [{o_erl, "src"}, {o_hrl, "include"}].
-
-compile_gpb(Source, _Target, Config) ->
- SourceFullPath = filename:absname(Source),
- GpbOpts = user_gpb_opts(Config) ++ default_dest_opts()
- ++ default_include_opts(SourceFullPath),
- ok = filelib:ensure_dir(filename:join("ebin", "dummy")),
- ok = filelib:ensure_dir(filename:join("include", "dummy")),
- case gpb_compile:file(SourceFullPath, GpbOpts) of
- ok ->
- ok;
- {error, Reason} ->
- ReasonStr = gpb_compile:format_error(Reason),
- ?ERROR("Failed to compile ~s: ~s~n", [SourceFullPath, ReasonStr]),
- ?FAIL
- end.
-
-default_include_opts(SourceFullPath) ->
- [{i,filename:dirname(SourceFullPath)}].
-
-beam_file(ProtoFile, GpbOpts) ->
- proto_filename_to_path("ebin", ProtoFile, ".beam", GpbOpts).
-
-erl_file(ProtoFile, GpbOpts) ->
- ErlOutDir = get_erl_outdir(GpbOpts),
- proto_filename_to_path(ErlOutDir, ProtoFile, ".erl", GpbOpts).
-
-hrl_file(ProtoFile, GpbOpts) ->
- HrlOutDir = get_hrl_outdir(GpbOpts),
- proto_filename_to_path(HrlOutDir, ProtoFile, ".hrl", GpbOpts).
-
-proto_filename_to_path(Dir, ProtoFile, NewExt, GpbOpts) ->
- BaseNoExt = filename:basename(ProtoFile, ".proto"),
- Prefix = proplists:get_value(module_name_prefix, GpbOpts, ""),
- Suffix = proplists:get_value(module_name_suffix, GpbOpts, ""),
- filename:join([Dir, Prefix ++ BaseNoExt ++ Suffix ++ NewExt]).
-
-get_erl_outdir(Opts) ->
- proplists:get_value(o_erl, Opts, get_outdir(Opts)).
-
-get_hrl_outdir(Opts) ->
- proplists:get_value(o_hrl, Opts, get_outdir(Opts)).
-
-get_outdir(Opts) ->
- proplists:get_value(o, Opts, ".").

View File

@ -0,0 +1,64 @@
From: Peter Lemenkov <lemenkov@gmail.com>
Date: Wed, 2 Mar 2016 15:10:20 +0300
Subject: [PATCH] Remove pre-R15B02 workaround
Signed-off-by: Peter Lemenkov <lemenkov@gmail.com>
diff --git a/src/rebar_eunit.erl b/src/rebar_eunit.erl
index f4d7b76..19c3138 100644
--- a/src/rebar_eunit.erl
+++ b/src/rebar_eunit.erl
@@ -72,8 +72,6 @@
%% for internal use only
-export([info/2]).
--dialyzer({no_missing_calls, pre15b02_eunit_primitive/3}).
-
-include("rebar.hrl").
-define(EUNIT_DIR, ".eunit").
@@ -436,18 +434,6 @@ get_beam_test_exports(ModuleStr) ->
end.
make_test_primitives(RawTests) ->
- %% Use {test,M,F} and {generator,M,F} if at least R15B02. Otherwise,
- %% use eunit_test:function_wrapper/2 fallback.
- %% eunit_test:function_wrapper/2 was renamed to eunit_test:mf_wrapper/2
- %% in R15B02; use that as >= R15B02 check.
- %% TODO: remove fallback and use only {test,M,F} and {generator,M,F}
- %% primitives once at least R15B02 is required.
- {module, eunit_test} = code:ensure_loaded(eunit_test),
- MakePrimitive = case erlang:function_exported(eunit_test, mf_wrapper, 2) of
- true -> fun eunit_primitive/3;
- false -> fun pre15b02_eunit_primitive/3
- end,
-
?CONSOLE(" Running test function(s):~n", []),
F = fun({M, F2}, Acc) ->
?CONSOLE(" ~p:~p/0~n", [M, F2]),
@@ -456,23 +442,15 @@ make_test_primitives(RawTests) ->
case re:run(FNameStr, "_test_") of
nomatch ->
%% Normal test
- MakePrimitive(test, M, F2);
+ {test, M, F2};
_ ->
%% Generator
- MakePrimitive(generator, M, F2)
+ {generator, M, F2}
end,
[eunit_module_suite(M, NewFunction)|Acc]
end,
lists:foldl(F, [], RawTests).
-eunit_primitive(Type, M, F) ->
- {Type, M, F}.
-
-pre15b02_eunit_primitive(test, M, F) ->
- eunit_test:function_wrapper(M, F);
-pre15b02_eunit_primitive(generator, M, F) ->
- {generator, eunit_test:function_wrapper(M, F)}.
-
% Add a test group for eunit_surefire to be able to deduce the testsuite.
% Calling eunit:test({module, M}) does exactly this as well.
eunit_module_suite(M, X) ->

View File

@ -0,0 +1,39 @@
From: Peter Lemenkov <lemenkov@gmail.com>
Date: Wed, 2 Mar 2016 13:52:44 +0300
Subject: [PATCH] Use erlang:timestamp/0 explicitly
Signed-off-by: Peter Lemenkov <lemenkov@gmail.com>
diff --git a/src/rebar_utils.erl b/src/rebar_utils.erl
index 5947277..8fe9719 100644
--- a/src/rebar_utils.erl
+++ b/src/rebar_utils.erl
@@ -791,7 +791,7 @@ cross_sizeof(Arch, Type) ->
end.
mktempfile(Suffix) ->
- {A,B,C} = rebar_now(),
+ {A,B,C} = erlang:timestamp(),
Dir = temp_dir(),
File = "rebar_"++os:getpid()++
integer_to_list(A)++"_"++
@@ -815,19 +815,6 @@ windows_temp_dir() ->
TEMP -> TEMP
end.
-rebar_now() ->
- case erlang:function_exported(erlang, timestamp, 0) of
- true ->
- erlang:timestamp();
- false ->
- %% erlang:now/0 was deprecated in 18.0. One solution to avoid the
- %% deprecation warning is to use
- %% -compile({nowarn_deprecated_function, [{erlang, now, 0}]}), but
- %% that would raise a warning in versions older than 18.0. Calling
- %% erlang:now/0 via apply/3 avoids that.
- apply(erlang, now, [])
- end.
-
native_wordsize() ->
try erlang:system_info({wordsize, external}) of
Val ->

View File

@ -0,0 +1,25 @@
From: Peter Lemenkov <lemenkov@gmail.com>
Date: Sun, 6 Mar 2016 01:25:36 +0300
Subject: [PATCH] Try shell variable VSN first
Try shell variable VSN first before substituting version placeholder in
app-file.
Signed-off-by: Peter Lemenkov <lemenkov@gmail.com>
diff --git a/src/rebar_otp_app.erl b/src/rebar_otp_app.erl
index b3566c8..187b1c3 100644
--- a/src/rebar_otp_app.erl
+++ b/src/rebar_otp_app.erl
@@ -116,7 +116,10 @@ preprocess(Config, AppSrcFile) ->
%% AppSrcFile may contain instructions for generating a vsn number
- {Config2, Vsn} = rebar_app_utils:app_vsn(Config1, AppSrcFile),
+ {Config2, Vsn} = case os:getenv("VSN") of
+ false -> rebar_app_utils:app_vsn(Config1, AppSrcFile);
+ V -> {Config1, V}
+ end,
A2 = lists:keystore(vsn, 1, A1, {vsn, Vsn}),
%% systools:make_relup/4 fails with {missing_param, registered}

View File

@ -0,0 +1,30 @@
From: Peter Lemenkov <lemenkov@gmail.com>
Date: Mon, 7 Mar 2016 16:55:33 +0300
Subject: [PATCH] Allow ignoring missing deps
Signed-off-by: Peter Lemenkov <lemenkov@gmail.com>
diff --git a/src/rebar_deps.erl b/src/rebar_deps.erl
index 251bdee..577db64 100644
--- a/src/rebar_deps.erl
+++ b/src/rebar_deps.erl
@@ -163,12 +163,17 @@ do_check_deps(Config) ->
{Config1, {AvailDeps, []}} ->
%% No missing deps
{Config1, AvailDeps};
- {_Config1, {_, MissingDeps}} ->
+ {Config1, {AvailDeps, MissingDeps}} ->
lists:foreach(fun (#dep{app=App, vsn_regex=Vsn, source=Src}) ->
?CONSOLE("Dependency not available: "
"~p-~s (~p)\n", [App, Vsn, Src])
end, MissingDeps),
- ?FAIL
+ case os:getenv("IGNORE_MISSING_DEPS") of
+ false -> ?FAIL;
+ _ ->
+ ?CONSOLE("Continue anyway because IGNORE_MISSING_DEPS was set\n", []),
+ {Config1, lists:sort(AvailDeps ++ MissingDeps)}
+ end
end.
'check-deps'(Config, _) ->

View File

@ -0,0 +1,32 @@
From: Peter Lemenkov <lemenkov@gmail.com>
Date: Thu, 7 Nov 2019 15:07:35 +0100
Subject: [PATCH] Drop obsolete crypto:rand_uniform/2
Signed-off-by: Peter Lemenkov <lemenkov@gmail.com>
diff --git a/src/rebar_ct.erl b/src/rebar_ct.erl
index b27f661..5541b1c 100644
--- a/src/rebar_ct.erl
+++ b/src/rebar_ct.erl
@@ -288,7 +288,7 @@ search_ct_specs_from(Cwd, TestDir, Config) ->
build_name(Config) ->
%% generate a unique name for our test node, we want
%% to make sure the odds of name clashing are low
- Random = integer_to_list(crypto:rand_uniform(0, 10000)),
+ Random = integer_to_list(rand:uniform(10001) - 1),
case rebar_config:get_local(Config, ct_use_short_names, false) of
true -> "-sname test" ++ Random;
false -> " -name test" ++ Random ++ "@" ++ net_adm:localhost()
diff --git a/src/rebar_eunit.erl b/src/rebar_eunit.erl
index 19c3138..5606e14 100644
--- a/src/rebar_eunit.erl
+++ b/src/rebar_eunit.erl
@@ -277,7 +277,7 @@ randomize_suites(Config, Modules) ->
undefined ->
Modules;
"true" ->
- Seed = crypto:rand_uniform(1, 65535),
+ Seed = rand:uniform(65536) - 1,
randomize_suites1(Modules, Seed);
String ->
try list_to_integer(String) of

View File

@ -0,0 +1,249 @@
From: Peter Lemenkov <lemenkov@gmail.com>
Date: Thu, 7 Nov 2019 16:02:20 +0100
Subject: [PATCH] Remove compat random modules
Signed-off-by: Peter Lemenkov <lemenkov@gmail.com>
diff --git a/ebin/rebar.app b/ebin/rebar.app
index e22ad72..f1477e9 100644
--- a/ebin/rebar.app
+++ b/ebin/rebar.app
@@ -42,8 +42,7 @@
rebar_utils,
rebar_xref,
rebar_metacmds,
- rmemo,
- rebar_rand_compat ]},
+ rmemo ]},
{registered, []},
{applications,
[
diff --git a/rebar.config b/rebar.config
index 7d0870e..6fa4f27 100644
--- a/rebar.config
+++ b/rebar.config
@@ -29,9 +29,7 @@
- (\"diameter_codegen\":\"from_dict\"/\"4\")
- (\"diameter_dict_util\":\"format_error\"/\"1\")
- (\"diameter_dict_util\":\"parse\"/\"2\")
- - (\"erlang\":\"timestamp\"/\"0\")
- - (\"rebar_rnd\":\"seed\"/\"1\")
- - (\"rebar_rnd\":\"uniform\"/\"0\"))",
+ - (\"erlang\":\"timestamp\"/\"0\"))",
[]}]}.
{dialyzer,
diff --git a/src/rebar.erl b/src/rebar.erl
index 91593c2..488be2c 100644
--- a/src/rebar.erl
+++ b/src/rebar.erl
@@ -220,9 +220,6 @@ run_aux(BaseConfig, Commands) ->
{error, {already_started, _}} -> ok
end,
- %% Make sure rebar_rnd module is generated, compiled, and loaded
- {ok, rebar_rnd} = rebar_rand_compat:init("rebar_rnd"),
-
%% Convert command strings to atoms
CommandAtoms = [list_to_atom(C) || C <- Commands],
diff --git a/src/rebar_eunit.erl b/src/rebar_eunit.erl
index 5606e14..c78a112 100644
--- a/src/rebar_eunit.erl
+++ b/src/rebar_eunit.erl
@@ -291,9 +291,9 @@ randomize_suites(Config, Modules) ->
end.
randomize_suites1(Modules, Seed) ->
- _ = rebar_rnd:seed({35, Seed, 1337}),
+ _ = rand:seed(exsplus, {35, Seed, 1337}),
?CONSOLE("Randomizing suite order with seed ~b~n", [Seed]),
- [X||{_,X} <- lists:sort([{rebar_rnd:uniform(), M} || M <- Modules])].
+ [X||{_,X} <- lists:sort([{rand:uniform(), M} || M <- Modules])].
%%
%% == get matching tests ==
diff --git a/src/rebar_rand_compat.erl b/src/rebar_rand_compat.erl
deleted file mode 100644
index 849ee35..0000000
--- a/src/rebar_rand_compat.erl
+++ /dev/null
@@ -1,178 +0,0 @@
-%%% -*- erlang-indent-level: 4;indent-tabs-mode: nil -*-
-%%% ex: ts=4 sw=4 et
-%%%
-%%% Copyright (c) 2016 Tuncer Ayaz
-%%%
-%%% Permission to use, copy, modify, and/or distribute this software
-%%% for any purpose with or without fee is hereby granted, provided
-%%% that the above copyright notice and this permission notice appear
-%%% in all copies.
-%%%
-%%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
-%%% WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
-%%% WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
-%%% AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
-%%% CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-%%% LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
-%%% NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
-%%% CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
--module(rebar_rand_compat).
-
-%% API
--export([ init/0
- , init/1
- ]).
-
--define(DEFAULT_MODNAME, "rnd").
-
-%%%===================================================================
-%%% API
-%%%===================================================================
-
-%%--------------------------------------------------------------------
-%% @doc
-%% Generate, compile and load rnd module.
-%% @end
-%%--------------------------------------------------------------------
--spec init() -> {'ok', module()}.
-init() ->
- init(?DEFAULT_MODNAME).
-
-%%--------------------------------------------------------------------
-%% @doc
-%% Generate, compile and load ModName module.
-%% @end
-%%--------------------------------------------------------------------
--spec init(string()) -> {'ok', module()}.
-init(ModName) ->
- %% First, select the right module, then generate the appropriate code as a
- %% string, and finally compile and load it as ModName.
- Src = select(ModName),
- {ok, Mod, Bin, []} = compile(Src),
- {module, Mod} = code:load_binary(Mod, ModName++".erl", Bin),
- {ok, Mod}.
-
-%%%===================================================================
-%%% Internal functions
-%%%===================================================================
-
-%% Select right rand module and return wrapper module's source as string
--spec select(string()) -> string().
-select(ModName) ->
- case code:which(rand) of
- non_existing ->
- src(ModName, fun funs_random/0);
- _ ->
- src(ModName, fun funs_rand/0)
- end.
-
-%% Return module's implementation as a string.
--spec src(string(), fun(() -> binary())) -> string().
-src(ModName, GenFuns) ->
- lists:flatten(
- io_lib:format(
- <<"
--module(~s).
--export([ seed/0
- , seed/1
- , uniform/0
- , uniform/1
- , uniform_s/1
- , uniform_s/2
- ]).
-
-%% Functions
-~s
-">>
-, [ModName, GenFuns()])).
-
-%% random.beam wrapper
-funs_random() ->
- <<"
-seed() -> random:seed().
-seed(Exp) -> random:seed(Exp).
-uniform() -> random:uniform().
-uniform(N) -> random:uniform(N).
-uniform_s(St) -> random:uniform_s(St).
-uniform_s(N, St) -> random:uniform_s(N, St).
-">>.
-
-%% rand.beam wrapper
-funs_rand() ->
- <<"
-seed() -> rand:seed(exsplus).
-seed(Exp) -> rand:seed(exsplus, Exp).
-uniform() -> rand:uniform().
-uniform(N) -> rand:uniform(N).
-uniform_s(St) -> rand:uniform_s(St).
-uniform_s(N, St) -> rand:uniform_s(N, St).
-">>.
-
-compile(String) ->
- Forms = convert(String ++ eof, []),
- compile:forms(Forms, [return]).
-
-%% Parse string into forms for compiler.
-convert({done, {eof, _EndLocation}, _LeftOverChars}, Acc)->
- %% Finished
- lists:reverse(Acc);
-convert({done, {error, ErrorInfo, _EndLocation}, _LeftOverChars}, _Acc)->
- ErrorInfo;
-convert({done, {ok, Tokens, _EndLocation}, LeftOverChars}, Acc)->
- case erl_parse:parse_form(Tokens) of
- {ok, AbsForm} ->
- convert(LeftOverChars, [AbsForm|Acc]);
- {error, AbsForm} ->
- convert(LeftOverChars, AbsForm)
- end;
-convert({more, Continuation}, Acc)->
- convert(erl_scan:tokens(Continuation, [], 1), Acc);
-convert(String, Acc) ->
- convert(erl_scan:tokens([], String, 1), Acc).
-
-%%%===================================================================
-%%% Tests
-%%%===================================================================
-
--ifdef(TEST).
--include_lib("eunit/include/eunit.hrl").
-
-init_test() ->
- DefMod = list_to_atom(?DEFAULT_MODNAME),
- ok = unload(DefMod),
- ?assertMatch(false, code:is_loaded(DefMod)),
- ?assertMatch({ok, DefMod}, init()),
- ?assertMatch({file, _}, code:is_loaded(DefMod)),
- check_api(DefMod),
- CustomMod = foornd,
- CustomName = "foornd",
- ok = unload(CustomMod),
- ?assertMatch(false, code:is_loaded(CustomMod)),
- ?assertMatch({ok, CustomMod}, init(CustomName)),
- ?assertMatch({file, _}, code:is_loaded(CustomMod)),
- check_api(CustomMod).
-
-unload(Mod) ->
- case code:is_loaded(Mod) of
- false ->
- ok;
- {file, _} ->
- code:delete(Mod),
- code:purge(Mod),
- ok
- end.
-
-check_api(Mod) ->
- Exports = [ {seed, 0}
- , {seed, 1}
- , {uniform, 0}
- , {uniform, 1}
- , {uniform_s, 1}
- , {uniform_s, 2}
- , {module_info, 0}
- , {module_info, 1}
- ],
- ?assertMatch(Exports, Mod:module_info(exports)).
-
--endif.

BIN
rebar-2.6.4.tar.gz Normal file

Binary file not shown.