1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
//! `lapp` provides a straightforward way to parse command-line
//! arguments, using the _usage text_ as a pattern.
//!
//! # Example
//! ```
//! extern crate lapp;
//!
//! let args = lapp::parse_args("
//!    A test program
//!    -v,--verbose  verbose output
//!    -k         (default 10)
//!    -s, --save (default 'out.txt')
//!    <out>      (default 'stdout')
//! ");
//! assert_eq!(args.get_bool("verbose"),false);
//! assert_eq!(args.get_integer("k"),10);
//! assert_eq!(args.get_string("save"),"out.txt");
//! assert_eq!(args.get_string("out"),"stdout");
//! ```
//!
//! The usage text or _specification_ follows these simple rules:
//! line begining with one of '-short, --long', '--long' or '-short' (flags)
//! or begining with <name> (positional arguments).
//! These may be followed by a type/default specifier (<type>) - otherwise considered a bool flag
//! with default `false`. This specifier can be a type (like '(integer)') or a default,
//! like '(default 10)`. If there's a default, the type is infered from the value - can always
//! use single quotes to insist that the flag value is a string. Otherwise this flag is
//! _required_ and must be present! You can also use a type with default, e.g. "(path default ~/.boo).
//!
//! The currently supported types are 'string','integer','bool','float','infile','outfile' and 'path'.
//! There are corresponding access methods like `get_string("flag")` and so forth.
//! Access methods like `get_string_result("flag")` will _not_ exit the program on error
//! and instead return an error.
//!
//! The flag may be followed by '...' (e.g '-I... (<type>)') and it is then a _multiple_
//! flag; its value will be a vector. This vector may be empty (flag is not required).
//! If the '...' appears inside the type specifier (e.g. '-p (integer...)') then
//! the flag is expecting several space-separated values (like -p '10 20 30'); it is also
//! represented by a vector.
//!
//! Rest of line (or any other kind of line) is ignored.
//!
//! lapp scans command-line arguments using GNU-style short and long flags.
//! Short flags may be combined, and may immediately followed by a value, e.g '-vk5'.
//! As an extension, you can say '--flag=value' or '-f:value'.

use std::process;
use std::env;
use std::io;
use std::io::{Write,Read};
use std::error::Error;
use std::str::FromStr;
use std::fmt::Display;
use std::path::PathBuf;

mod strutil;
mod types;
mod flag;
use types::*;
pub type Result<T> = types::Result<T>;
use flag::Flag;

pub struct Args<'a> {
    flags: Vec<Flag>,
    pos: usize,
    text: &'a str,
    varargs: bool,
    user_types: Vec<String>,
    istart: usize,
}

impl <'a> Args<'a> {
    /// provide a _usage string_ from which we extract flag definitions
    pub fn new(text: &'a str) -> Args {
        Args{flags: Vec::new(), pos: 0, text: text, varargs: false, user_types: Vec::new(), istart: 1}
    }

    /// start offset in program command-line arguments.
    /// This defaults to 1, but e.g. for Cargo subcommands
    /// it would be 2
    pub fn start(mut self, istart: usize) -> Self {
        self.istart = istart;
        self
    }

    /// declare any user-defined types to be used in the spec.
    /// (They will need to implement FromStr)
    pub fn user_types(&mut self, types: &[&str]) {
        let v: Vec<String> = types.iter().map(|s| s.to_string()).collect();
        self.user_types = v;
    }

    /// bail out of program with non-zero return code.
    /// May force this to panic instead with the
    /// LAPP_PANIC environment variable.
    pub fn quit(&self, msg: &str) -> ! {
        let path = env::current_exe().unwrap();
        let exe = path.file_name().unwrap().to_string_lossy();
        let text = format!("{} error: {}\nType {} --help for more information",exe,msg,exe);
        if env::var("LAPP_PANIC").is_ok() {
            panic!(text);
        } else {
            writeln!(&mut io::stderr(),"{}",text).unwrap();
            process::exit(1);
        }
    }

