Special case for boolean arguments to consider them enabled when the argument is missing.

This commit is contained in:
Juan Jose Comellas 2009-12-31 10:39:35 -03:00
parent 400a7b7cf9
commit 2a42bd761c

View File

@ -11,7 +11,7 @@
-module(getopt). -module(getopt).
-author('juanjo@comellas.org'). -author('juanjo@comellas.org').
-export([parse/2, usage/2, is_option/1]). -export([parse/2, usage/2]).
-define(TAB_LENGTH, 8). -define(TAB_LENGTH, 8).
@ -132,7 +132,7 @@ get_option(OptSpecList, OptStr, FieldPos, OptName, Tail) ->
ArgSpecType = arg_spec_type(ArgSpec), ArgSpecType = arg_spec_type(ArgSpec),
case Tail of case Tail of
[Arg | Tail1] -> [Arg | Tail1] ->
case (ArgSpecType =:= boolean) andalso is_option(Arg) of case (ArgSpecType =:= boolean) andalso not is_boolean_arg(Arg) of
%% Special case for booleans: when the next string %% Special case for booleans: when the next string
%% is an option we assume the value is 'true'. %% is an option we assume the value is 'true'.
true -> true ->
@ -238,9 +238,9 @@ append_default_args([], OptAcc) ->
OptAcc. OptAcc.
-spec is_option(string()) -> boolean(). %% -spec is_option(string()) -> boolean().
is_option([Char | _Tail] = OptStr) -> %% is_option([Char | _Tail] = OptStr) ->
(Char =:= $-) orelse lists:member($=, OptStr). %% (Char =:= $-) orelse lists:member($=, OptStr).
-spec convert_option_arg(option_spec(), string()) -> [option()]. -spec convert_option_arg(option_spec(), string()) -> [option()].
@ -272,13 +272,18 @@ to_type(integer, Arg) ->
to_type(float, Arg) -> to_type(float, Arg) ->
list_to_float(Arg); list_to_float(Arg);
to_type(boolean, Arg) -> to_type(boolean, Arg) ->
is_boolean_arg(Arg);
to_type(_Type, Arg) ->
Arg.
-spec is_boolean_arg(string()) -> boolean().
is_boolean_arg(Arg) ->
LowerArg = string:to_lower(Arg), LowerArg = string:to_lower(Arg),
(LowerArg =:= "true") orelse (LowerArg =:= "t") orelse (LowerArg =:= "true") orelse (LowerArg =:= "t") orelse
(LowerArg =:= "yes") orelse (LowerArg =:= "y") orelse (LowerArg =:= "yes") orelse (LowerArg =:= "y") orelse
(LowerArg =:= "on") orelse (LowerArg =:= "enabled") orelse (LowerArg =:= "on") orelse (LowerArg =:= "enabled") orelse
(LowerArg =:= "1"); (LowerArg =:= "1").
to_type(_Type, Arg) ->
Arg.
-spec usage([option_spec()], string()) -> ok. -spec usage([option_spec()], string()) -> ok.