root/misc/tango/opttest.d

Revision 84, 2.6 kB (checked in by KirkMcDonald, 2 years ago)

Added doc-comments, changed to Tango naming conventions.

Line 
1 //import std.stdio : Stdout.formatln;
2 import tango.io.Stdout : Stdout;
3 import tango.text.convert.Format : Format;
4
5 import optparse;
6
7 Format!(char) format;
8
9 char[] format_arr(T)(T[] arr) {
10     char[] result = "[";
11     foreach (i, s; arr) {
12         result ~= format("{0}", s);
13         if (i != arr.length-1) result ~= ",";
14     }
15     result ~= "]";
16     return result;
17 }
18
19 void print_opts(Options options) {
20     Stdout.formatln("file:        {0}", options["file"]);
21     Stdout.formatln("imports:     {0}", format_arr(options.list("importPath")));
22     Stdout.formatln("verbosity:   {0}", options.count("verbose"));
23     Stdout.formatln("value:       {0}", options.value("value"));
24     Stdout.formatln("number list: {0}", format_arr(options.valueList("list")));
25     Stdout.formatln("switch:      {0}", options.flag("switch"));
26     Stdout.formatln("args:        {0}", format_arr(options.args));
27 }
28
29 int main(char[][] args) {
30     format = new Format!(char);
31     //Stdout.println(format_arr(args));
32     auto parser = new OptionParser("A test suite for optparser.");
33     parser.addOption("-f", "--file").help("Stores a single argument.");
34     parser.addOption(["-I", "--import"], "importPath", Action.Append).help("Adds arguments to a list.");
35     parser.addOption(["-c", "--callback"], {
36         Stdout.formatln("callback encountered");
37     }).help("Calls a callback.");
38     parser.addOption(["-n", "--number"], (int i) {
39         Stdout.formatln("number callback: {0} * 2 = {1}", i, i*2);
40     }).help("Calls a callback with a number.");
41     // A fancy callback
42     parser.addOption(["--fancy"], "a callback", (Options opts, inout char[][] a, inout int i, char[] name) {
43         Stdout.formatln("Current file: {0}", opts["file"]);
44         Stdout.formatln("Remaining args: {0}", a[i+1 .. $]);
45         // Skip the next arg
46         ++i;
47         Stdout.formatln("This arg's name: {0}", name);
48     }).help("Tests optparse's fancy callbacks.");
49     parser.addOption(["--enable"], "switch", Action.SetTrue).help("Enables the switch.");
50     parser.addOption(["--disable"], "switch", Action.SetFalse).help("Disables the switch.");
51     parser.addOption(["-V", "--value"], ArgType.Integer).help("Stores a single number").argName("NUMBER");
52     parser.addOption(["-l", "--list"], Action.Append, ArgType.Integer).help("Adds numbers to a list.").argName("NUMBER");
53     parser.addOption(["-v", "--verbose"], Action.Count).help("Counts the number of times this option appears.");
54     parser.addOption(["-h", "--help"], Action.Help).help("Displays a help message.");
55     auto options = parser.parse(args);
56
57     print_opts(options);
58
59     return 0;
60 }
Note: See TracBrowser for help on using the browser.