    /// create suggested variable or struct declarations for accessing the flags...
    pub fn declarations(&mut self, struct_name: &str) -> String {
        if let Err(e) = self.parse_spec() {
            self.quit(e.description());
        }
        let mut res = String::new();
        if struct_name.len() > 0 {
            res += &format!("const USAGE: &'static str = \"\n{}\";\n",self.text);
            res += &format!("#[derive(Debug)]\nstruct {} {{\n",struct_name);
            for f in &self.flags {
                res += &format!("\t{}: {},\n",f.rust_name(),f.rust_type());
            }
            res += &format!(
                "}}\n\nimpl {} {{\n\tfn new() -> ({},lapp::Args<'static>) {{\n",
                struct_name,struct_name);
            res += &format!(
                "\t\tlet args = lapp::parse_args(USAGE);\n\t\t({}{{\n",struct_name);
            for f in &self.flags {
                res += &format!("\t\t\t{}: {},\n",f.rust_name(),f.getter_name());
            }
            res += &format!("\t\t}},args)\n\t}}\n}}\n\n");
        } else {
            for f in &self.flags {
                res += &format!("    let {} = {};\n",
                    f.rust_name(),f.getter_name());
            }
        }
        res
    }

    pub fn dump(&mut self) {
        self.parse();
        for f in &self.flags {
            println!("flag '{}' value {:?}",f.long,f.value);
        }
    }

    pub fn parse_env_args(&mut self) -> Result<()> {
        let v: Vec<String> = env::args().skip(self.istart).collect();
        self.parse_command_line(v)
    }

    /// parse the spec and the command-line
    pub fn parse_result(&mut self) -> Result<()> {
        self.parse_spec()?;
        self.parse_env_args()
    }


    /// parse the spec and the command-line, quitting on error.
    pub fn parse(&mut self) {
        if let Err(e) = self.parse_result() {
            self.quit(e.description());
        }
    }

    /// parse the spec and create the flags.
    pub fn parse_spec(&mut self) -> Result<()> {
        for line in self.text.lines() {
            if let Err(e) = self.parse_spec_line(line) {
                return error(format!("{}\nat line: '{}'",e.description(),line));
            }
        }
        if let Err(_) = self.flags_by_long("help") {
            self.parse_spec_line("   -h,--help this help").unwrap();
        }
        Ok(())
    }


