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
// License: see LICENSE file at root directory of `master` branch

//! # Command

use std::{
    borrow::Cow,
    fmt,
};

use super::{Cfg, I18n, Opt};

/// # Command
///
/// ## Examples
///
/// ```
/// use std::borrow::Cow;
/// use dia_args::docs::Cmd;
///
/// // All these constants are convenient while working with Args.
/// // And you can also use them for Cmd.
///
/// const CMD_HELP: &str = "help";
/// const CMD_HELP_DOCS: Cow<str> = Cow::Borrowed("Prints help and exits.");
///
/// let _cmd = Cmd::new(CMD_HELP, CMD_HELP_DOCS, None);
/// // Here you can pass this command to Docs::new(...)
/// ```
#[derive(Clone)]
pub struct Cmd<'a> {
    name: &'a str,
    docs: Cow<'a, str>,
    options: Option<Vec<Cow<'a, Opt<'a>>>>,
}

impl<'a> Cmd<'a> {

    /// # Makes new instance
    pub const fn new(name: &'a str, docs: Cow<'a, str>, options: Option<Vec<Cow<'a, Opt<'a>>>>) -> Self {
        Self {
            name,
            docs,
            options,
        }
    }

    /// # Formats self
    pub fn format(&self, cfg: &Cfg, i18n: &I18n, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        // Name
        let tab = cfg.tab_len().saturating_mul(cfg.tab_level().into());
        f.write_str(&super::format(self.name, tab, cfg.columns()))?;
        f.write_str(super::LINE_BREAK)?;

        // Docs
        let cfg = cfg.increment_level();
        let tab = cfg.tab_len().saturating_mul(cfg.tab_level().into());
        f.write_str(&super::format(&self.docs, tab, cfg.columns()))?;
        f.write_str(super::LINE_BREAK)?;

        // Options
        if let Some(options) = self.options.as_ref() {
            f.write_str(&super::format(i18n.options.to_uppercase(), tab, cfg.columns()))?;
            f.write_str(super::LINE_BREAK)?;

            let cfg = cfg.increment_level();
            for option in options {
                option.format(&cfg, &i18n, f)?;
            }
        }

        Ok(())
    }

}

impl<'a> From<Cmd<'a>> for Cow<'a, Cmd<'a>> {

    fn from(cmd: Cmd<'a>) -> Self {
        Cow::Owned(cmd)
    }

}

impl<'a> From<&'a Cmd<'a>> for Cow<'a, Cmd<'a>> {

    fn from(cmd: &'a Cmd<'a>) -> Self {
        Cow::Borrowed(cmd)
    }

}