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
use crate::{Context, Result, Error, ErrorKind, CommandResolver, CommandHandler,
    Flag, Param, Resource, Intent, build_subcommand_positions,
    build_command_summary, subcommand_at_position, build_supcommand_summaries,
    build_subcommand_summaries, build_flag_summaries, build_param_summaries,
    build_resource_summaries, parse_args};

/// Command structure which represents command-line task.
pub struct Command<C = Context> {
    name: String,
    about: Option<String>,
    description: Option<String>,
    author: Option<String>,
    version: Option<String>,
    flags: Vec<Flag>,
    params: Vec<Param>,
    resources: Vec<Resource>,
    commands: Vec<Command<C>>,
    handler: Option<CommandHandler<C>>,
    resolver: Option<CommandResolver<C>>,
}

/// Command structure implementation.
impl<C> Command<C> {

    /// Returns name.
    pub fn name(&self) -> &String {
        &self.name
    }

    /// Returns about.
    pub fn about(&self) -> &Option<String> {
        &self.about
    }

    /// Returns description.
    pub fn description(&self) -> &Option<String> {
        &self.description
    }

    /// Returns author.
    pub fn author(&self) -> &Option<String> {
        &self.author
    }

    /// Returns version.
    pub fn version(&self) -> &Option<String> {
        &self.version
    }

    /// Returns flags.
    pub fn flags(&self) -> &Vec<Flag> {
        &self.flags
    }

    /// Returns flags.
    pub fn params(&self) -> &Vec<Param> {
        &self.params
    }

    /// Returns resources.
    pub fn resources(&self) -> &Vec<Resource> {
        &self.resources
    }

    /// Returns commands.
    pub fn commands(&self) -> &Vec<Command<C>> {
        &self.commands
    }
}

/// Command structure implementation.
impl<C> Command<C> {

    /// Returns new instance.
    pub fn with_name<S: Into<String>>(name: S) -> Self {
        Self {
            name: name.into(),
            about: None,
            flags: Vec::new(),
            params: Vec::new(),
            resources: Vec::new(),
            commands: Vec::new(),
            handler: None,
            resolver: None,
            description: None,
            author: None,
            version: None,
        }
    }

    /// Sets about.
    pub fn with_about<S: Into<String>>(mut self, val: S) -> Self {
        self.about = Some(val.into());
        self
    }

    /// Sets description.
    pub fn with_description<S: Into<String>>(mut self, val: S) -> Self {
        self.description = Some(val.into());
        self
    }

    /// Sets about.
    pub fn with_author<S: Into<String>>(mut self, val: S) -> Self {
        self.author = Some(val.into());
        self
    }

    /// Sets version.
    pub fn with_version<S: Into<String>>(mut self, val: S) -> Self {
        self.version = Some(val.into());
        self
    }
    
    /// Sets error handler function.
    pub fn with_handler(mut self, handler: CommandHandler<C>) -> Self {
        self.handler = Some(handler);
        self
    }

    /// Sets resolver function.
    pub fn with_resolver(mut self, resolver: CommandResolver<C>) -> Self {
        self.resolver = Some(resolver);
        self
    }

    /// Adds flag.
    pub fn with_flag(mut self, flag: Flag) -> Self {
        self.flags.push(flag);
        self
    }

    /// Adds param.
    pub fn with_param(mut self, param: Param) -> Self {
        self.params.push(param);
        self
    }

    /// Adds resource.
    pub fn with_resource(mut self, resource: Resource) -> Self {
        self.resources.push(resource);
        self
    }

    /// Adds subcommand.
    pub fn with_subcommand(mut self, command: Command<C>) -> Self {
        self.commands.push(command);
        self
    }

    /// Executes as a command-line application.
    pub fn run(self, ctx: &mut C) -> Result<i32> {
        self.run_args(parse_args(), ctx)
    }

    /// Executes as a command-line application.
    pub fn run_args<A, T>(self, args: A, ctx: &mut C) -> Result<i32>
        where
        A: IntoIterator<Item = T>,
        T: Into<String>,
    {
        let args: Vec<String> = args.into_iter().map(Into::into).collect();
        let command_positions = build_subcommand_positions(&self, &args)?;
        let command = subcommand_at_position(&self, &command_positions);
        let command_summary = build_command_summary(&command);
        let supcommand_summaries = build_supcommand_summaries(&self, &command_positions);
        let subcommand_summaries = build_subcommand_summaries(&command);
        let flag_summaries = build_flag_summaries(&command, &args)?;
        let param_summaries = build_param_summaries(&self, &args)?;
        let resource_summaries = build_resource_summaries(&command);

        let intent = Intent::new(
            args,
            command_summary,
            supcommand_summaries,
            subcommand_summaries,
            flag_summaries,
            param_summaries,
            resource_summaries,
        );

        let err = match &command.resolver {
            Some(resolver) => match resolver(&intent, ctx) {
                Ok(code) => return Ok(code),
                Err(err) => err,
            },
            None => Error::new(ErrorKind::MissingCommandResolver(command.name().to_string())),
        };
        match &command.handler {
            Some(handler) => handler(err, ctx),
            None => Err(err),
        }
    }
}

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

    #[test]
    fn resolves_command() {
        fn resolver(_: &Intent, _: &mut Context) -> Result<i32> { Ok(1) }
        let mut ctx = Context::default();
        let app = Command::with_name("a").with_resolver(resolver);
        assert_eq!(app.run_args(vec![] as Vec<String>, &mut ctx), Ok(1));
        let app = Command::with_name("a").with_resolver(|_, _| { Ok(2) });
        assert_eq!(app.run_args(vec![] as Vec<String>, &mut ctx), Ok(2));
    }

    #[test]
    fn resolves_subcommand() {
        fn resolver0(_: &Intent, _: &mut Context) -> Result<i32> { Ok(1) };
        fn resolver1(_: &Intent, _: &mut Context) -> Result<i32> { Ok(2) };
        let mut ctx = Context::default();
        let app = Command::with_name("a")
            .with_subcommand(Command::with_name("b").with_resolver(resolver0))
            .with_resolver(resolver1);
        assert_eq!(app.run_args(vec!["b"], &mut ctx), Ok(1));
    }

    #[test]
    fn handles_error() {
        fn resolver(_: &Intent, _: &mut Context) -> Result<i32> { Err(Error::default()) }
        fn handler(_error: Error, _: &mut Context) -> Result<i32> { Ok(1) }
        let mut ctx = Context::default();
        let app = Command::with_name("a").with_resolver(resolver).with_handler(handler);
        assert_eq!(app.run_args(vec![] as Vec<String>, &mut ctx), Ok(1));
    }
}