    fn parse_spec_line(&mut self, mut slice: &str) -> Result<()> {
        use strutil::*;
        fn flag_error (flag: &Flag,msg: &str) -> Result<()> {
            error(format!("{}: flag '{}'",msg,flag.long))
        }

        if let Some(idx) = slice.find(|c: char| ! c.is_whitespace()) {
            let mut flag: Flag = Default::default();
            let mut is_positional = false;
            slice = &slice[idx..];
            let is_flag = starts_with(&mut slice,"-");
            let mut long_flag = starts_with(&mut slice,"-");
            if is_flag && ! long_flag { // short flag
                flag.short = (&slice[0..1]).chars().next().unwrap();
                flag.long = flag.short.to_string();
                if ! flag.short.is_alphanumeric() {
                    return flag_error(&flag,"not allowed: only letters or digits in short flags");
                }
                slice = &slice[1..];
                if let Some(0) = slice.find(|c: char| c.is_alphanumeric()) {
                   return flag_error(&flag,"short flags should have one character");
                }
                if starts_with(&mut slice,",") {
                    slice = skipws(slice);
                    long_flag = starts_with(&mut slice,"--");
                    if ! long_flag {
                        return flag_error(&flag,"expecting long flag after short flag");
                    }
                }
            }
            if long_flag {
                let idx = slice.find(|c: char| ! (c.is_alphanumeric() || c == '_' || c == '-'))
                    .unwrap_or(slice.len());
                let parts = slice.split_at(idx);
                flag.long = parts.0.to_string();
                slice = parts.1;
                if slice.len() > 0 && ! (slice.starts_with(" ") || slice.starts_with("."))  {
                    return flag_error(&flag,"long flags can only contain letters, numbers, '_' or '-'");
                }
            } else
            if starts_with(&mut slice, "<") { // positional argument
                flag.long = grab_upto(&mut slice, ">")?;
                self.pos = self.pos + 1;
                flag.pos = self.pos;
                is_positional = true;
            }
            if flag.long == "" && flag.short == '\0' {
                // not a significant line, ignore!
                return Ok(());
            }
            if flag.long == "" { // just a short flag
                flag.long = flag.short.to_string();
            }
            slice = skipws(slice);
            if starts_with(&mut slice,"...") {
                flag.is_multiple = true;
                slice = skipws(slice);
            }
            if starts_with(&mut slice,"(") {
                let r = grab_upto(&mut slice, ")")?;
                let mut rest = r.as_str().trim();
                let multable = ends_with(&mut rest,"...");
                if let Some((b1,b2)) = split_with(rest,"..") {
                    // bounds on a number type
                    flag.set_range_constraint(b1,b2)?;
                } else {
                    // default VALUE or TYPE
                    if rest.len() == 0 {
                        return flag_error(&flag,"nothing inside type specifier");
                    }
                    if starts_with(&mut rest,"default ") {
                        rest = skipws(rest);
                        // flag type will be deduced
                        flag.set_default_from_string(rest,true)?;
                    } else {
                        let name = grab_word(&mut rest);
                        // custom types are _internally_ stored as string types,
                        // but we must verify that it is a known type!
                        flag.vtype = if self.user_types.iter().any(|s| s == name.as_str()) {
                            Type::Str
                        } else {
                            Type::from_name(&name)?
                        };
                        if starts_with(&mut rest,"default ") {
                            rest = skipws(rest);
                            // flag already has a definite type
                            flag.set_default_from_string(rest,false)?;
                        }
                    }
                }
                // if type is followed by '...' then the flag is also represented
                // by a vector (e.g. --ports '8080 8081 8082').
                // UNLESS it is a positional argument,
                // where it is considered multiple!
                if multable {
                    flag.defval = Value::empty_array();
                    if is_positional {
                        flag.is_multiple = true;
                        if self.varargs {
                            return flag_error(&flag,"only last argument can occur multiple times");
                        }
                        self.varargs = true;
                    } else { // i.e the flag type is an array of a basic scalar type
                        flag.vtype = flag.vtype.create_empty_array();
                    }
                }
                if flag.is_multiple {
                    flag.value = Value::empty_array();
                }
            } else {
                flag.defval = Value::Bool(false);
                flag.vtype = Type::Bool;
            }
            if slice.len() > 0 {
                flag.help = skipws(slice).to_string();
            }

            // it is an error to specify a flag twice...
            if self.flags_by_long_ref(&flag.long).is_ok() {
                return flag_error(&flag,"already defined");
            }
            self.flags.push(flag);
        }
        Ok(())

    }

    fn flags_by_long(&mut self, s: &str) -> Result<&mut Flag> {
        self.flags.iter_mut()
            .filter(|&ref f| f.long == s)
            .next().ok_or(LappError(format!("no long flag '{}'",s)))
    }

    fn flags_by_long_ref(&self, s: &str) -> Result<&Flag> {
        self.flags.iter()
            .filter(|&f| f.long == s)
            .next().ok_or(LappError(format!("no long flag '{}'",s)))
    }

    fn flags_by_short(&mut self, ch: char) -> Result<&mut Flag> {
        self.flags.iter_mut()
            .filter(|&ref f| f.short == ch)
            .next().ok_or(LappError(format!("no short flag '{}'",ch)))
    }

    fn flags_by_pos(&mut self, pos: usize) -> Result<&mut Flag> {
        self.flags.iter_mut()
            .filter(|&ref f| f.pos == pos)
            .next().ok_or(LappError(format!("no arg #{}",pos)))
    }

