Ticket #748: ArgumentsExample.d
| File ArgumentsExample.d, 2.2 kB (added by darrylb, 8 months ago) |
|---|
Arguments version of http://www.dsource.org/projects/tango/wiki/ArgParserExample |
| Line | |
|---|---|
| 1 | /******************************************************************************* |
| 2 | Illustrates use of the Arguments class. It shows the |
| 3 | different ways of defining arguments, and also shows some more |
| 4 | advanced use by loading arguments from a file using tango.io. |
| 5 | |
| 6 | *******************************************************************************/ |
| 7 | |
| 8 | import tetra.app.Arguments; |
| 9 | import tango.io.Stdout; |
| 10 | import tango.io.FileConduit; |
| 11 | import tango.text.stream.LineIterator; |
| 12 | |
| 13 | void main(char[][] cmdl) |
| 14 | { |
| 15 | char[] helpText = "Available options:\n\t\t-h\tthis help\n\t\t-cool-action\tdo "; |
| 16 | helpText ~= "cool things to your files\n\t\t-@filename\tuse filename as a response file "; |
| 17 | helpText ~= "with extra arguments\n\t\tall other arguments are handled as files to do "; |
| 18 | helpText ~= "cool things with."; |
| 19 | |
| 20 | auto args = new Arguments; |
| 21 | args.prefixShort = null; |
| 22 | args.prefixLong = ["-"]; |
| 23 | args.define("X").parameters(0,1); |
| 24 | args.define("h"); |
| 25 | args.define("@").delimiters([null]).parameters(0,1); |
| 26 | args.define("@").callback(delegate void(char[] a, char[] p){ |
| 27 | if (("@" in args) && (args["@"].length > 1)){ |
| 28 | throw new Exception("Only one response file can be given."); }}); |
| 29 | args.define("cool-action"); |
| 30 | args.parse(cmdl[1..$]); |
| 31 | |
| 32 | if (("h" in args) || (args.length < 2)) |
| 33 | Stdout(helpText).newline; |
| 34 | else |
| 35 | { |
| 36 | if ("@" in args) |
| 37 | { |
| 38 | auto file = new FileConduit(args["@"]); |
| 39 | auto lines = new LineIterator!(char)(file); |
| 40 | char[][] arguments; |
| 41 | foreach(line; lines) |
| 42 | arguments ~= line; |
| 43 | args.parse(arguments); |
| 44 | } |
| 45 | if ("cool-action" in args) |
| 46 | { |
| 47 | Stdout("Listing the files to be actioned in a cool way.").newline; |
| 48 | for (int i = 1; i <= args.parameters[null].length; i++) |
| 49 | Stdout.format("{0}. {1}", i, args.parameters[null][i-1]).newline; |
| 50 | Stdout("Cool and secret action performed.").newline; |
| 51 | } |
| 52 | if ("X" in args) |
| 53 | Stdout.format("User set the X factor to \"{0}\".", args["X"]).newline; |
| 54 | } |
| 55 | } |










