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
use std::collections::HashMap;

/// Enum that define the variants of the CLI option handlers.
///
/// There are 2 types of this variant: `Plain` and `WithArg`.
///
/// `Plain` means that your handler doesn't need arguments to run.
/// For example, a handler to show help message or to output current version.
///
/// `WithArg` means that your handler is a function that need arguments to run.
/// For example, a handler to use certain user to run the command.
///
/// Note that every functions that will be registered as action handler
/// must pass a variable with type `&Handler` as its first parameter.
/// This is required to make every action handler becomes _stateful_
/// (means that it can parse and use all of the arguments passed to the
/// CLI program).
///
/// # Example
///
/// ```rust
/// use medusa::Handler;
///
/// // without arguments (using `Plain` variant)
/// // the usage would be:
/// // Variant::Plain(hello);
/// fn hello(handler: &Handler) {
///   println!("Hello, world!");
/// }
///
/// // with arguments (using `WithArg` variant)
/// // the usage would be:
/// // Variant::WithArg(echo);
/// fn echo(handler: &Handler, payload: String) {
///   println!("Got payload : {}", payload);
/// }
/// ```
#[derive(Clone)]
pub enum Variant {
    Plain(fn(&Handler)),
    WithArg(fn(&Handler, String)),
}

/// Enum that define the type (or kind) of option arguments.
///
/// There are 2 types of this variant: `Flag` and `Content`.
///
/// `Flag` means that your arguments are only a variable that tells
/// if it is exist (`true`) or not (`false`), since it only contains
/// boolean value.
/// For example, option parameter `--wait` will make your CLI
/// program wait until the process are finished, otherwise it will
/// run as a background process. Here, option `--wait` will have
/// value of `true` because it is called when executing the program.
///
/// `Content` means that your arguments consist of a `String` instance
/// that can be processed later (hence the name, `Content`).
/// For example, option parameter `--user nobody` will make your CLI
/// program run as user `nobody`. Here, option `--user` will have
/// argument value of `nobody` since this argument is passed to the
/// option `--user`.
#[derive(Clone)]
pub enum ArgType {
    Flag(bool),
    Content(String),
}

/// Struct that defines a CLI option handler in a programmatic way.
#[derive(Clone)]
pub struct Handler {
    actions: Option<HashMap<String, Variant>>,
    hints: Option<HashMap<String, String>>,
    values: Option<HashMap<String, ArgType>>,
}

impl Handler {
    /// Create a new empty `Handler` instance.
    ///
    /// # Example
    ///
    /// ```
    /// use medusa::Handler;
    ///
    /// // code ...
    ///
    /// let mut handler: Handler = Handler::new();
    /// ```
    pub fn new() -> Handler {
        Handler {
            actions: None,
            hints: None,
            values: None,
        }
    }

    /// Manually parse the options and arguments passed to the CLI program.
    ///
    /// This method **meant to be called internally** by `CommandLine` instance,
    /// and indeed it is currently being called internally.
    ///
    /// # Example
    ///
    /// ```
    /// use medusa::Handler;
    ///
    /// use std::env;
    ///
    /// // code ...
    ///
    /// let mut handler: Handler = Handler::new();
    /// let result = handler.parse_args(env::args().collect());
    /// println!("result : {:?}", result);
    /// ```
    pub fn parse_args(&mut self, args: Vec<String>) -> Result<(), String> {
        if let Some(map) = &self.actions {
            if let None = &mut self.values {
                let mut new_values: HashMap<String, ArgType> = HashMap::new();
                let mut option_key: Option<String> = None;
                let mut status: Result<(), String> = Ok(());

                let args = args.iter().skip(1);
                for option in args {
                    match map.get(option) {
                        None => {
                            if let Some(key) = &option_key {
                                new_values
                                    .insert(key.clone(), ArgType::Content(option.to_string()));
                                status = Ok(());
                            } else {
                                let mut msg = String::from("error parsing argument : ");
                                msg.push_str(&option.as_str());
                                return Err(msg);
                            }
                        }
                        Some(variant) => {
                            match variant {
                                Variant::Plain(_) => {
                                    new_values.insert(option.to_string(), ArgType::Flag(true));
                                }
                                Variant::WithArg(_) => {
                                    // save for further processing

                                    let mut msg = String::from("handler does not have value : ");
                                    msg.push_str(&option.as_str());
                                    status = Err(msg);

                                    option_key = Some(option.to_string());
                                }
                            }
                        }
                    }
                }

                // only set to struct if it contains minimum of single element
                if new_values.len() > 0 {
                    self.values = Some(new_values);
                }

                status
            } else {
                return Err(String::from("handler values not empty"));
            }
        } else {
            Err(String::from("no action handlers found"))
        }
    }

