ecla/app/
mod.rs

1
2use parser::Parser;
3use show_help_tips;
4use command::Command;
5use flag::Flag;
6
7
8/// Command line application
9///
10#[derive(Debug)]
11pub struct App {
12    help: String,
13    version: String,
14    parser: Parser
15}
16
17impl App {
18    /// Create a new command line application.
19    pub fn new<T: Into<String>>(help: T, version: T) -> App {
20        let app = App {
21            help: help.into(),
22            version: version.into(),
23            parser: Parser::new()
24        };
25
26        if app.parser.no_args() || app.parser.get_flag("--help").is_some() {
27            app.show_help();
28            exit!(0);
29        }
30
31        if app.parser.get_flag("--version").is_some() {
32            app.show_version();
33            exit!(0);
34        }
35
36        app
37    }
38
39    /// Get sub command
40    pub fn get_command(&self, name: &str) -> Option<Command> {
41        self.parser.get_command(name)
42    }
43
44    /// Check arguments if has flags
45    pub fn has_flag(&self) -> bool {
46        self.parser.has_flag()
47    }
48
49    /// If you can not find any supported sub commands or flags,
50    /// you can use this to tell user something is wrong.
51    pub fn show_unknown_or_help(&self) {
52        if self.has_command() {
53            self.show_command_unknown();
54        } else if self.has_flag() {
55            self.show_help();
56        }
57    }
58
59    /// Check arguments if has sub command
60    pub fn has_command(&self) -> bool {
61        ! self.parser.no_command()
62    }
63
64    /// Get flag
65    pub fn get_flag<T: AsRef<str>>(&self, names: &[T]) -> Option<Flag> {
66        for name in names.into_iter() {
67            let flag = self.parser.get_flag(name.as_ref());
68            if flag.is_some() {
69                return flag;
70            }
71        }
72
73        None
74
75    }
76
77    /// Tell user is entering an unknown sub command
78    pub fn show_command_unknown(&self) {
79        errors!("unknown sub command: {}", self.parser.get_unknown_command().get_name());
80        show_help_tips();
81    }
82
83    /// Print help message
84    pub fn show_help(&self) {
85        println!("{}", self.help);
86    }
87
88    /// Print version
89    pub fn show_version(&self) {
90        println!("{}", self.version);
91    }
92}