    pub fn parse_command_line(&mut self, v: Vec<String>) -> Result<()> {
        use strutil::*;
        let mut iter = v.into_iter();

        fn nextarg(name: &str, ms: Option<String>) -> Result<String> {
            if  ms.is_none() {return error(format!("no value for flag '{}'",name));}
            Ok(ms.unwrap())
        };

        // flags _may_ have the value after a = or : delimiter
        fn extract_flag_value(s: &mut &str) -> String {
            if let Some(idx) = s.find(|c: char| c == '=' || c == ':') {
               let rest = (&s[idx+1..]).to_string();
               *s = &s[0..idx];
               rest
            } else {
               "".to_string()
           }
        }

        let mut parsing = true;
        let mut k = 1;
        while let Some(arg) = iter.next() {
            let mut s = arg.as_str();
             if parsing && starts_with(&mut s, "--") { // long flag
                if s.is_empty() { // plain '--' means 'stop arg processing'
                    parsing = false;
                } else {
                    let mut rest = extract_flag_value(&mut s);
                    let flag = self.flags_by_long(s)?;
                    if flag.vtype != Type::Bool { // then it needs a value....
                        if rest == "" {  // try grab the next arg
                            rest = nextarg(s,iter.next())?;
                        }
                        flag.set_value_from_string(&rest)?;
                    } else {
                        flag.set_value(Value::Bool(true))?;
                    }
                }
            } else
            if parsing && starts_with(&mut s,"-") { // short flag
                // there can be multiple short flags
                // although only the last one can take a value
                let mut chars = s.chars();
                while let Some(ch) = chars.next() {
                    let flag = self.flags_by_short(ch)?;
                    if flag.vtype != Type::Bool {
                        let mut rest: String = chars.collect();
                        if rest == "" {
                            rest = nextarg(&flag.long,iter.next())?;
                        }
                        flag.set_value_from_string(&rest)?;
                        break;
                    } else {
                       flag.set_value(Value::Bool(true))?;
                    }
                }
            } else {  // positional argument
                let flag = self.flags_by_pos(k)?;
                flag.set_value_from_string(s)?;
                // multiple arguments are added to the vector value
                if ! flag.is_multiple {
                    k += 1;
                }

            }
        }


        // display usage if help is requested
        if let Ok(ref flag) = self.flags_by_long_ref("help") {
            if flag.is_set {
                let text = strutil::dedent(self.text);
                println!("{}",text);
                process::exit(0);
            }
        }

        // fill in defaults. If a default isn't available it's
        // a required flag. If not specified the flag value is set to an error
        for flag in &mut self.flags {
            flag.check()?;
        }
        Ok(())
    }

    /// clear used flag state
    pub fn clear_used(&mut self) {
        for flag in &mut self.flags {
            flag.uncheck();
        }
    }

    /// clear all the flags - ready to parse a new command line.
    pub fn clear(&mut self) {
        for flag in &mut self.flags {
            flag.clear();
        }
    }

    fn error_msg(&self, tname: &str, msg: &str, pos: Option<usize>) -> String {
        if let Some(idx) = pos {
            format!("argument #{} '{}': {}",idx,tname,msg)
        } else {
            format!("flag '{}': {}",tname,msg)
        }
    }

    fn bad_flag <T>(&self, tname: &str, msg: &str) -> Result<T> {
        let pos = if let Ok(ref flag) = self.flags_by_long_ref(tname) {
            flag.position()
        } else {
            None
        };
        error(&self.error_msg(tname,msg,pos))
    }

    fn unwrap<T>(&self, res: Result<T>) -> T {
        match res {
            Ok(v) => v,
            Err(e) => self.quit(e.description())
        }
    }

    // there are three bad scenarios here. First, the flag wasn't found.
    // Second, the flag's value was not set. Third, the flag's value was an error.
    fn result_flag_flag (&self, name: &str) -> Result<&Flag> {
        if let Ok(ref flag) = self.flags_by_long_ref(name) {
           if flag.value.is_none() {
                self.bad_flag(name,"is required")
            } else {
                if let Value::Error(ref s) = flag.value {
                   self.bad_flag(name,s)
                } else {
                    Ok(flag)
                }
            }
        } else {
            self.bad_flag(name,"is unknown")
        }
    }

    fn result_flag_value (&self, name: &str) -> Result<&Value> {
        Ok(&(self.result_flag_flag(name)?.value))
    }