    /// Get the argument of CLI option as its `key`.
    ///
    /// This function can be called in the inner side of any
    /// action handler function definition to get the argument
    /// of the parameter option specified. The value return are
    /// the `ArgType` instance. See its documentation for details.
    /// See also the `stateful` example for code snippet.
    ///
    /// # Example
    ///
    /// ```
    /// use medusa::{ArgType, Handler};
    ///
    /// // code ...
    ///
    /// fn print_twice(handler: &Handler) {
    ///     if let Some(argtype) = handler.get_arg("--echo") {
    ///         if let ArgType::Content(payload) = argtype {
    ///             println!("printed once more : {}", payload);
    ///         }
    ///     }
    /// }
    /// ```
    pub fn get_arg(&self, key: &str) -> Option<ArgType> {
        match &self.values {
            None => None,
            Some(value_map) => {
                if let Some(argtype) = value_map.get(key) {
                    return Some(argtype.clone());
                } else {
                    return None;
                }
            }
        }
    }

    /// Get action handler list in form of `HashMap` from the current
    /// `Handler` instance.
    ///
    /// # Example
    ///
    /// ```
    /// use medusa::{Handler, Variant};
    ///
    /// use std::collections::HashMap;
    ///
    /// let mut handler: Handler = Handler::new();
    /// // code ...
    ///
    /// if let Some(map) = handler.get_actions() {
    ///     println!("Got some actions here!");
    /// } else {
    ///     println!("No actions defined!");
    /// }
    /// ```
    pub fn get_actions(&self) -> Option<&HashMap<String, Variant>> {
        if let Some(map) = &self.actions {
            return Some(map);
        } else {
            return None;
        }
    }

    /// Clone action handler list in form of `HashMap` from the current
    /// `Handler` instance.
    ///
    /// Note that the return value from this method
    /// are a `HashMap` instance wrapped in `Option` instance, instead
    /// of _reference_ to a `HashMap` instance.
    ///
    /// # Example
    ///
    /// ```
    /// use medusa::{Handler, Variant};
    ///
    /// use std::collections::HashMap;
    ///
    /// let mut handler: Handler = Handler::new();
    /// // code ...
    ///
    /// if let Some(map) = handler.clone_actions() {
    ///     println!("Got some cloned actions here!");
    /// } else {
    ///     println!("No actions defined!");
    /// }
    /// ```
    pub fn clone_actions(&self) -> Option<HashMap<String, Variant>> {
        if let Some(map) = &self.actions {
            return Some((*map).clone());
        } else {
            return None;
        }
    }

    /// Consume `self` instance and return the `HashMap` containing
    /// consumed action handlers wrapped with `Option` instance.
    ///
    /// Note that the current instance are consumed, hence
    /// it won't be able to be used again unless it was cloned first.
    ///
    /// # Example
    ///
    /// ```
    /// use medusa::{Handler, Variant};
    ///
    /// use std::collections::HashMap;
    ///
    /// let mut handler: Handler = Handler::new();
    /// // code ...
    ///
    /// if let Some(map) = handler.extract_actions() {
    ///     println!("Got some cloned actions here!");
    /// } else {
    ///     println!("No actions defined!");
    /// }
    /// ```
    pub fn extract_actions(self) -> Option<HashMap<String, Variant>> {
        if let Some(map) = self.actions {
            return Some(map);
        } else {
            return None;
        }
    }

    /// Get action hint list in form of `HashMap` from the current
    /// `Handler` instance.
    ///
    /// # Example
    ///
    /// ```
    /// use medusa::{Handler, Variant};
    ///
    /// use std::collections::HashMap;
    ///
    /// let mut handler: Handler = Handler::new();
    /// // code ...
    ///
    /// if let Some(map) = handler.get_hints() {
    ///     println!("Got some hints here!");
    /// } else {
    ///     println!("No hints defined!");
    /// }
    /// ```
    pub fn get_hints(&self) -> Option<&HashMap<String, String>> {
        if let Some(map) = &self.hints {
            return Some(map);
        } else {
            return None;
        }
    }

