/std/getopt.d

http://github.com/jcd/phobos · D · 874 lines · 420 code · 44 blank · 410 comment · 127 complexity · 45b6688467d9a8e35065a6a2b7230d71 MD5 · raw file

  1. // Written in the D programming language.
  2. /**
  3. Processing of command line options.
  4. The getopt module implements a $(D getopt) function, which adheres to
  5. the POSIX syntax for command line options. GNU extensions are
  6. supported in the form of long options introduced by a double dash
  7. ("--"). Support for bundling of command line options, as was the case
  8. with the more traditional single-letter approach, is provided but not
  9. enabled by default.
  10. Macros:
  11. WIKI = Phobos/StdGetopt
  12. Copyright: Copyright Andrei Alexandrescu 2008 - 2009.
  13. License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>.
  14. Authors: $(WEB erdani.org, Andrei Alexandrescu)
  15. Credits: This module and its documentation are inspired by Perl's $(WEB
  16. perldoc.perl.org/Getopt/Long.html, Getopt::Long) module. The syntax of
  17. D's $(D getopt) is simpler than its Perl counterpart because $(D
  18. getopt) infers the expected parameter types from the static types of
  19. the passed-in pointers.
  20. Source: $(PHOBOSSRC std/_getopt.d)
  21. */
  22. /*
  23. Copyright Andrei Alexandrescu 2008 - 2009.
  24. Distributed under the Boost Software License, Version 1.0.
  25. (See accompanying file LICENSE_1_0.txt or copy at
  26. http://www.boost.org/LICENSE_1_0.txt)
  27. */
  28. module std.getopt;
  29. private import std.array, std.string, std.conv, std.traits, std.bitmanip,
  30. std.algorithm, std.ascii, std.exception;
  31. version (unittest)
  32. {
  33. import std.stdio; // for testing only
  34. }
  35. /**
  36. Synopsis:
  37. ---------
  38. import std.getopt;
  39. string data = "file.dat";
  40. int length = 24;
  41. bool verbose;
  42. enum Color { no, yes };
  43. Color color;
  44. void main(string[] args)
  45. {
  46. getopt(
  47. args,
  48. "length", &length, // numeric
  49. "file", &data, // string
  50. "verbose", &verbose, // flag
  51. "color", &color); // enum
  52. ...
  53. }
  54. ---------
  55. The $(D getopt) function takes a reference to the command line
  56. (as received by $(D main)) as its first argument, and an
  57. unbounded number of pairs of strings and pointers. Each string is an
  58. option meant to "fill" the value pointed-to by the pointer to its
  59. right (the "bound" pointer). The option string in the call to
  60. $(D getopt) should not start with a dash.
  61. In all cases, the command-line options that were parsed and used by
  62. $(D getopt) are removed from $(D args). Whatever in the
  63. arguments did not look like an option is left in $(D args) for
  64. further processing by the program. Values that were unaffected by the
  65. options are not touched, so a common idiom is to initialize options
  66. to their defaults and then invoke $(D getopt). If a
  67. command-line argument is recognized as an option with a parameter and
  68. the parameter cannot be parsed properly (e.g. a number is expected
  69. but not present), a $(D Exception) exception is thrown.
  70. Depending on the type of the pointer being bound, $(D getopt)
  71. recognizes the following kinds of options:
  72. $(OL $(LI $(I Boolean options). A lone argument sets the option to $(D true).
  73. Additionally $(B true) or $(B false) can be set within the option separated with
  74. an "=" sign:
  75. ---------
  76. bool verbose = false, debugging = true;
  77. getopt(args, "verbose", &verbose, "debug", &debugging);
  78. ---------
  79. To set $(D verbose) to $(D true), invoke the program with either $(D
  80. --verbose) or $(D --verbose=true).
  81. To set $(D debugging) to $(D false), invoke the program with $(D --debugging=false).
  82. )$(LI $(I Numeric options.) If an option is bound to a numeric type, a
  83. number is expected as the next option, or right within the option
  84. separated with an "=" sign:
  85. ---------
  86. uint timeout;
  87. getopt(args, "timeout", &timeout);
  88. ---------
  89. To set $(D timeout) to $(D 5), invoke the program with either $(D
  90. --timeout=5) or $(D --timeout 5).
  91. $(UL $(LI $(I Incremental options.) If an option name has a "+" suffix and
  92. is bound to a numeric type, then the option's value tracks the number
  93. of times the option occurred on the command line:
  94. ---------
  95. uint paranoid;
  96. getopt(args, "paranoid+", &paranoid);
  97. ---------
  98. Invoking the program with "--paranoid --paranoid --paranoid" will set
  99. $(D paranoid) to 3. Note that an incremental option never
  100. expects a parameter, e.g. in the command line "--paranoid 42
  101. --paranoid", the "42" does not set $(D paranoid) to 42;
  102. instead, $(D paranoid) is set to 2 and "42" is not considered
  103. as part of the normal program arguments.)))
  104. $(LI $(I Enum options.) If an option is bound to an enum, an enum symbol as a
  105. string is expected as the next option, or right within the option separated
  106. with an "=" sign:
  107. ---------
  108. enum Color { no, yes };
  109. Color color; // default initialized to Color.no
  110. getopt(args, "color", &color);
  111. ---------
  112. To set $(D color) to $(D Color.yes), invoke the program with either $(D
  113. --color=yes) or $(D --color yes).)
  114. $(LI $(I String options.) If an option is bound to a string, a string
  115. is expected as the next option, or right within the option separated
  116. with an "=" sign:
  117. ---------
  118. string outputFile;
  119. getopt(args, "output", &outputFile);
  120. ---------
  121. Invoking the program with "--output=myfile.txt" or "--output
  122. myfile.txt" will set $(D outputFile) to "myfile.txt". If you want to
  123. pass a string containing spaces, you need to use the quoting that is
  124. appropriate to your shell, e.g. --output='my file.txt'.)
  125. $(LI $(I Array options.) If an option is bound to an array, a new
  126. element is appended to the array each time the option occurs:
  127. ---------
  128. string[] outputFiles;
  129. getopt(args, "output", &outputFiles);
  130. ---------
  131. Invoking the program with "--output=myfile.txt --output=yourfile.txt"
  132. or "--output myfile.txt --output yourfile.txt" will set $(D
  133. outputFiles) to [ "myfile.txt", "yourfile.txt" ] .)
  134. $(LI $(I Hash options.) If an option is bound to an associative
  135. array, a string of the form "name=value" is expected as the next
  136. option, or right within the option separated with an "=" sign:
  137. ---------
  138. double[string] tuningParms;
  139. getopt(args, "tune", &tuningParms);
  140. ---------
  141. Invoking the program with e.g. "--tune=alpha=0.5 --tune beta=0.6" will
  142. set $(D tuningParms) to [ "alpha" : 0.5, "beta" : 0.6 ]. In general,
  143. keys and values can be of any parsable types.)
  144. $(LI $(I Callback options.) An option can be bound to a function or
  145. delegate with the signature $(D void function()), $(D void function(string option)),
  146. $(D void function(string option, string value)), or their delegate equivalents.
  147. $(UL $(LI If the callback doesn't take any arguments, the callback is invoked
  148. whenever the option is seen.) $(LI If the callback takes one string argument,
  149. the option string (without the leading dash(es)) is passed to the callback.
  150. After that, the option string is considered handled and removed from the
  151. options array.
  152. ---------
  153. void main(string[] args)
  154. {
  155. uint verbosityLevel = 1;
  156. void myHandler(string option)
  157. {
  158. if (option == "quiet")
  159. {
  160. verbosityLevel = 0;
  161. }
  162. else
  163. {
  164. assert(option == "verbose");
  165. verbosityLevel = 2;
  166. }
  167. }
  168. getopt(args, "verbose", &myHandler, "quiet", &myHandler);
  169. }
  170. ---------
  171. )$(LI If the callback takes two string arguments, the
  172. option string is handled as an option with one argument, and parsed
  173. accordingly. The option and its value are passed to the
  174. callback. After that, whatever was passed to the callback is
  175. considered handled and removed from the list.
  176. ---------
  177. void main(string[] args)
  178. {
  179. uint verbosityLevel = 1;
  180. void myHandler(string option, string value)
  181. {
  182. switch (value)
  183. {
  184. case "quiet": verbosityLevel = 0; break;
  185. case "verbose": verbosityLevel = 2; break;
  186. case "shouting": verbosityLevel = verbosityLevel.max; break;
  187. default :
  188. stderr.writeln("Dunno how verbose you want me to be by saying ",
  189. value);
  190. exit(1);
  191. }
  192. }
  193. getopt(args, "verbosity", &myHandler);
  194. }
  195. ---------
  196. ))))
  197. $(B Options with multiple names)
  198. Sometimes option synonyms are desirable, e.g. "--verbose",
  199. "--loquacious", and "--garrulous" should have the same effect. Such
  200. alternate option names can be included in the option specification,
  201. using "|" as a separator:
  202. ---------
  203. bool verbose;
  204. getopt(args, "verbose|loquacious|garrulous", &verbose);
  205. ---------
  206. $(B Case)
  207. By default options are case-insensitive. You can change that behavior
  208. by passing $(D getopt) the $(D caseSensitive) directive like this:
  209. ---------
  210. bool foo, bar;
  211. getopt(args,
  212. std.getopt.config.caseSensitive,
  213. "foo", &foo,
  214. "bar", &bar);
  215. ---------
  216. In the example above, "--foo", "--bar", "--FOo", "--bAr" etc. are recognized.
  217. The directive is active til the end of $(D getopt), or until the
  218. converse directive $(D caseInsensitive) is encountered:
  219. ---------
  220. bool foo, bar;
  221. getopt(args,
  222. std.getopt.config.caseSensitive,
  223. "foo", &foo,
  224. std.getopt.config.caseInsensitive,
  225. "bar", &bar);
  226. ---------
  227. The option "--Foo" is rejected due to $(D
  228. std.getopt.config.caseSensitive), but not "--Bar", "--bAr"
  229. etc. because the directive $(D
  230. std.getopt.config.caseInsensitive) turned sensitivity off before
  231. option "bar" was parsed.
  232. $(B "Short" versus "long" options)
  233. Traditionally, programs accepted single-letter options preceded by
  234. only one dash (e.g. $(D -t)). $(D getopt) accepts such parameters
  235. seamlessly. When used with a double-dash (e.g. $(D --t)), a
  236. single-letter option behaves the same as a multi-letter option. When
  237. used with a single dash, a single-letter option is accepted. If the
  238. option has a parameter, that must be "stuck" to the option without
  239. any intervening space or "=":
  240. ---------
  241. uint timeout;
  242. getopt(args, "timeout|t", &timeout);
  243. ---------
  244. To set $(D timeout) to $(D 5), use either of the following: $(D --timeout=5),
  245. $(D --timeout 5), $(D --t=5), $(D --t 5), or $(D -t5). Forms such as $(D -t 5)
  246. and $(D -timeout=5) will be not accepted.
  247. For more details about short options, refer also to the next section.
  248. $(B Bundling)
  249. Single-letter options can be bundled together, i.e. "-abc" is the same as
  250. $(D "-a -b -c"). By default, this confusing option is turned off. You can
  251. turn it on with the $(D std.getopt.config.bundling) directive:
  252. ---------
  253. bool foo, bar;
  254. getopt(args,
  255. std.getopt.config.bundling,
  256. "foo|f", &foo,
  257. "bar|b", &bar);
  258. ---------
  259. In case you want to only enable bundling for some of the parameters,
  260. bundling can be turned off with $(D std.getopt.config.noBundling).
  261. $(B Passing unrecognized options through)
  262. If an application needs to do its own processing of whichever arguments
  263. $(D getopt) did not understand, it can pass the
  264. $(D std.getopt.config.passThrough) directive to $(D getopt):
  265. ---------
  266. bool foo, bar;
  267. getopt(args,
  268. std.getopt.config.passThrough,
  269. "foo", &foo,
  270. "bar", &bar);
  271. ---------
  272. An unrecognized option such as "--baz" will be found untouched in
  273. $(D args) after $(D getopt) returns.
  274. $(B Options Terminator)
  275. A lonesome double-dash terminates $(D getopt) gathering. It is used to
  276. separate program options from other parameters (e.g. options to be passed
  277. to another program). Invoking the example above with $(D "--foo -- --bar")
  278. parses foo but leaves "--bar" in $(D args). The double-dash itself is
  279. removed from the argument array.
  280. */
  281. void getopt(T...)(ref string[] args, T opts) {
  282. enforce(args.length,
  283. "Invalid arguments string passed: program name missing");
  284. configuration cfg;
  285. return getoptImpl(args, cfg, opts);
  286. }
  287. /**
  288. * Configuration options for $(D getopt). You can pass them to $(D
  289. * getopt) in any position, except in between an option string and its
  290. * bound pointer.
  291. */
  292. enum config {
  293. /// Turns case sensitivity on
  294. caseSensitive,
  295. /// Turns case sensitivity off
  296. caseInsensitive,
  297. /// Turns bundling on
  298. bundling,
  299. /// Turns bundling off
  300. noBundling,
  301. /// Pass unrecognized arguments through
  302. passThrough,
  303. /// Signal unrecognized arguments as errors
  304. noPassThrough,
  305. /// Stop at first argument that does not look like an option
  306. stopOnFirstNonOption,
  307. }
  308. private void getoptImpl(T...)(ref string[] args,
  309. ref configuration cfg, T opts)
  310. {
  311. static if (opts.length)
  312. {
  313. static if (is(typeof(opts[0]) : config))
  314. {
  315. // it's a configuration flag, act on it
  316. setConfig(cfg, opts[0]);
  317. return getoptImpl(args, cfg, opts[1 .. $]);
  318. }
  319. else
  320. {
  321. // it's an option string
  322. auto option = to!string(opts[0]);
  323. auto receiver = opts[1];
  324. bool incremental;
  325. // Handle options of the form --blah+
  326. if (option.length && option[$ - 1] == autoIncrementChar)
  327. {
  328. option = option[0 .. $ - 1];
  329. incremental = true;
  330. }
  331. handleOption(option, receiver, args, cfg, incremental);
  332. return getoptImpl(args, cfg, opts[2 .. $]);
  333. }
  334. }
  335. else
  336. {
  337. // no more options to look for, potentially some arguments left
  338. foreach (i, a ; args[1 .. $]) {
  339. if (!a.length || a[0] != optionChar)
  340. {
  341. // not an option
  342. if (cfg.stopOnFirstNonOption) break;
  343. continue;
  344. }
  345. if (endOfOptions.length && a == endOfOptions)
  346. {
  347. // Consume the "--"
  348. args = args.remove(i + 1);
  349. break;
  350. }
  351. if (!cfg.passThrough)
  352. {
  353. throw new Exception("Unrecognized option "~a);
  354. }
  355. }
  356. }
  357. }
  358. void handleOption(R)(string option, R receiver, ref string[] args,
  359. ref configuration cfg, bool incremental)
  360. {
  361. // Scan arguments looking for a match for this option
  362. for (size_t i = 1; i < args.length; ) {
  363. auto a = args[i];
  364. if (endOfOptions.length && a == endOfOptions) break;
  365. if (cfg.stopOnFirstNonOption && (!a.length || a[0] != optionChar))
  366. {
  367. // first non-option is end of options
  368. break;
  369. }
  370. // Unbundle bundled arguments if necessary
  371. if (cfg.bundling && a.length > 2 && a[0] == optionChar &&
  372. a[1] != optionChar)
  373. {
  374. string[] expanded;
  375. foreach (j, dchar c; a[1 .. $])
  376. {
  377. // If the character is not alpha, stop right there. This allows
  378. // e.g. -j100 to work as "pass argument 100 to option -j".
  379. if (!isAlpha(c))
  380. {
  381. expanded ~= a[j + 1 .. $];
  382. break;
  383. }
  384. expanded ~= text(optionChar, c);
  385. }
  386. args = args[0 .. i] ~ expanded ~ args[i + 1 .. $];
  387. continue;
  388. }
  389. string val;
  390. if (!optMatch(a, option, val, cfg))
  391. {
  392. ++i;
  393. continue;
  394. }
  395. // found it
  396. // from here on, commit to eat args[i]
  397. // (and potentially args[i + 1] too, but that comes later)
  398. args = args[0 .. i] ~ args[i + 1 .. $];
  399. static if (is(typeof(*receiver) == bool))
  400. {
  401. // parse '--b=true/false'
  402. if (val.length)
  403. {
  404. *receiver = parse!(typeof(*receiver))(val);
  405. break;
  406. }
  407. // no argument means set it to true
  408. *receiver = true;
  409. break;
  410. }
  411. else
  412. {
  413. // non-boolean option, which might include an argument
  414. //enum isCallbackWithOneParameter = is(typeof(receiver("")) : void);
  415. enum isCallbackWithLessThanTwoParameters =
  416. (is(typeof(receiver) == delegate) || is(typeof(*receiver) == function)) &&
  417. !is(typeof(receiver("", "")));
  418. if (!isCallbackWithLessThanTwoParameters && !(val.length) && !incremental) {
  419. // Eat the next argument too. Check to make sure there's one
  420. // to be eaten first, though.
  421. enforce(i < args.length,
  422. "Missing value for argument " ~ a ~ ".");
  423. val = args[i];
  424. args = args[0 .. i] ~ args[i + 1 .. $];
  425. }
  426. static if (is(typeof(*receiver) == enum))
  427. {
  428. // enum receiver
  429. *receiver = parse!(typeof(*receiver))(val);
  430. }
  431. else static if (is(typeof(*receiver) : real))
  432. {
  433. // numeric receiver
  434. if (incremental) ++*receiver;
  435. else *receiver = to!(typeof(*receiver))(val);
  436. }
  437. else static if (is(typeof(*receiver) == string))
  438. {
  439. // string receiver
  440. *receiver = to!(typeof(*receiver))(val);
  441. }
  442. else static if (is(typeof(receiver) == delegate) ||
  443. is(typeof(*receiver) == function))
  444. {
  445. static if (is(typeof(receiver("", "")) : void))
  446. {
  447. // option with argument
  448. receiver(option, val);
  449. }
  450. else static if (is(typeof(receiver("")) : void))
  451. {
  452. static assert(is(typeof(receiver("")) : void));
  453. // boolean-style receiver
  454. receiver(option);
  455. }
  456. else
  457. {
  458. static assert(is(typeof(receiver()) : void));
  459. // boolean-style receiver without argument
  460. receiver();
  461. }
  462. }
  463. else static if (isArray!(typeof(*receiver)))
  464. {
  465. // array receiver
  466. *receiver ~= [ to!(typeof((*receiver)[0]))(val) ];
  467. }
  468. else static if (isAssociativeArray!(typeof(*receiver)))
  469. {
  470. // hash receiver
  471. alias typeof(receiver.keys[0]) K;
  472. alias typeof(receiver.values[0]) V;
  473. auto j = std.string.indexOf(val, assignChar);
  474. auto key = val[0 .. j], value = val[j + 1 .. $];
  475. (*receiver)[to!(K)(key)] = to!(V)(value);
  476. }
  477. else
  478. {
  479. static assert(false, "Dunno how to deal with type " ~
  480. typeof(receiver).stringof);
  481. }
  482. }
  483. }
  484. }
  485. /**
  486. The option character. Defaults to '-' but it can be assigned to
  487. prior to calling $(D getopt).
  488. */
  489. dchar optionChar = '-';
  490. /**
  491. The string that conventionally marks the end of all
  492. options. Defaults to "--" but can be assigned to prior to calling
  493. $(D getopt). Assigning an empty string to $(D endOfOptions)
  494. effectively disables it.
  495. */
  496. string endOfOptions = "--";
  497. /**
  498. The assignment character used in options with parameters. Defaults
  499. to '=' but can be assigned to prior to calling $(D getopt).
  500. */
  501. dchar assignChar = '=';
  502. enum autoIncrementChar = '+';
  503. private struct configuration
  504. {
  505. mixin(bitfields!(
  506. bool, "caseSensitive", 1,
  507. bool, "bundling", 1,
  508. bool, "passThrough", 1,
  509. bool, "stopOnFirstNonOption", 1,
  510. ubyte, "", 4));
  511. }
  512. private bool optMatch(string arg, string optPattern, ref string value,
  513. configuration cfg)
  514. {
  515. //writeln("optMatch:\n ", arg, "\n ", optPattern, "\n ", value);
  516. //scope(success) writeln("optMatch result: ", value);
  517. if (!arg.length || arg[0] != optionChar) return false;
  518. // yank the leading '-'
  519. arg = arg[1 .. $];
  520. immutable isLong = arg.length > 1 && arg[0] == optionChar;
  521. //writeln("isLong: ", isLong);
  522. // yank the second '-' if present
  523. if (isLong) arg = arg[1 .. $];
  524. immutable eqPos = std.string.indexOf(arg, assignChar);
  525. if (isLong && eqPos >= 0)
  526. {
  527. // argument looks like --opt=value
  528. value = arg[eqPos + 1 .. $];
  529. arg = arg[0 .. eqPos];
  530. }
  531. else
  532. {
  533. if (!isLong && !cfg.bundling)
  534. {
  535. // argument looks like -ovalue and there's no bundling
  536. value = arg[1 .. $];
  537. arg = arg[0 .. 1];
  538. }
  539. else
  540. {
  541. // argument looks like --opt, or -oxyz with bundling
  542. value = null;
  543. }
  544. }
  545. //writeln("Arg: ", arg, " pattern: ", optPattern, " value: ", value);
  546. // Split the option
  547. const variants = split(optPattern, "|");
  548. foreach (v ; variants)
  549. {
  550. //writeln("Trying variant: ", v, " against ", arg);
  551. if (arg == v || !cfg.caseSensitive && toUpper(arg) == toUpper(v))
  552. return true;
  553. if (cfg.bundling && !isLong && v.length == 1
  554. && std.string.indexOf(arg, v) >= 0)
  555. {
  556. //writeln("success");
  557. return true;
  558. }
  559. }
  560. return false;
  561. }
  562. private void setConfig(ref configuration cfg, config option)
  563. {
  564. switch (option)
  565. {
  566. case config.caseSensitive: cfg.caseSensitive = true; break;
  567. case config.caseInsensitive: cfg.caseSensitive = false; break;
  568. case config.bundling: cfg.bundling = true; break;
  569. case config.noBundling: cfg.bundling = false; break;
  570. case config.passThrough: cfg.passThrough = true; break;
  571. case config.noPassThrough: cfg.passThrough = false; break;
  572. case config.stopOnFirstNonOption:
  573. cfg.stopOnFirstNonOption = true; break;
  574. default: assert(false);
  575. }
  576. }
  577. unittest
  578. {
  579. uint paranoid = 2;
  580. string[] args = (["program.name",
  581. "--paranoid", "--paranoid", "--paranoid"]).dup;
  582. getopt(args, "paranoid+", &paranoid);
  583. assert(paranoid == 5, to!(string)(paranoid));
  584. enum Color { no, yes }
  585. Color color;
  586. args = (["program.name", "--color=yes",]).dup;
  587. getopt(args, "color", &color);
  588. assert(color, to!(string)(color));
  589. color = Color.no;
  590. args = (["program.name", "--color", "yes",]).dup;
  591. getopt(args, "color", &color);
  592. assert(color, to!(string)(color));
  593. string data = "file.dat";
  594. int length = 24;
  595. bool verbose = false;
  596. args = (["program.name", "--length=5",
  597. "--file", "dat.file", "--verbose"]).dup;
  598. getopt(
  599. args,
  600. "length", &length,
  601. "file", &data,
  602. "verbose", &verbose);
  603. assert(args.length == 1);
  604. assert(data == "dat.file");
  605. assert(length == 5);
  606. assert(verbose);
  607. //
  608. string[] outputFiles;
  609. args = (["program.name", "--output=myfile.txt",
  610. "--output", "yourfile.txt"]).dup;
  611. getopt(args, "output", &outputFiles);
  612. assert(outputFiles.length == 2
  613. && outputFiles[0] == "myfile.txt" && outputFiles[0] == "myfile.txt");
  614. args = (["program.name", "--tune=alpha=0.5",
  615. "--tune", "beta=0.6"]).dup;
  616. double[string] tuningParms;
  617. getopt(args, "tune", &tuningParms);
  618. assert(args.length == 1);
  619. assert(tuningParms.length == 2);
  620. assert(tuningParms["alpha"] == 0.5);
  621. assert(tuningParms["beta"] == 0.6);
  622. uint verbosityLevel = 1;
  623. void myHandler(string option)
  624. {
  625. if (option == "quiet")
  626. {
  627. verbosityLevel = 0;
  628. }
  629. else
  630. {
  631. assert(option == "verbose");
  632. verbosityLevel = 2;
  633. }
  634. }
  635. args = (["program.name", "--quiet"]).dup;
  636. getopt(args, "verbose", &myHandler, "quiet", &myHandler);
  637. assert(verbosityLevel == 0);
  638. args = (["program.name", "--verbose"]).dup;
  639. getopt(args, "verbose", &myHandler, "quiet", &myHandler);
  640. assert(verbosityLevel == 2);
  641. verbosityLevel = 1;
  642. void myHandler2(string option, string value)
  643. {
  644. assert(option == "verbose");
  645. verbosityLevel = 2;
  646. }
  647. args = (["program.name", "--verbose", "2"]).dup;
  648. getopt(args, "verbose", &myHandler2);
  649. assert(verbosityLevel == 2);
  650. verbosityLevel = 1;
  651. void myHandler3()
  652. {
  653. verbosityLevel = 2;
  654. }
  655. args = (["program.name", "--verbose"]).dup;
  656. getopt(args, "verbose", &myHandler3);
  657. assert(verbosityLevel == 2);
  658. bool foo, bar;
  659. args = (["program.name", "--foo", "--bAr"]).dup;
  660. getopt(args,
  661. std.getopt.config.caseSensitive,
  662. std.getopt.config.passThrough,
  663. "foo", &foo,
  664. "bar", &bar);
  665. assert(args[1] == "--bAr");
  666. // test stopOnFirstNonOption
  667. args = (["program.name", "--foo", "nonoption", "--bar"]).dup;
  668. foo = bar = false;
  669. getopt(args,
  670. std.getopt.config.stopOnFirstNonOption,
  671. "foo", &foo,
  672. "bar", &bar);
  673. assert(foo && !bar && args[1] == "nonoption" && args[2] == "--bar");
  674. args = (["program.name", "--foo", "nonoption", "--zab"]).dup;
  675. foo = bar = false;
  676. getopt(args,
  677. std.getopt.config.stopOnFirstNonOption,
  678. "foo", &foo,
  679. "bar", &bar);
  680. assert(foo && !bar && args[1] == "nonoption" && args[2] == "--zab");
  681. args = (["program.name", "--fb1", "--fb2=true", "--tb1=false"]).dup;
  682. bool fb1, fb2;
  683. bool tb1 = true;
  684. getopt(args, "fb1", &fb1, "fb2", &fb2, "tb1", &tb1);
  685. assert(fb1 && fb2 && !tb1);
  686. // test function callbacks
  687. static class MyEx : Exception
  688. {
  689. this() { super(""); }
  690. this(string option) { this(); this.option = option; }
  691. this(string option, string value) { this(option); this.value = value; }
  692. string option;
  693. string value;
  694. }
  695. static void myStaticHandler1() { throw new MyEx(); }
  696. args = (["program.name", "--verbose"]).dup;
  697. try { getopt(args, "verbose", &myStaticHandler1); assert(0); }
  698. catch (MyEx ex) { assert(ex.option is null && ex.value is null); }
  699. static void myStaticHandler2(string option) { throw new MyEx(option); }
  700. args = (["program.name", "--verbose"]).dup;
  701. try { getopt(args, "verbose", &myStaticHandler2); assert(0); }
  702. catch (MyEx ex) { assert(ex.option == "verbose" && ex.value is null); }
  703. static void myStaticHandler3(string option, string value) { throw new MyEx(option, value); }
  704. args = (["program.name", "--verbose", "2"]).dup;
  705. try { getopt(args, "verbose", &myStaticHandler3); assert(0); }
  706. catch (MyEx ex) { assert(ex.option == "verbose" && ex.value == "2"); }
  707. }
  708. unittest
  709. {
  710. // From bugzilla 2142
  711. bool f_linenum, f_filename;
  712. string[] args = [ "", "-nl" ];
  713. getopt
  714. (
  715. args,
  716. std.getopt.config.bundling,
  717. //std.getopt.config.caseSensitive,
  718. "linenum|l", &f_linenum,
  719. "filename|n", &f_filename
  720. );
  721. assert(f_linenum);
  722. assert(f_filename);
  723. }
  724. unittest
  725. {
  726. // From bugzilla 6887
  727. string[] p;
  728. string[] args = ["", "-pa"];
  729. getopt(args, "p", &p);
  730. assert(p.length == 1);
  731. assert(p[0] == "a");
  732. }
  733. unittest
  734. {
  735. // From bugzilla 6888
  736. int[string] foo;
  737. auto args = ["", "-t", "a=1"];
  738. getopt(args, "t", &foo);
  739. assert(foo == ["a":1]);
  740. }
  741. unittest
  742. {
  743. // From bugzilla 9583
  744. int opt;
  745. auto args = ["prog", "--opt=123", "--", "--a", "--b", "--c"];
  746. getopt(args, "opt", &opt);
  747. assert(args == ["prog", "--a", "--b", "--c"]);
  748. }
  749. unittest
  750. {
  751. string foo, bar;
  752. auto args = ["prog", "-thello", "-dbar=baz"];
  753. getopt(args, "t", &foo, "d", &bar);
  754. assert(foo == "hello");
  755. assert(bar == "bar=baz");
  756. // From bugzilla 5762
  757. string a;
  758. args = ["prog", "-a-0x12"];
  759. getopt(args, config.bundling, "a|addr", &a);
  760. assert(a == "-0x12", a);
  761. args = ["prog", "--addr=-0x12"];
  762. getopt(args, config.bundling, "a|addr", &a);
  763. assert(a == "-0x12");
  764. // From https://d.puremagic.com/issues/show_bug.cgi?id=11764
  765. args = ["main", "-test"];
  766. bool opt;
  767. args.getopt(config.passThrough, "opt", &opt);
  768. assert(args == ["main", "-test"]);
  769. }