    // this extracts the desired value from the Value struct using a closure.
    // This operation may fail, e.g. args.get_float("foo") is an error if the
    // flag type is integer.
    fn result_flag<T, F: Fn(&Value) -> Result<T>> (&self, name: &str, extract: F) -> Result<T> {
        match self.result_flag_value(name) {
            Ok(value) => {
                match extract(value) {
                    Ok(v) => Ok(v),
                    Err(e) => self.bad_flag(name,e.description())
                }
            },
            Err(e) => Err(e)
        }
    }

    /// has this flag been set? Quits if it's an unknown flag
    pub fn flag_present(&self, name: &str) -> bool {
        if let Ok(ref flag) = self.flags_by_long_ref(name) {
           if flag.value.is_none() {
                false
            } else {
                true
            }
        } else {
            self.quit(&format!("'{}' is not a flag",name));
        }
    }


    /// get flag as a string
    pub fn get_string_result(&self, name: &str) -> Result<String> {
        self.result_flag(name,|v| v.as_string())
    }

    /// get flag as an integer
    pub fn get_integer_result(&self, name: &str) -> Result<i32> {
        self.result_flag(name,|v| v.as_int())
    }

    /// get flag as a float
    pub fn get_float_result(&self, name: &str) -> Result<f32> {
        self.result_flag(name,|v| v.as_float())
    }

    /// get flag as boolean
    pub fn get_bool_result(&self, name: &str) -> Result<bool> {
        self.result_flag(name,|v| v.as_bool())
    }

    /// get flag as a file for reading
    pub fn get_infile_result(&self, name: &str) -> Result<Box<Read>> {
        self.result_flag(name,|v| v.as_infile())
    }

    /// get flag as a file for writing
    pub fn get_outfile_result(&self, name: &str) -> Result<Box<Write>> {
        self.result_flag(name,|v| v.as_outfile())
    }

    /// get flag as a path
    pub fn get_path_result(&self, name: &str) -> Result<PathBuf> {
        self.result_flag(name,|v| v.as_path())
    }

    /// get flag always as text, if it's defined
    pub fn get_text_result(&self, name: &str) -> Result<&String> {
        self.result_flag_flag(name).map(|f| &f.strings[0])
    }

    /// get flag as any value which can parsed from a string.
    // The magic here is that Rust needs to be told that
    // the associated Err type can be displayed.
    pub fn get_result<T>(&self, name: &str) -> Result<T>
    where T: FromStr, <T as FromStr>::Err : Display
    {
        match self.get_text_result(name)?.parse::<T>() {
            Ok(v) => Ok(v),
            Err(e) =>  self.bad_flag(name,&e.to_string())
        }
    }

    /// get flag as a string, quitting otherwise.
    pub fn get_string(&self, name: &str) -> String {
        self.unwrap(self.get_string_result(name))
    }

    /// get flag as an integer, quitting otherwise.
    pub fn get_integer(&self, name: &str) -> i32 {
        self.unwrap(self.get_integer_result(name))
    }

    /// get flag as a float, quitting otherwise.
    pub fn get_float(&self, name: &str) -> f32 {
        self.unwrap(self.get_float_result(name))
    }

    /// get flag as a bool, quitting otherwise.
    pub fn get_bool(&self, name: &str) -> bool {
        self.unwrap(self.get_bool_result(name))
    }

    /// get flag as a file for reading, quitting otherwise.
    pub fn get_infile(&self, name: &str) -> Box<Read> {
        self.unwrap(self.get_infile_result(name))
    }

    /// get flag as a file for writing, quitting otherwise.
    pub fn get_outfile(&self, name: &str) -> Box<Write> {
        self.unwrap(self.get_outfile_result(name))
    }

    /// get flag as a path, quitting otherwise.
    pub fn get_path(&self, name: &str) -> PathBuf {
        self.unwrap(self.get_path_result(name))
    }

    /// get flag as any value which can parsed from a string, quitting otherwise.
    pub fn get<T>(&self, name: &str) -> T
    where T: FromStr, <T as FromStr>::Err : Display
    {
        match self.get_result::<T>(name) {
            Ok(v) => v,
            Err(e) => self.quit(&e.to_string())
        }
    }