    /// Clone action hint list in form of `HashMap` from the current
    /// `Handler` instance.
    ///
    /// Note that the return value from this method
    /// are a `HashMap` instance wrapped in `Option` instance, instead
    /// of _reference_ to a `HashMap` instance.
    ///
    /// # Example
    ///
    /// ```
    /// use medusa::{Handler, Variant};
    ///
    /// use std::collections::HashMap;
    ///
    /// let mut handler: Handler = Handler::new();
    /// // code ...
    ///
    /// if let Some(map) = handler.clone_hints() {
    ///     println!("Got some cloned hints here!");
    /// } else {
    ///     println!("No hints defined!");
    /// }
    /// ```
    pub fn clone_hints(&self) -> Option<HashMap<String, String>> {
        if let Some(map) = &self.hints {
            return Some((*map).clone());
        } else {
            return None;
        }
    }

    /// Consume `self` instance and return the `HashMap` containing
    /// consumed action hints wrapped with `Option` instance.
    ///
    /// Note that the current instance are consumed, hence
    /// it won't be able to be used again unless it was cloned first.
    ///
    /// # Example
    ///
    /// ```
    /// use medusa::{Handler, Variant};
    ///
    /// use std::collections::HashMap;
    ///
    /// let mut handler: Handler = Handler::new();
    /// // code ...
    ///
    /// if let Some(map) = handler.extract_hints() {
    ///     println!("Got some cloned hints here!");
    /// } else {
    ///     println!("No hints defined!");
    /// }
    /// ```
    pub fn extract_hints(self) -> Option<HashMap<String, String>> {
        if let Some(map) = self.hints {
            return Some(map);
        } else {
            return None;
        }
    }

    /// Add an action for CLI option handler. Note that you must also provide
    /// function hint for this option handler. This hint will be shown if arguments
    /// passed to this handler are invalid, or when the CLI is calling the `--help`
    /// option. This kind of hint usually a single line of `String`, but it is not
    /// restricted for multi-line `String`.
    ///
    /// # Example
    ///
    /// ```
    /// use medusa::{Handler, Variant};
    ///
    /// // code ...
    ///
    /// fn show_help(handler: &Handler) {
    ///     println!("This is help message!");
    /// }
    ///
    /// let mut handler: Handler = Handler::new();
    /// handler.add(
    ///     String::from("--help"),
    ///     Variant::Plain(show_help),
    ///     String::from("Show this help message.")
    /// );
    /// ```
    pub fn add(&mut self, parameter: String, action: Variant, hint: String) {
        match &mut self.actions {
            None => {
                let mut map: HashMap<String, Variant> = HashMap::new();
                map.insert(parameter.clone(), action);
                self.actions = Some(map);
            }
            Some(map) => {
                map.insert(parameter.clone(), action);
            }
        }
        match &mut self.hints {
            None => {
                let mut map: HashMap<String, String> = HashMap::new();
                map.insert(parameter, hint);
                self.hints = Some(map);
            }
            Some(map) => {
                map.insert(parameter, hint);
            }
        }
    }

    /// Append `Handler` instance passed to the calling `Handler` instance.
    ///
    /// # Example
    ///
    /// ```
    /// use medusa::{Handler, Variant};
    ///
    /// // code ...
    ///
    /// let mut handler: Handler = Handler::new();
    /// // code ...
    ///
    /// let mut other_handler: Handler = Handler::new();
    /// // code ...
    ///
    /// // append the first handler to the second
    /// other_handler.append(handler);
    /// ```
    pub fn append(&mut self, handler: Handler) {
        if let Some(target_actions) = handler.clone_actions() {
            if let Some(current_actions) = &mut self.actions {
                current_actions.extend(target_actions);
            }
        }
        if let Some(target_hints) = handler.extract_hints() {
            if let Some(current_hints) = &mut self.hints {
                current_hints.extend(target_hints);
            }
        }
    }
}