Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

501 righe
20 KiB

  1. %%%-------------------------------------------------------------------
  2. %%% @author Juan Jose Comellas <juanjo@comellas.org>
  3. %%% @copyright (C) 2009 Juan Jose Comellas
  4. %%% @doc Parses command line options with a format similar to that of GNU getopt.
  5. %%% @end
  6. %%%
  7. %%% This source file is subject to the New BSD License. You should have received
  8. %%% a copy of the New BSD license with this software. If not, it can be
  9. %%% retrieved from: http://www.opensource.org/licenses/bsd-license.php
  10. %%%-------------------------------------------------------------------
  11. -module(getopt).
  12. -author('juanjo@comellas.org').
  13. -export([parse/2, usage/2, usage/3, usage/4]).
  14. -define(TAB_LENGTH, 8).
  15. %% Indentation of the help messages in number of tabs.
  16. -define(INDENTATION, 3).
  17. %% Position of each field in the option specification tuple.
  18. -define(OPT_NAME, 1).
  19. -define(OPT_SHORT, 2).
  20. -define(OPT_LONG, 3).
  21. -define(OPT_ARG, 4).
  22. -define(OPT_HELP, 5).
  23. -define(IS_OPT_SPEC(Opt), (tuple_size(Opt) =:= ?OPT_HELP)).
  24. %% Atom indicating the data type that an argument can be converted to.
  25. -type arg_type() :: 'atom' | 'binary' | 'boolean' | 'float' | 'integer' | 'string'.
  26. %% Data type that an argument can be converted to.
  27. -type arg_value() :: atom() | binary() | boolean() | float() | integer() | string().
  28. %% Argument specification.
  29. -type arg_spec() :: arg_type() | {arg_type(), arg_value()} | undefined.
  30. %% Option type and optional default argument.
  31. -type simple_option() :: atom().
  32. -type compound_option() :: {atom(), arg_value()}.
  33. -type option() :: simple_option() | compound_option().
  34. %% Command line option specification.
  35. -type option_spec() :: {
  36. Name :: atom(),
  37. Short :: char() | undefined,
  38. Long :: string() | undefined,
  39. ArgSpec :: arg_spec(),
  40. Help :: string() | undefined
  41. }.
  42. %% @doc Parse the command line options and arguments returning a list of tuples
  43. %% and/or atoms using the Erlang convention for sending options to a
  44. %% function.
  45. -spec parse([option_spec()], string() | [string()]) ->
  46. {ok, {[option()], [string()]}} | {error, {Reason :: atom(), Data :: any()}}.
  47. parse(OptSpecList, CmdLine) ->
  48. try
  49. Args = if
  50. is_integer(hd(CmdLine)) ->
  51. string:tokens(CmdLine, " \t\n");
  52. true ->
  53. CmdLine
  54. end,
  55. parse(OptSpecList, [], [], 0, Args)
  56. catch
  57. throw: {error, {_Reason, _Data}} = Error ->
  58. Error
  59. end.
  60. -spec parse([option_spec()], [option()], [string()], integer(), [string()]) ->
  61. {ok, {[option()], [string()]}}.
  62. %% Process the option terminator.
  63. parse(OptSpecList, OptAcc, ArgAcc, _ArgPos, ["--" | Tail]) ->
  64. % Any argument present after the terminator is not considered an option.
  65. {ok, {lists:reverse(append_default_options(OptSpecList, OptAcc)), lists:reverse(ArgAcc, Tail)}};
  66. %% Process long options.
  67. parse(OptSpecList, OptAcc, ArgAcc, ArgPos, [[$-, $- | OptArg] = OptStr | Tail]) ->
  68. parse_option_long(OptSpecList, OptAcc, ArgAcc, ArgPos, Tail, OptStr, OptArg);
  69. %% Process short options.
  70. parse(OptSpecList, OptAcc, ArgAcc, ArgPos, [[$- | [_Char | _] = OptArg] = OptStr | Tail]) ->
  71. parse_option_short(OptSpecList, OptAcc, ArgAcc, ArgPos, Tail, OptStr, OptArg);
  72. %% Process non-option arguments.
  73. parse(OptSpecList, OptAcc, ArgAcc, ArgPos, [Arg | Tail]) ->
  74. case find_non_option_arg(OptSpecList, ArgPos) of
  75. {value, OptSpec} when ?IS_OPT_SPEC(OptSpec) ->
  76. parse(OptSpecList, [convert_option_arg(OptSpec, Arg) | OptAcc],
  77. ArgAcc, ArgPos + 1, Tail);
  78. false ->
  79. parse(OptSpecList, OptAcc, [Arg | ArgAcc], ArgPos, Tail)
  80. end;
  81. parse(OptSpecList, OptAcc, ArgAcc, _ArgPos, []) ->
  82. % Once we have completed gathering the options we add the ones that were
  83. % not present but had default arguments in the specification.
  84. {ok, {lists:reverse(append_default_options(OptSpecList, OptAcc)), lists:reverse(ArgAcc)}}.
  85. %% @doc Parse a long option, add it to the option accumulator and continue
  86. %% parsing the rest of the arguments recursively.
  87. %% A long option can have the following syntax:
  88. %% --foo Single option 'foo', no argument
  89. %% --foo=bar Single option 'foo', argument "bar"
  90. %% --foo bar Single option 'foo', argument "bar"
  91. -spec parse_option_long([option_spec()], [option()], [string()], integer(), [string()], string(), string()) ->
  92. {ok, {[option()], [string()]}}.
  93. parse_option_long(OptSpecList, OptAcc, ArgAcc, ArgPos, Args, OptStr, OptArg) ->
  94. case split_assigned_arg(OptArg) of
  95. {Long, Arg} ->
  96. % Get option that has its argument within the same string
  97. % separated by an equal ('=') character (e.g. "--port=1000").
  98. parse_option_assigned_arg(OptSpecList, OptAcc, ArgAcc, ArgPos, Args, OptStr, Long, Arg);
  99. Long ->
  100. case lists:keysearch(Long, ?OPT_LONG, OptSpecList) of
  101. {value, {Name, _Short, Long, undefined, _Help}} ->
  102. parse(OptSpecList, [Name | OptAcc], ArgAcc, ArgPos, Args);
  103. {value, {_Name, _Short, Long, _ArgSpec, _Help} = OptSpec} ->
  104. % The option argument string is empty, but the option requires
  105. % an argument, so we look into the next string in the list.
  106. parse_option_next_arg(OptSpecList, OptAcc, ArgAcc, ArgPos, Args, OptSpec);
  107. false ->
  108. throw({error, {invalid_option, OptStr}})
  109. end
  110. end.
  111. %% @doc Parse an option where the argument is 'assigned' in the same string using
  112. %% the '=' character, add it to the option accumulator and continue parsing the
  113. %% rest of the arguments recursively. This syntax is only valid for long options.
  114. -spec parse_option_assigned_arg([option_spec()], [option()], [string()], integer(),
  115. [string()], string(), string(), string()) ->
  116. {ok, {[option()], [string()]}}.
  117. parse_option_assigned_arg(OptSpecList, OptAcc, ArgAcc, ArgPos, Args, OptStr, Long, Arg) ->
  118. case lists:keysearch(Long, ?OPT_LONG, OptSpecList) of
  119. {value, {_Name, _Short, Long, ArgSpec, _Help} = OptSpec} ->
  120. case ArgSpec of
  121. undefined ->
  122. throw({error, {invalid_option_arg, OptStr}});
  123. _ ->
  124. parse(OptSpecList, [convert_option_arg(OptSpec, Arg) | OptAcc], ArgAcc, ArgPos, Args)
  125. end;
  126. false ->
  127. throw({error, {invalid_option, OptStr}})
  128. end.
  129. %% @doc Split an option string that may contain an option with its argument
  130. %% separated by an equal ('=') character (e.g. "port=1000").
  131. -spec split_assigned_arg(string()) -> {Name :: string(), Arg :: string()} | string().
  132. split_assigned_arg(OptStr) ->
  133. split_assigned_arg(OptStr, OptStr, []).
  134. split_assigned_arg(_OptStr, [$= | Tail], Acc) ->
  135. {lists:reverse(Acc), Tail};
  136. split_assigned_arg(OptStr, [Char | Tail], Acc) ->
  137. split_assigned_arg(OptStr, Tail, [Char | Acc]);
  138. split_assigned_arg(OptStr, [], _Acc) ->
  139. OptStr.
  140. %% @doc Parse a short option, add it to the option accumulator and continue
  141. %% parsing the rest of the arguments recursively.
  142. %% A short option can have the following syntax:
  143. %% -a Single option 'a', no argument or implicit boolean argument
  144. %% -a foo Single option 'a', argument "foo"
  145. %% -afoo Single option 'a', argument "foo"
  146. %% -abc Multiple options: 'a'; 'b'; 'c'
  147. %% -bcafoo Multiple options: 'b'; 'c'; 'a' with argument "foo"
  148. -spec parse_option_short([option_spec()], [option()], [string()], integer(), [string()], string(), string()) ->
  149. {ok, {[option()], [string()]}}.
  150. parse_option_short(OptSpecList, OptAcc, ArgAcc, ArgPos, Args, OptStr, [Short | Arg]) ->
  151. case lists:keysearch(Short, ?OPT_SHORT, OptSpecList) of
  152. {value, {Name, Short, _Long, undefined, _Help}} ->
  153. parse_option_short(OptSpecList, [Name | OptAcc], ArgAcc, ArgPos, Args, OptStr, Arg);
  154. {value, {_Name, Short, _Long, ArgSpec, _Help} = OptSpec} ->
  155. case Arg of
  156. [] ->
  157. % The option argument string is empty, but the option requires
  158. % an argument, so we look into the next string in the list.
  159. parse_option_next_arg(OptSpecList, OptAcc, ArgAcc, ArgPos, Args, OptSpec);
  160. _ ->
  161. case is_valid_arg(ArgSpec, Arg) of
  162. true ->
  163. parse(OptSpecList, [convert_option_arg(OptSpec, Arg) | OptAcc], ArgAcc, ArgPos, Args);
  164. _ ->
  165. parse_option_short(OptSpecList, [convert_option_no_arg(OptSpec) | OptAcc], ArgAcc, ArgPos, Args, OptStr, Arg)
  166. end
  167. end;
  168. false ->
  169. throw({error, {invalid_option, OptStr}})
  170. end;
  171. parse_option_short(OptSpecList, OptAcc, ArgAcc, ArgPos, Args, _OptStr, []) ->
  172. parse(OptSpecList, OptAcc, ArgAcc, ArgPos, Args).
  173. %% @doc Retrieve the argument for an option from the next string in the list of
  174. %% command-line parameters.
  175. parse_option_next_arg(OptSpecList, OptAcc, ArgAcc, ArgPos, [Arg | Tail] = Args, {Name, _Short, _Long, ArgSpec, _Help} = OptSpec) ->
  176. % Special case for booleans: when the next string is an option we assume
  177. % the value is 'true'.
  178. case (arg_spec_type(ArgSpec) =:= boolean) andalso not is_boolean_arg(Arg) of
  179. true ->
  180. parse(OptSpecList, [{Name, true} | OptAcc], ArgAcc, ArgPos, Args);
  181. _ ->
  182. parse(OptSpecList, [convert_option_arg(OptSpec, Arg) | OptAcc], ArgAcc, ArgPos, Tail)
  183. end;
  184. parse_option_next_arg(OptSpecList, OptAcc, ArgAcc, ArgPos, [] = Args, {Name, _Short, _Long, ArgSpec, _Help}) ->
  185. % Special case for booleans: when the next string is missing we assume the
  186. % value is 'true'.
  187. case arg_spec_type(ArgSpec) of
  188. boolean ->
  189. parse(OptSpecList, [{Name, true} | OptAcc], ArgAcc, ArgPos, Args);
  190. _ ->
  191. throw({error, {missing_option_arg, Name}})
  192. end.
  193. %% @doc Find the option for the discrete argument in position specified in the
  194. %% Pos argument.
  195. -spec find_non_option_arg([option_spec()], integer()) -> {value, option_spec()} | false.
  196. find_non_option_arg([{_Name, undefined, undefined, _ArgSpec, _Help} = OptSpec | _Tail], 0) ->
  197. {value, OptSpec};
  198. find_non_option_arg([{_Name, undefined, undefined, _ArgSpec, _Help} | Tail], Pos) ->
  199. find_non_option_arg(Tail, Pos - 1);
  200. find_non_option_arg([_Head | Tail], Pos) ->
  201. find_non_option_arg(Tail, Pos);
  202. find_non_option_arg([], _Pos) ->
  203. false.
  204. %% @doc Append options that were not present in the command line arguments with
  205. %% their default arguments.
  206. -spec append_default_options([option_spec()], [option()]) -> [option()].
  207. append_default_options([{Name, _Short, _Long, {_Type, DefaultArg}, _Help} | Tail], OptAcc) ->
  208. append_default_options(Tail,
  209. case lists:keymember(Name, 1, OptAcc) of
  210. false ->
  211. [{Name, DefaultArg} | OptAcc];
  212. _ ->
  213. OptAcc
  214. end);
  215. %% For options with no default argument.
  216. append_default_options([_Head | Tail], OptAcc) ->
  217. append_default_options(Tail, OptAcc);
  218. append_default_options([], OptAcc) ->
  219. OptAcc.
  220. -spec convert_option_no_arg(option_spec()) -> compound_option().
  221. convert_option_no_arg({Name, _Short, _Long, ArgSpec, _Help}) ->
  222. case ArgSpec of
  223. % Special case for booleans: if there is no argument we assume
  224. % the value is 'true'.
  225. {boolean, _DefaultValue} ->
  226. {Name, true};
  227. boolean ->
  228. {Name, true};
  229. _ ->
  230. throw({error, {missing_option_arg, Name}})
  231. end.
  232. %% @doc Convert the argument passed in the command line to the data type
  233. %% indicated by the argument specification.
  234. -spec convert_option_arg(option_spec(), string()) -> compound_option().
  235. convert_option_arg({Name, _Short, _Long, ArgSpec, _Help}, Arg) ->
  236. try
  237. {Name, to_type(arg_spec_type(ArgSpec), Arg)}
  238. catch
  239. error:_ ->
  240. throw({error, {invalid_option_arg, {Name, Arg}}})
  241. end.
  242. %% @doc Retrieve the data type form an argument specification.
  243. -spec arg_spec_type(arg_spec()) -> arg_type() | undefined.
  244. arg_spec_type({Type, _DefaultArg}) ->
  245. Type;
  246. arg_spec_type(Type) when is_atom(Type) ->
  247. Type.
  248. %% @doc Convert an argument string to its corresponding data type.
  249. -spec to_type(arg_type(), string()) -> arg_value().
  250. to_type(binary, Arg) ->
  251. list_to_binary(Arg);
  252. to_type(atom, Arg) ->
  253. list_to_atom(Arg);
  254. to_type(integer, Arg) ->
  255. list_to_integer(Arg);
  256. to_type(float, Arg) ->
  257. list_to_float(Arg);
  258. to_type(boolean, Arg) ->
  259. LowerArg = string:to_lower(Arg),
  260. case is_arg_true(LowerArg) of
  261. true ->
  262. true;
  263. _ ->
  264. case is_arg_false(LowerArg) of
  265. true ->
  266. false;
  267. false ->
  268. erlang:error(badarg)
  269. end
  270. end;
  271. to_type(_Type, Arg) ->
  272. Arg.
  273. -spec is_arg_true(string()) -> boolean().
  274. is_arg_true(Arg) ->
  275. (Arg =:= "true") orelse (Arg =:= "t") orelse
  276. (Arg =:= "yes") orelse (Arg =:= "y") orelse
  277. (Arg =:= "on") orelse (Arg =:= "enabled") orelse
  278. (Arg =:= "1").
  279. -spec is_arg_false(string()) -> boolean().
  280. is_arg_false(Arg) ->
  281. (Arg =:= "false") orelse (Arg =:= "f") orelse
  282. (Arg =:= "no") orelse (Arg =:= "n") orelse
  283. (Arg =:= "off") orelse (Arg =:= "disabled") orelse
  284. (Arg =:= "0").
  285. -spec is_valid_arg(arg_spec(), nonempty_string()) -> boolean().
  286. is_valid_arg({Type, _DefaultArg}, Arg) ->
  287. is_valid_arg(Type, Arg);
  288. is_valid_arg(boolean, Arg) ->
  289. is_boolean_arg(Arg);
  290. is_valid_arg(integer, Arg) ->
  291. is_integer_arg(Arg);
  292. is_valid_arg(float, Arg) ->
  293. is_float_arg(Arg);
  294. is_valid_arg(_Type, _Arg) ->
  295. true.
  296. -spec is_boolean_arg(string()) -> boolean().
  297. is_boolean_arg(Arg) ->
  298. LowerArg = string:to_lower(Arg),
  299. is_arg_true(LowerArg) orelse is_arg_false(LowerArg).
  300. -spec is_integer_arg(string()) -> boolean().
  301. is_integer_arg([Head | Tail]) when Head >= $0, Head =< $9 ->
  302. is_integer_arg(Tail);
  303. is_integer_arg([_Head | _Tail]) ->
  304. false;
  305. is_integer_arg([]) ->
  306. true.
  307. -spec is_float_arg(string()) -> boolean().
  308. is_float_arg([Head | Tail]) when (Head >= $0 andalso Head =< $9) orelse Head =:= $. ->
  309. is_float_arg(Tail);
  310. is_float_arg([_Head | _Tail]) ->
  311. false;
  312. is_float_arg([]) ->
  313. true.
  314. %% @doc Show a message on stdout indicating the command line options and
  315. %% arguments that are supported by the program.
  316. -spec usage([option_spec()], string()) -> ok.
  317. usage(OptSpecList, ProgramName) ->
  318. io:format("Usage: ~s~s~n~n~s~n",
  319. [ProgramName, usage_cmd_line(OptSpecList), usage_options(OptSpecList)]).
  320. %% @doc Show a message on stdout indicating the command line options and
  321. %% arguments that are supported by the program. The CmdLineTail argument
  322. %% is a string that is added to the end of the usage command line.
  323. -spec usage([option_spec()], string(), string()) -> ok.
  324. usage(OptSpecList, ProgramName, CmdLineTail) ->
  325. io:format("Usage: ~s~s ~s~n~n~s~n",
  326. [ProgramName, usage_cmd_line(OptSpecList), CmdLineTail, usage_options(OptSpecList)]).
  327. %% @doc Show a message on stdout indicating the command line options and
  328. %% arguments that are supported by the program. The CmdLineTail and OptionsTail
  329. %% arguments are a string that is added to the end of the usage command line
  330. %% and a list of tuples that are added to the end of the options' help lines.
  331. -spec usage([option_spec()], string(), string(), [{string(), string()}]) -> ok.
  332. usage(OptSpecList, ProgramName, CmdLineTail, OptionsTail) ->
  333. UsageOptions = lists:foldl(
  334. fun ({Prefix, Help}, Acc) ->
  335. add_option_help(Prefix, Help, Acc)
  336. end, usage_options_reverse(OptSpecList, []), OptionsTail),
  337. io:format("Usage: ~s~s ~s~n~n~s~n",
  338. [ProgramName, usage_cmd_line(OptSpecList), CmdLineTail,
  339. lists:flatten(lists:reverse(UsageOptions))]).
  340. %% @doc Return a string with the syntax for the command line options and
  341. %% arguments.
  342. -spec usage_cmd_line([option_spec()]) -> string().
  343. usage_cmd_line(OptSpecList) ->
  344. usage_cmd_line(OptSpecList, []).
  345. usage_cmd_line([{Name, Short, Long, ArgSpec, _Help} | Tail], Acc) ->
  346. CmdLine =
  347. case ArgSpec of
  348. undefined ->
  349. if
  350. % For options with short form and no argument.
  351. Short =/= undefined ->
  352. [$\s, $[, $-, Short, $]];
  353. % For options with only long form and no argument.
  354. Long =/= undefined ->
  355. [$\s, $[, $-, $-, Long, $]];
  356. true ->
  357. []
  358. end;
  359. _ ->
  360. if
  361. % For options with short form and argument.
  362. Short =/= undefined ->
  363. [$\s, $[, $-, Short, $\s, $<, atom_to_list(Name), $>, $]];
  364. % For options with only long form and argument.
  365. Long =/= undefined ->
  366. [$\s, $[, $-, $-, Long, $\s, $<, atom_to_list(Name), $>, $]];
  367. % For options with neither short nor long form and argument.
  368. true ->
  369. [$\s, $<, atom_to_list(Name), $>]
  370. end
  371. end,
  372. usage_cmd_line(Tail, [CmdLine | Acc]);
  373. usage_cmd_line([], Acc) ->
  374. lists:flatten(lists:reverse(Acc)).
  375. %% @doc Return a string with the help message for each of the options and
  376. %% arguments.
  377. -spec usage_options([option_spec()]) -> string().
  378. usage_options(OptSpecList) ->
  379. lists:flatten(lists:reverse(usage_options_reverse(OptSpecList, []))).
  380. usage_options_reverse([{Name, Short, Long, _ArgSpec, Help} | Tail], Acc) ->
  381. Prefix =
  382. case Long of
  383. undefined ->
  384. case Short of
  385. % Neither short nor long form (non-option argument).
  386. undefined ->
  387. [$<, atom_to_list(Name), $>];
  388. % Only short form.
  389. _ ->
  390. [$-, Short]
  391. end;
  392. _ ->
  393. case Short of
  394. % Only long form.
  395. undefined ->
  396. [$-, $- | Long];
  397. % Both short and long form.
  398. _ ->
  399. [$-, Short, $,, $\s, $-, $- | Long]
  400. end
  401. end,
  402. usage_options_reverse(Tail, add_option_help(Prefix, Help, Acc));
  403. usage_options_reverse([], Acc) ->
  404. Acc.
  405. %% @doc Add the help message corresponding to an option specification to a list
  406. %% with the correct indentation.
  407. -spec add_option_help(Prefix :: string(), Help :: string(), Acc :: string()) -> string().
  408. add_option_help(Prefix, Help, Acc) when is_list(Help), Help =/= [] ->
  409. FlatPrefix = lists:flatten(Prefix),
  410. case ((?INDENTATION * ?TAB_LENGTH) - 2 - length(FlatPrefix)) of
  411. TabSize when TabSize > 0 ->
  412. Tab = lists:duplicate(ceiling(TabSize / ?TAB_LENGTH), $\t),
  413. [[$\s, $\s, FlatPrefix, Tab, Help, $\n] | Acc];
  414. _ ->
  415. % The indentation for the option description is 3 tabs (i.e. 24 characters)
  416. % IMPORTANT: Change the number of tabs below if you change the
  417. % value of the INDENTATION macro.
  418. [[$\t, $\t, $\t, Help, $\n], [$\s, $\s, FlatPrefix, $\n] | Acc]
  419. end;
  420. add_option_help(_Opt, _Prefix, Acc) ->
  421. Acc.
  422. %% @doc Return the smallest integral value not less than the argument.
  423. -spec ceiling(float()) -> integer().
  424. ceiling(X) ->
  425. T = erlang:trunc(X),
  426. case (X - T) of
  427. % Neg when Neg < 0 ->
  428. % T;
  429. Pos when Pos > 0 ->
  430. T + 1;
  431. _ ->
  432. T
  433. end.