    fn get_boxed_array(&self, name: &str, kind: &str) -> Result<&Vec<Box<Value>>> {
        let arr = self.result_flag_value(name)?.as_array()?;
        // empty array matches all types
        if arr.len() == 0 { return Ok(arr); }
        // otherwise check the type of the first element
        let ref v = *(arr[0]);
        let tname = v.type_of().short_name();
        if tname == kind {
            Ok(arr)
        } else {
            let msg = format!("wanted array of {}, but is array of {}",kind,tname);
            error(self.error_msg(name,&msg,None))
        }
    }

    fn get_array_result<T,F>(&self, name: &str, kind: &str, extract: F) -> Result<Vec<T>>
    where T: Sized, F: Fn(&Box<Value>)->Result<T> {
        let va = self.get_boxed_array(name,kind)?;
        let mut res = Vec::new();
        for v in va {
            let n = extract(v)?;
            res.push(n);
        }
        Ok(res)
    }

    /// get a multiple flag as an array of strings
    pub fn get_strings_result(&self, name: &str) -> Result<Vec<String>> {
        self.get_array_result(name,"string",|b| b.as_string())
    }

    /// get a multiple flag as an array of integers
    pub fn get_integers_result(&self, name: &str) -> Result<Vec<i32>> {
        self.get_array_result(name,"integer",|b| b.as_int())
    }

    /// get a multiple flag as an array of floats
    pub fn get_floats_result(&self, name: &str) -> Result<Vec<f32>> {
        self.get_array_result(name,"float",|b| b.as_float())
    }

    /// get a multiple flag as an array of any parsable value.
    pub fn get_results<T>(&self, name: &str) -> Result<Vec<T>>
    where T: FromStr, <T as FromStr>::Err : Display
    {
        let flag = self.result_flag_flag(name)?;
        flag.strings.iter()
            .map(|s| s.parse::<T>()) // Result<T,Err>
            .map(|r| { match r { // but we want Result<T,LappError>
                Ok(v) => Ok(v),
                Err(e) => self.bad_flag(name,&e.to_string())
             }})
            .collect()
    }


    /// get a multiple flag as an array of strings, quitting otherwise
    pub fn get_strings(&self, name: &str) -> Vec<String> {
        self.unwrap(self.get_strings_result(name))
    }

    /// get a multiple flag as an array of integers, quitting otherwise
    pub fn get_integers(&self, name: &str) -> Vec<i32> {
        self.unwrap(self.get_integers_result(name))
    }

    /// get a multiple flag as an array of floats, quitting otherwise
    pub fn get_floats(&self, name: &str) -> Vec<f32> {
        self.unwrap(self.get_floats_result(name))
    }

    /// get a multiple flag as an array of any parsable value, quitting otherwise
    pub fn get_array<T>(&self, name: &str) -> Vec<T>
    where T: FromStr, <T as FromStr>::Err : Display
    {
        self.unwrap(self.get_results(name))
    }


}

/// parse the command-line specification and use it
/// to parse the program's command line args.
/// As before, quits on any error.
pub fn parse_args(s: &str) -> Args {
    let mut res = Args::new(s);
    res.parse();
    res
}

#[cfg(test)]
mod tests {
    use super::*;

    const SIMPLE: &'static str = "
        Testing Lapp
          -v, --verbose verbose flag
          -k   arb flag
          -o, --output (default 'stdout')
          -p   (integer...)
          -I, --include... (string)
          <in> (string)
          <out> (string...)
    ";


    fn arg_strings(a: &[&str]) -> Vec<String> {
        a.iter().map(|s| s.to_string()).collect()
    }

    fn empty_strings() -> Vec<String> {
        Vec::new()
    }

