You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@couchdb.apache.org by rn...@apache.org on 2014/02/03 13:59:46 UTC
[07/27] Build with rebar
http://git-wip-us.apache.org/repos/asf/couchdb/blob/f84eb4fc/src/rebar/src/getopt.erl
----------------------------------------------------------------------
diff --git a/src/rebar/src/getopt.erl b/src/rebar/src/getopt.erl
deleted file mode 100644
index f9852fb..0000000
--- a/src/rebar/src/getopt.erl
+++ /dev/null
@@ -1,842 +0,0 @@
-%%%-------------------------------------------------------------------
-%%% @author Juan Jose Comellas <ju...@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(getopt).
--author('juanjo@comellas.org').
-
--export([parse/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.
--spec parse([option_spec()], string() | [string()]) ->
- {ok, {[option()], [string()]}} | {error, {Reason :: atom(), Data :: any()}}.
-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 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 HelpLength 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) ->
- float_to_list(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() -> non_neg_integer().
-line_length() ->
- case io:columns() of
- {ok, Columns} when Columns < ?LINE_LENGTH ->
- Columns - 1;
- _ ->
- ?LINE_LENGTH
- end.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/f84eb4fc/src/rebar/src/mustache.erl
----------------------------------------------------------------------
diff --git a/src/rebar/src/mustache.erl b/src/rebar/src/mustache.erl
deleted file mode 100644
index f6963cd..0000000
--- a/src/rebar/src/mustache.erl
+++ /dev/null
@@ -1,228 +0,0 @@
-%% The MIT License
-%%
-%% Copyright (c) 2009 Tom Preston-Werner <to...@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(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}).
-
-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: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:escape(mustache:get(" ++ Content ++ ", Ctx, " ++ atom_to_list(Mod) ++ "))";
-compile_tag("{", Content, State) ->
- Mod = State#mstate.mod,
- "mustache: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("<", Acc));
-escape([">" | Rest], Acc) ->
- escape(Rest, lists:reverse(">", Acc));
-escape(["&" | Rest], Acc) ->
- escape(Rest, lists:reverse("&", Acc));
-escape([X | Rest], Acc) ->
- escape(Rest, [X | Acc]).
-
-%%---------------------------------------------------------------------------
-
-start([T]) ->
- Out = render(list_to_atom(T)),
- io:format(Out ++ "~n", []).
http://git-wip-us.apache.org/repos/asf/couchdb/blob/f84eb4fc/src/rebar/src/rebar.erl
----------------------------------------------------------------------
diff --git a/src/rebar/src/rebar.erl b/src/rebar/src/rebar.erl
deleted file mode 100644
index 2d9fe04..0000000
--- a/src/rebar/src/rebar.erl
+++ /dev/null
@@ -1,501 +0,0 @@
-%% -*- erlang-indent-level: 4;indent-tabs-mode: nil -*-
-%% ex: ts=4 sw=4 et
-%% -------------------------------------------------------------------
-%%
-%% rebar: Erlang Build Tools
-%%
-%% Copyright (c) 2009 Dave Smith (dizzyd@dizzyd.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).
-
--export([main/1,
- run/2,
- help/0,
- parse_args/1,
- version/0,
- get_jobs/1]).
-
--include("rebar.hrl").
-
--ifndef(BUILD_TIME).
--define(BUILD_TIME, "undefined").
--endif.
-
--ifndef(VCS_INFO).
--define(VCS_INFO, "undefined").
--endif.
-
--ifndef(OTP_INFO).
--define(OTP_INFO, "undefined").
--endif.
-
--define(DEFAULT_JOBS, 3).
-
-%% ====================================================================
-%% Public API
-%% ====================================================================
-
-%% escript Entry point
-main(Args) ->
- case catch(run(Args)) of
- ok ->
- ok;
- rebar_abort ->
- rebar_utils:delayed_halt(1);
- Error ->
- %% Nothing should percolate up from rebar_core;
- %% Dump this error to console
- io:format("Uncaught error in rebar_core: ~p\n", [Error]),
- rebar_utils:delayed_halt(1)
- end.
-
-%% Erlang-API entry point
-run(BaseConfig, Commands) ->
- _ = application:load(rebar),
- run_aux(BaseConfig, Commands).
-
-%% ====================================================================
-%% Internal functions
-%% ====================================================================
-
-run(["help"|RawCmds]) when RawCmds =/= [] ->
- ok = load_rebar_app(),
- Cmds = unabbreviate_command_names(RawCmds),
- Args = parse_args(Cmds),
- BaseConfig = init_config(Args),
- {BaseConfig1, _} = save_options(BaseConfig, Args),
- BaseConfig2 = init_config1(BaseConfig1),
- rebar_core:help(BaseConfig2, [list_to_atom(C) || C <- Cmds]);
-run(["help"]) ->
- help();
-run(["info"|_]) ->
- help();
-run(["version"]) ->
- ok = load_rebar_app(),
- %% Display vsn and build time info
- version();
-run(RawArgs) ->
- ok = load_rebar_app(),
- %% Parse out command line arguments -- what's left is a list of commands to
- %% run -- and start running commands
- Args = parse_args(RawArgs),
- BaseConfig = init_config(Args),
- {BaseConfig1, Cmds} = save_options(BaseConfig, Args),
-
- case rebar_config:get_xconf(BaseConfig1, enable_profiling, false) of
- true ->
- io:format("Profiling!\n"),
- try
- fprof:apply(fun run_aux/2, [BaseConfig1, Cmds])
- after
- ok = fprof:profile(),
- ok = fprof:analyse([{dest, "fprof.analysis"}])
- end;
- false ->
- run_aux(BaseConfig1, Cmds)
- end.
-
-load_rebar_app() ->
- %% Pre-load the rebar app so that we get default configuration
- ok = application:load(rebar).
-
-init_config({Options, _NonOptArgs}) ->
- %% If $HOME/.rebar/config exists load and use as global config
- GlobalConfigFile = filename:join([os:getenv("HOME"), ".rebar", "config"]),
- GlobalConfig = case filelib:is_regular(GlobalConfigFile) of
- true ->
- ?DEBUG("Load global config file ~p~n",
- [GlobalConfigFile]),
- rebar_config:new(GlobalConfigFile);
- false ->
- rebar_config:new()
- end,
-
- %% Set the rebar config to use
- GlobalConfig1 = case proplists:get_value(config, Options) of
- undefined ->
- GlobalConfig;
- Conf ->
- rebar_config:set_global(GlobalConfig, config, Conf)
- end,
-
- GlobalConfig2 = set_log_level(GlobalConfig1, Options),
- %% Initialize logging system
- ok = rebar_log:init(GlobalConfig2),
-
- BaseConfig = rebar_config:base_config(GlobalConfig2),
-
- %% Keep track of how many operations we do, so we can detect bad commands
- BaseConfig1 = rebar_config:set_xconf(BaseConfig, operations, 0),
- %% Initialize vsn cache
- rebar_config:set_xconf(BaseConfig1, vsn_cache, dict:new()).
-
-init_config1(BaseConfig) ->
- %% Determine the location of the rebar executable; important for pulling
- %% resources out of the escript
- ScriptName = filename:absname(escript:script_name()),
- BaseConfig1 = rebar_config:set_xconf(BaseConfig, escript, ScriptName),
- ?DEBUG("Rebar location: ~p\n", [ScriptName]),
- %% Note the top-level directory for reference
- AbsCwd = filename:absname(rebar_utils:get_cwd()),
- rebar_config:set_xconf(BaseConfig1, base_dir, AbsCwd).
-
-run_aux(BaseConfig, Commands) ->
- %% Make sure crypto is running
- case crypto:start() of
- ok -> ok;
- {error,{already_started,crypto}} -> ok
- end,
-
- %% Convert command strings to atoms
- CommandAtoms = [list_to_atom(C) || C <- Commands],
-
- BaseConfig1 = init_config1(BaseConfig),
-
- %% Process each command, resetting any state between each one
- rebar_core:process_commands(CommandAtoms, BaseConfig1).
-
-%%
-%% print help/usage string
-%%
-help() ->
- OptSpecList = option_spec_list(),
- getopt:usage(OptSpecList, "rebar",
- "[var=value,...] <command,...>",
- [{"var=value", "rebar global variables (e.g. force=1)"},
- {"command", "Command to run (e.g. compile)"}]),
- ?CONSOLE(
- "Type 'rebar help <CMD1> <CMD2>' for help on specific commands."
- "~n~n", []),
- ?CONSOLE(
- "Core rebar.config options:~n"
- " ~p~n"
- " ~p~n"
- " ~p~n"
- " ~p~n"
- " ~p~n"
- " ~p~n",
- [
- {lib_dirs, []},
- {sub_dirs, ["dir1", "dir2"]},
- {plugins, [plugin1, plugin2]},
- {plugin_dir, "some_other_directory"},
- {pre_hooks, [{clean, "./prepare_package_files.sh"},
- {"linux", compile, "c_src/build_linux.sh"},
- {compile, "escript generate_headers"},
- {compile, "escript check_headers"}]},
- {post_hooks, [{clean, "touch file1.out"},
- {"freebsd", compile, "c_src/freebsd_tweaks.sh"},
- {eunit, "touch file2.out"},
- {compile, "touch postcompile.out"}]}
- ]).
-
-%%
-%% Parse command line arguments using getopt and also filtering out any
-%% key=value pairs. What's left is the list of commands to run
-%%
-parse_args(RawArgs) ->
- %% Parse getopt options
- OptSpecList = option_spec_list(),
- case getopt:parse(OptSpecList, RawArgs) of
- {ok, Args} ->
- Args;
- {error, {Reason, Data}} ->
- ?ERROR("~s ~p~n~n", [Reason, Data]),
- help(),
- rebar_utils:delayed_halt(1)
- end.
-
-save_options(Config, {Options, NonOptArgs}) ->
- %% Check options and maybe halt execution
- ok = show_info_maybe_halt(Options, NonOptArgs),
-
- GlobalDefines = proplists:get_all_values(defines, Options),
-
- Config1 = rebar_config:set_xconf(Config, defines, GlobalDefines),
-
- %% Setup profiling flag
- Config2 = rebar_config:set_xconf(Config1, enable_profiling,
- proplists:get_bool(profile, Options)),
-
- %% Setup flag to keep running after a single command fails
- Config3 = rebar_config:set_xconf(Config2, keep_going,
- proplists:get_bool(keep_going, Options)),
-
- %% Set global variables based on getopt options
- Config4 = set_global_flag(Config3, Options, force),
- Config5 = case proplists:get_value(jobs, Options, ?DEFAULT_JOBS) of
- ?DEFAULT_JOBS ->
- Config4;
- Jobs ->
- rebar_config:set_global(Config4, jobs, Jobs)
- end,
-
- %% Filter all the flags (i.e. strings of form key=value) from the
- %% command line arguments. What's left will be the commands to run.
- {Config6, RawCmds} = filter_flags(Config5, NonOptArgs, []),
- {Config6, unabbreviate_command_names(RawCmds)}.
-
-%%
-%% set log level based on getopt option
-%%
-set_log_level(Config, Options) ->
- LogLevel = case proplists:get_all_values(verbose, Options) of
- [] ->
- rebar_log:default_level();
- Verbosities ->
- lists:last(Verbosities)
- end,
- rebar_config:set_global(Config, verbose, LogLevel).
-
-%%
-%% show version information and halt
-%%
-version() ->
- {ok, Vsn} = application:get_key(rebar, vsn),
- ?CONSOLE("rebar ~s ~s ~s ~s\n",
- [Vsn, ?OTP_INFO, ?BUILD_TIME, ?VCS_INFO]).
-
-
-%%
-%% set global flag based on getopt option boolean value
-%%
-set_global_flag(Config, Options, Flag) ->
- Value = case proplists:get_bool(Flag, Options) of
- true ->
- "1";
- false ->
- "0"
- end,
- rebar_config:set_global(Config, Flag, Value).
-
-%%
-%% show info and maybe halt execution
-%%
-show_info_maybe_halt(Opts, NonOptArgs) ->
- false = show_info_maybe_halt(help, Opts, fun help/0),
- false = show_info_maybe_halt(commands, Opts, fun commands/0),
- false = show_info_maybe_halt(version, Opts, fun version/0),
- case NonOptArgs of
- [] ->
- ?CONSOLE("No command to run specified!~n",[]),
- help(),
- rebar_utils:delayed_halt(1);
- _ ->
- ok
- end.
-
-show_info_maybe_halt(O, Opts, F) ->
- case proplists:get_bool(O, Opts) of
- true ->
- F(),
- rebar_utils:delayed_halt(0);
- false ->
- false
- end.
-
-%%
-%% print known commands
-%%
-commands() ->
- S = <<"
-clean Clean
-compile Compile sources
-
-escriptize Generate escript archive
-
-create template= [var=foo,...] Create skel based on template and vars
-create-app [appid=myapp] Create simple app skel
-create-node [nodeid=mynode] Create simple node skel
-list-templates List available templates
-
-doc Generate Erlang program documentation
-
-check-deps Display to be fetched dependencies
-get-deps Fetch dependencies
-update-deps Update fetched dependencies
-delete-deps Delete fetched dependencies
-list-deps List dependencies
-
-generate [dump_spec=0/1] Build release with reltool
-overlay Run reltool overlays only
-
-generate-upgrade previous_release=path Build an upgrade package
-
-generate-appups previous_release=path Generate appup files
-
-eunit [suites=foo] Run eunit tests in foo.erl and
- test/foo_tests.erl
- [suites=foo] [tests=bar] Run specific eunit tests [first test name
- starting with 'bar' in foo.erl and
- test/foo_tests.erl]
- [tests=bar] For every existing suite, run the first
- test whose name starts with bar and, if
- no such test exists, run the test whose
- name starts with bar in the suite's
- _tests module
-
-ct [suites=] [case=] Run common_test suites
-
-qc Test QuickCheck properties
-
-xref Run cross reference analysis
-
-help Show the program options
-version Show version information
-">>,
- io:put_chars(S).
-
-get_jobs(Config) ->
- rebar_config:get_global(Config, jobs, ?DEFAULT_JOBS).
-
-%%
-%% options accepted via getopt
-%%
-option_spec_list() ->
- Jobs = ?DEFAULT_JOBS,
- JobsHelp = io_lib:format(
- "Number of concurrent workers a command may use. Default: ~B",
- [Jobs]),
- VerboseHelp = "Verbosity level (-v, -vv, -vvv, --verbose 3). Default: 0",
- [
- %% {Name, ShortOpt, LongOpt, ArgSpec, HelpMsg}
- {help, $h, "help", undefined, "Show the program options"},
- {commands, $c, "commands", undefined, "Show available commands"},
- {verbose, $v, "verbose", integer, VerboseHelp},
- {version, $V, "version", undefined, "Show version information"},
- {force, $f, "force", undefined, "Force"},
- {defines, $D, undefined, string, "Define compiler macro"},
- {jobs, $j, "jobs", integer, JobsHelp},
- {config, $C, "config", string, "Rebar config file to use"},
- {profile, $p, "profile", undefined, "Profile this run of rebar"},
- {keep_going, $k, "keep-going", undefined,
- "Keep running after a command fails"}
- ].
-
-%%
-%% Seperate all commands (single-words) from flags (key=value) and store
-%% values into the rebar_config global storage.
-%%
-filter_flags(Config, [], Commands) ->
- {Config, lists:reverse(Commands)};
-filter_flags(Config, [Item | Rest], Commands) ->
- case string:tokens(Item, "=") of
- [Command] ->
- filter_flags(Config, Rest, [Command | Commands]);
- [KeyStr, RawValue] ->
- Key = list_to_atom(KeyStr),
- Value = case Key of
- verbose ->
- list_to_integer(RawValue);
- _ ->
- RawValue
- end,
- Config1 = rebar_config:set_global(Config, Key, Value),
- filter_flags(Config1, Rest, Commands);
- Other ->
- ?CONSOLE("Ignoring command line argument: ~p\n", [Other]),
- filter_flags(Config, Rest, Commands)
- end.
-
-command_names() ->
- [
- "check-deps",
- "clean",
- "compile",
- "create",
- "create-app",
- "create-node",
- "ct",
- "delete-deps",
- "doc",
- "eunit",
- "escriptize",
- "generate",
- "generate-appups",
- "generate-upgrade",
- "get-deps",
- "help",
- "list-deps",
- "list-templates",
- "qc",
- "update-deps",
- "overlay",
- "shell",
- "version",
- "xref"
- ].
-
-unabbreviate_command_names([]) ->
- [];
-unabbreviate_command_names([Command | Commands]) ->
- case get_command_name_candidates(Command) of
- [] ->
- %% let the rest of the code detect that the command doesn't exist
- %% (this would perhaps be a good place to fail)
- [Command | unabbreviate_command_names(Commands)];
- [FullCommand] ->
- [FullCommand | unabbreviate_command_names(Commands)];
- Candidates ->
- ?ABORT("Found more than one match for abbreviated command name "
- " '~s',~nplease be more specific. Possible candidates:~n"
- " ~s~n",
- [Command, string:join(Candidates, ", ")])
- end.
-
-get_command_name_candidates(Command) ->
- %% Get the command names which match the given (abbreviated) command name.
- %% * "c" matches commands like compile, clean and create-app
- %% * "create" matches command create only, since it's unique
- %% * "create-" matches commands starting with create-
- %% * "c-a" matches create-app
- %% * "create-a" matches create-app
- %% * "c-app" matches create-app
- Candidates = [Candidate || Candidate <- command_names(),
- is_command_name_candidate(Command, Candidate)],
- %% Is there a complete match? If so return only that, return a
- %% list of candidates otherwise
- case lists:member(Command, Candidates) of
- true -> [Command];
- false -> Candidates
- end.
-
-is_command_name_candidate(Command, Candidate) ->
- lists:prefix(Command, Candidate)
- orelse is_command_name_sub_word_candidate(Command, Candidate).
-
-is_command_name_sub_word_candidate(Command, Candidate) ->
- %% Allow for parts of commands to be abbreviated, i.e. create-app
- %% can be shortened to "create-a", "c-a" or "c-app" (but not
- %% "create-" since that would be ambiguous).
- ReOpts = [{return, list}],
- CommandSubWords = re:split(Command, "-", ReOpts),
- CandidateSubWords = re:split(Candidate, "-", ReOpts),
- is_command_name_sub_word_candidate_aux(CommandSubWords, CandidateSubWords).
-
-is_command_name_sub_word_candidate_aux([CmdSW | CmdSWs],
- [CandSW | CandSWs]) ->
- lists:prefix(CmdSW, CandSW) andalso
- is_command_name_sub_word_candidate_aux(CmdSWs, CandSWs);
-is_command_name_sub_word_candidate_aux([], []) ->
- true;
-is_command_name_sub_word_candidate_aux(_CmdSWs, _CandSWs) ->
- false.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/f84eb4fc/src/rebar/src/rebar_abnfc_compiler.erl
----------------------------------------------------------------------
diff --git a/src/rebar/src/rebar_abnfc_compiler.erl b/src/rebar/src/rebar_abnfc_compiler.erl
deleted file mode 100644
index 37731b5..0000000
--- a/src/rebar/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.
http://git-wip-us.apache.org/repos/asf/couchdb/blob/f84eb4fc/src/rebar/src/rebar_app_utils.erl
----------------------------------------------------------------------
diff --git a/src/rebar/src/rebar_app_utils.erl b/src/rebar/src/rebar_app_utils.erl
deleted file mode 100644
index 8158eb6..0000000
--- a/src/rebar/src/rebar_app_utils.erl
+++ /dev/null
@@ -1,208 +0,0 @@
-%% -*- erlang-indent-level: 4;indent-tabs-mode: nil -*-
-%% ex: ts=4 sw=4 et
-%% -------------------------------------------------------------------
-%%
-%% rebar: Erlang Build Tools
-%%
-%% Copyright (c) 2009 Dave Smith (dizzyd@dizzyd.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_app_utils).
-
--export([is_app_dir/0, is_app_dir/1,
- is_app_src/1,
- app_src_to_app/1,
- app_name/2,
- app_applications/2,
- app_vsn/2,
- is_skipped_app/2]).
-
--export([load_app_file/2]). % TEMPORARY
-
--include("rebar.hrl").
-
-%% ===================================================================
-%% Public API
-%% ===================================================================
-
-is_app_dir() ->
- is_app_dir(rebar_utils:get_cwd()).
-
-is_app_dir(Dir) ->
- SrcDir = filename:join([Dir, "src"]),
- AppSrc = filename:join([SrcDir, "*.app.src"]),
- case filelib:wildcard(AppSrc) of
- [AppSrcFile] ->
- {true, AppSrcFile};
- [] ->
- EbinDir = filename:join([Dir, "ebin"]),
- App = filename:join([EbinDir, "*.app"]),
- case filelib:wildcard(App) of
- [AppFile] ->
- {true, AppFile};
- [] ->
- false;
- _ ->
- ?ERROR("More than one .app file in ~s~n", [EbinDir]),
- false
- end;
- _ ->
- ?ERROR("More than one .app.src file in ~s~n", [SrcDir]),
- false
- end.
-
-
-is_app_src(Filename) ->
- %% If removing the extension .app.src yields a shorter name,
- %% this is an .app.src file.
- Filename =/= filename:rootname(Filename, ".app.src").
-
-app_src_to_app(Filename) ->
- filename:join("ebin", filename:basename(Filename, ".app.src") ++ ".app").
-
-app_name(Config, AppFile) ->
- case load_app_file(Config, AppFile) of
- {ok, NewConfig, AppName, _} ->
- {NewConfig, AppName};
- {error, Reason} ->
- ?ABORT("Failed to extract name from ~s: ~p\n",
- [AppFile, Reason])
- end.
-
-app_applications(Config, AppFile) ->
- case load_app_file(Config, AppFile) of
- {ok, NewConfig, _, AppInfo} ->
- {NewConfig, get_value(applications, AppInfo, AppFile)};
- {error, Reason} ->
- ?ABORT("Failed to extract applications from ~s: ~p\n",
- [AppFile, Reason])
- end.
-
-app_vsn(Config, AppFile) ->
- case load_app_file(Config, AppFile) of
- {ok, Config1, _, AppInfo} ->
- AppDir = filename:dirname(filename:dirname(AppFile)),
- rebar_utils:vcs_vsn(Config1, get_value(vsn, AppInfo, AppFile),
- AppDir);
- {error, Reason} ->
- ?ABORT("Failed to extract vsn from ~s: ~p\n",
- [AppFile, Reason])
- end.
-
-is_skipped_app(Config, AppFile) ->
- {Config1, ThisApp} = app_name(Config, AppFile),
- %% Check for apps global parameter; this is a comma-delimited list
- %% of apps on which we want to run commands
- Skipped =
- case get_apps(Config) of
- undefined ->
- %% No apps parameter specified, check the skip_apps list..
- case get_skip_apps(Config) of
- undefined ->
- %% No skip_apps list, run everything..
- false;
- SkipApps ->
- TargetApps = [list_to_atom(A) ||
- A <- string:tokens(SkipApps, ",")],
- is_skipped(ThisApp, TargetApps)
- end;
- Apps ->
- %% run only selected apps
- TargetApps = [list_to_atom(A) || A <- string:tokens(Apps, ",")],
- is_selected(ThisApp, TargetApps)
- end,
- {Config1, Skipped}.
-
-%% ===================================================================
-%% Internal functions
-%% ===================================================================
-
-load_app_file(Config, Filename) ->
- AppFile = {app_file, Filename},
- case rebar_config:get_xconf(Config, {appfile, AppFile}, undefined) of
- undefined ->
- case consult_app_file(Filename) of
- {ok, [{application, AppName, AppData}]} ->
- Config1 = rebar_config:set_xconf(Config,
- {appfile, AppFile},
- {AppName, AppData}),
- {ok, Config1, AppName, AppData};
- {error, _} = Error ->
- Error;
- Other ->
- {error, {unexpected_terms, Other}}
- end;
- {AppName, AppData} ->
- {ok, Config, AppName, AppData}
- end.
-
-%% In the case of *.app.src we want to give the user the ability to
-%% dynamically script the application resource file (think dynamic version
-%% string, etc.), in a way similar to what can be done with the rebar
-%% config. However, in the case of *.app, rebar should not manipulate
-%% that file. This enforces that dichotomy between app and app.src.
-consult_app_file(Filename) ->
- case lists:suffix(".app.src", Filename) of
- false ->
- file:consult(Filename);
- true ->
- %% TODO: EXPERIMENTAL For now let's warn the user if a
- %% script is going to be run.
- case filelib:is_regular([Filename, ".script"]) of
- true ->
- ?CONSOLE("NOTICE: Using experimental *.app.src.script "
- "functionality on ~s ~n", [Filename]);
- _ ->
- ok
- end,
- rebar_config:consult_file(Filename)
- end.
-
-get_value(Key, AppInfo, AppFile) ->
- case proplists:get_value(Key, AppInfo) of
- undefined ->
- ?ABORT("Failed to get app value '~p' from '~s'~n", [Key, AppFile]);
- Value ->
- Value
- end.
-
-%% apps= for selecting apps
-is_selected(ThisApp, TargetApps) ->
- case lists:member(ThisApp, TargetApps) of
- false ->
- {true, ThisApp};
- true ->
- false
- end.
-
-%% skip_apps= for filtering apps
-is_skipped(ThisApp, TargetApps) ->
- case lists:member(ThisApp, TargetApps) of
- false ->
- false;
- true ->
- {true, ThisApp}
- end.
-
-get_apps(Config) ->
- rebar_config:get_global(Config, apps, undefined).
-
-get_skip_apps(Config) ->
- rebar_config:get_global(Config, skip_apps, undefined).
http://git-wip-us.apache.org/repos/asf/couchdb/blob/f84eb4fc/src/rebar/src/rebar_appups.erl
----------------------------------------------------------------------
diff --git a/src/rebar/src/rebar_appups.erl b/src/rebar/src/rebar_appups.erl
deleted file mode 100644
index 722f161..0000000
--- a/src/rebar/src/rebar_appups.erl
+++ /dev/null
@@ -1,210 +0,0 @@
-%% -*- erlang-indent-level: 4;indent-tabs-mode: nil -*-
-%% ex: ts=4 sw=4 et
-%% -------------------------------------------------------------------
-%%
-%% rebar: Erlang Build Tools
-%%
-%% Copyright (c) 2011 Joe Williams (joe@joetify.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_appups).
-
--include("rebar.hrl").
-
--export(['generate-appups'/2]).
-
-%% for internal use only
--export([info/2]).
-
--define(APPUPFILEFORMAT, "%% appup generated for ~p by rebar (~p)~n"
- "{~p, [{~p, ~p}], [{~p, []}]}.~n").
-
-%% ====================================================================
-%% Public API
-%% ====================================================================
-
-'generate-appups'(Config, ReltoolFile) ->
- %% Get the old release path
- {Config1, ReltoolConfig} = rebar_rel_utils:load_config(Config, ReltoolFile),
- TargetParentDir = rebar_rel_utils:get_target_parent_dir(Config,
- ReltoolConfig),
-
- PrevRelPath = rebar_rel_utils:get_previous_release_path(Config),
- OldVerPath = filename:join([TargetParentDir, PrevRelPath]),
-
- %% Get the new and old release name and versions
- {Name, _Ver} = rebar_rel_utils:get_reltool_release_info(ReltoolConfig),
- NewVerPath = filename:join([TargetParentDir, Name]),
- {NewName, NewVer} = rebar_rel_utils:get_rel_release_info(Name, NewVerPath),
- {OldName, OldVer} = rebar_rel_utils:get_rel_release_info(Name, OldVerPath),
-
- %% Run some simple checks
- true = rebar_utils:prop_check(NewVer =/= OldVer,
- "New and old .rel versions match~n", []),
- true = rebar_utils:prop_check(
- NewName == OldName,
- "Reltool and .rel release names do not match~n", []),
-
- %% Find all the apps that have been upgraded
- {_Added, _Removed, Upgraded} = get_apps(Name, OldVerPath, NewVerPath),
-
- %% Get a list of any appup files that exist in the new release
- NewAppUpFiles = rebar_utils:find_files(
- filename:join([NewVerPath, "lib"]), "^.*.appup$"),
-
- %% Convert the list of appup files into app names
- AppUpApps = [file_to_name(File) || File <- NewAppUpFiles],
-
- %% Create a list of apps that don't already have appups
- UpgradeApps = genappup_which_apps(Upgraded, AppUpApps),
-
- %% Generate appup files for upgraded apps
- generate_appup_files(NewVerPath, OldVerPath, UpgradeApps),
-
- {ok, Config1}.
-
-%% ===================================================================
-%% Internal functions
-%% ===================================================================
-
-info(help, 'generate-appups') ->
- ?CONSOLE("Generate appup files.~n"
- "~n"
- "Valid command line options:~n"
- " previous_release=path~n",
- []).
-
-get_apps(Name, OldVerPath, NewVerPath) ->
- OldApps = rebar_rel_utils:get_rel_apps(Name, OldVerPath),
- ?DEBUG("Old Version Apps: ~p~n", [OldApps]),
-
- NewApps = rebar_rel_utils:get_rel_apps(Name, NewVerPath),
- ?DEBUG("New Version Apps: ~p~n", [NewApps]),
-
- Added = app_list_diff(NewApps, OldApps),
- ?DEBUG("Added: ~p~n", [Added]),
-
- Removed = app_list_diff(OldApps, NewApps),
- ?DEBUG("Removed: ~p~n", [Removed]),
-
- PossiblyUpgraded = proplists:get_keys(NewApps),
-
- UpgradedApps = [upgraded_app(AppName,
- proplists:get_value(AppName, OldApps),
- proplists:get_value(AppName, NewApps))
- || AppName <- PossiblyUpgraded],
-
- Upgraded = lists:dropwhile(fun(Elem) ->
- Elem == false
- end, lists:sort(UpgradedApps)),
-
- ?DEBUG("Upgraded: ~p~n", [Upgraded]),
-
- {Added, Removed, Upgraded}.
-
-upgraded_app(AppName, OldAppVer, NewAppVer) when OldAppVer /= NewAppVer ->
- {AppName, {OldAppVer, NewAppVer}};
-upgraded_app(_, _, _) ->
- false.
-
-app_list_diff(List1, List2) ->
- List3 = lists:umerge(lists:sort(proplists:get_keys(List1)),
- lists:sort(proplists:get_keys(List2))),
- List3 -- proplists:get_keys(List2).
-
-file_to_name(File) ->
- filename:rootname(filename:basename(File)).
-
-genappup_which_apps(UpgradedApps, [First|Rest]) ->
- List = proplists:delete(list_to_atom(First), UpgradedApps),
- genappup_which_apps(List, Rest);
-genappup_which_apps(Apps, []) ->
- Apps.
-
-generate_appup_files(NewVerPath, OldVerPath, [{_App, {undefined, _}}|Rest]) ->
- generate_appup_files(NewVerPath, OldVerPath, Rest);
-generate_appup_files(NewVerPath, OldVerPath, [{App, {OldVer, NewVer}}|Rest]) ->
- OldEbinDir = filename:join([OldVerPath, "lib",
- atom_to_list(App) ++ "-" ++ OldVer, "ebin"]),
- NewEbinDir = filename:join([NewVerPath, "lib",
- atom_to_list(App) ++ "-" ++ NewVer, "ebin"]),
-
- {AddedFiles, DeletedFiles, ChangedFiles} = beam_lib:cmp_dirs(NewEbinDir,
- OldEbinDir),
-
- Added = [generate_instruction(added, File) || File <- AddedFiles],
- Deleted = [generate_instruction(deleted, File) || File <- DeletedFiles],
- Changed = [generate_instruction(changed, File) || File <- ChangedFiles],
-
- Inst = lists:append([Added, Deleted, Changed]),
-
- AppUpFile = filename:join([NewEbinDir, atom_to_list(App) ++ ".appup"]),
-
- ok = file:write_file(AppUpFile,
- io_lib:fwrite(?APPUPFILEFORMAT,
- [App, rebar_utils:now_str(), NewVer,
- OldVer, Inst, OldVer])),
-
- ?CONSOLE("Generated appup for ~p~n", [App]),
- generate_appup_files(NewVerPath, OldVerPath, Rest);
-generate_appup_files(_, _, []) ->
- ?CONSOLE("Appup generation complete~n", []).
-
-generate_instruction(added, File) ->
- Name = list_to_atom(file_to_name(File)),
- {add_module, Name};
-generate_instruction(deleted, File) ->
- Name = list_to_atom(file_to_name(File)),
- {delete_module, Name};
-generate_instruction(changed, {File, _}) ->
- {ok, {Name, List}} = beam_lib:chunks(File, [attributes, exports]),
- Behavior = get_behavior(List),
- CodeChange = is_code_change(List),
- generate_instruction_advanced(Name, Behavior, CodeChange).
-
-generate_instruction_advanced(Name, undefined, undefined) ->
- %% Not a behavior or code change, assume purely functional
- {load_module, Name};
-generate_instruction_advanced(Name, [supervisor], _) ->
- %% Supervisor
- {update, Name, supervisor};
-generate_instruction_advanced(Name, _, code_change) ->
- %% Includes code_change export
- {update, Name, {advanced, []}};
-generate_instruction_advanced(Name, _, _) ->
- %% Anything else
- {load_module, Name}.
-
-get_behavior(List) ->
- Attributes = proplists:get_value(attributes, List),
- case proplists:get_value(behavior, Attributes) of
- undefined -> proplists:get_value(behaviour, Attributes);
- Else -> Else
- end.
-
-is_code_change(List) ->
- Exports = proplists:get_value(exports, List),
- case proplists:is_defined(code_change, Exports) of
- true ->
- code_change;
- false ->
- undefined
- end.