    fn parse_args(spec: &'static str, parms: &[&str]) -> Args<'static> {
        let mut args = Args::new(spec);
        args.parse_spec().expect("spec failed");
        args.parse_command_line(arg_strings(parms)).expect("scan failed");
        args
    }


    struct SimpleTest {
        verbose: bool,
        k: bool,
        output: String,
        p: Vec<i32>,
        include: Vec<String>,
        out: Vec<String>
    }

    impl SimpleTest {
        fn new(test_args: &[&str]) -> SimpleTest {
            let args = parse_args(SIMPLE,test_args);
            SimpleTest {
                verbose: args.get_bool("verbose"),
                k: args.get_bool("k"),
                output: args.get_string("output"),
                p: args.get_integers("p"),
                include: args.get_strings("include"),
                out: args.get_strings("out")
            }
        }
    }

    #[test]
    fn test_simple_just_out() {
        let res = SimpleTest::new(&["boo","hello"]);
        assert_eq!(res.verbose,false);
        assert_eq!(res.k,false);
        assert_eq!(res.output,"stdout");
        assert_eq!(res.p,&[]);
        assert_eq!(res.out,&["hello"]);
    }

    #[test]
    fn test_simple_bool_flags() {
        let res = SimpleTest::new(&["boo","-vk","hello"]);
        assert_eq!(res.verbose,true);
        assert_eq!(res.k,true);
        assert_eq!(res.output,"stdout");
        assert_eq!(res.p,&[]);
        assert_eq!(res.out,&["hello"]);
    }

    #[test]
    fn test_simple_array_flag() {
        let res = SimpleTest::new(&["boo","-p","10 20 30","hello"]);
        assert_eq!(res.verbose,false);
        assert_eq!(res.k,false);
        assert_eq!(res.output,"stdout");
        assert_eq!(res.p,&[10,20,30]);
        assert_eq!(res.out,&["hello"]);
    }

    #[test]
    fn test_simple_multiple_positional_args() {
        let res = SimpleTest::new(&["boo","hello","baggins","--","--frodo"]);
        assert_eq!(res.verbose,false);
        assert_eq!(res.k,false);
        assert_eq!(res.output,"stdout");
        assert_eq!(res.p,&[]);
        assert_eq!(res.include,empty_strings());
        assert_eq!(res.out,&["hello","baggins","--frodo"]);
    }

    #[test]
    fn test_simple_multiple_flags() {
        let res = SimpleTest::new(&["boo","-I.","-I..","--include","lib","hello"]);
        assert_eq!(res.verbose,false);
        assert_eq!(res.k,false);
        assert_eq!(res.output,"stdout");
        assert_eq!(res.p,&[]);
        assert_eq!(res.include,&[".","..","lib"]);
        assert_eq!(res.out,&["hello"]);
    }

    fn err<T>(r: Result<T>) -> String {
        r.err().unwrap().description().to_string()
    }

    fn ok<T>(r: Result<T>) -> T {
        r.unwrap()
    }

    static ERRS: &str = "
        testing lapp
        -s,--str (string)
        <frodo> (float)
        <bonzo>... (integer)
    ";

    #[test]
    fn test_errors_result() {
        let aa = parse_args(ERRS,&["1","10","20","30"]);
        assert_eq!(err(aa.get_string_result("str")),"flag \'str\': is required");
        assert_eq!(err(aa.get_string_result("frodo")),"argument #1 \'frodo\': not a string, but float");
        assert_eq!(ok(aa.get_float_result("frodo")),1.0);
        assert_eq!(ok(aa.get_integers_result("bonzo")),[10, 20, 30]);
    }



    const CUSTOM: &str = "
        Custom types need to be given names
        so we accept them as valid:
        --hex (hex)
    ";

    // they need to be user types that implement FromStr
    use std::str::FromStr;
    use std::num::ParseIntError;

    struct Hex {
        value: u64
    }

    impl FromStr for Hex {
        type Err = ParseIntError;

        fn from_str(s: &str) -> ::std::result::Result<Self,Self::Err> {
            let value = u64::from_str_radix(s,16)?;
            Ok(Hex{value: value})
        }
    }


    #[test]
    fn test_custom() {
        let mut args = Args::new(CUSTOM);
        args.user_types(&["hex"]);
        args.parse_spec().expect("spec failed");
        args.parse_command_line(arg_strings(&["--hex","FF"])).expect("scan failed");
        let hex: Hex = args.get("hex");
        assert_eq!(hex.value,0xFF);
    }


}