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

//! # Kit for documentation
//!
//! ## Examples
//!
//! ```
//! use dia_args::docs::{Cfg, Cmd, Docs, I18n, Opt};
//!
//! const CMD_HELP: &str = "help";
//! const CMD_HELP_DOCS: &str = "Prints help and exits.";
//!
//! const CMD_VERSION: &str = "version";
//! const CMD_VERSION_DOCS: &str = "Prints version and exits.";
//!
//! const CMD_DO_SOMETHING: &str = "do-something";
//! const CMD_DO_SOMETHING_DOCS: &str = concat!(
//!     "This command does something.\n",
//!     "\n",
//!     "It might NOT do that thing. If you encounter any problems,",
//!     " please contact developers.\n",
//! );
//!
//! const ARG_THIS: &[&str] = &["-t", "--this"];
//! const ARG_THIS_DEFAULT: bool = true;
//! const ARG_THIS_DOCS: &str = "This argument has 2 names.";
//!
//! const ARG_THAT: &[&str] = &["--that"];
//! const ARG_THAT_VALUES: &[u8] = &[99, 100];
//! const ARG_THAT_DEFAULT: u8 = ARG_THAT_VALUES[0];
//! const ARG_THAT_DOCS: &str = "This argument has 1 single name.";
//!
//! let help_cmd = Cmd::new(CMD_HELP, CMD_HELP_DOCS, None);
//! let version_cmd = Cmd::new(CMD_VERSION, CMD_VERSION_DOCS, None);
//!
//! let do_something_cmd_options = &[
//!     &Opt::new(ARG_THIS, false, None, Some(&ARG_THIS_DEFAULT), ARG_THIS_DOCS),
//!     &Opt::new(
//!         ARG_THAT, true, Some(dia_args::display!(ARG_THAT_VALUES)), Some(&ARG_THAT_DEFAULT),
//!         ARG_THAT_DOCS,
//!     ),
//! ];
//! let do_something_cmd = Cmd::new(
//!     CMD_DO_SOMETHING, CMD_DO_SOMETHING_DOCS, Some(do_something_cmd_options),
//! );
//!
//! let commands = &[&help_cmd, &version_cmd, &do_something_cmd];
//! let docs = Docs::new(
//!     // Name
//!     "The-Program",
//!     // Docs
//!     "This is the Program",
//!     // Configuration
//!     Cfg::default(),
//!     // Internatinonalization
//!     I18n::default(),
//!     // Program options
//!     None,
//!     // Commands
//!     Some(commands),
//! );
//! docs.print();
//!
//! // This does the same as above command:
//! // println!("{}", docs);
//! ```

mod cfg;
mod cmd;
mod i18n;
mod opt;

use std::{
    fmt,
};

pub use cfg::*;
pub use cmd::*;
pub use i18n::*;
pub use opt::*;

#[cfg(unix)]
const LINE_BREAK: &str = "\n";

#[cfg(not(unix))]
const LINE_BREAK: &str = "\r\n";

/// # Borrows an array of [`Display`][::Display] as a vector of [`&Display`][::Display]
///
/// ## Examples
///
/// ```
/// const FLAGS: &[u8] = &[0, 1, 2];
///
/// let v = dia_args::display!(FLAGS);
/// for i in v {
///     println!("{}", i);
/// }
/// ```
/// [::Display]: https://doc.rust-lang.org/std/fmt/trait.Display.html
#[macro_export]
macro_rules! display { ($e: expr) => {{
    $e.iter().map(|i| i as &std::fmt::Display).collect::<Vec<_>>()
}}}

/// # Documentation
pub struct Docs<'a> {
    name: &'a str,
    docs: &'a str,
    cfg: Cfg,
    i18n: I18n<'a>,
    options: Option<&'a [&'a Opt<'a>]>,
    commands: Option<&'a [&'a Cmd<'a>]>,
}

impl<'a> Docs<'a> {

    /// # Makes new instance
    pub fn new(name: &'a str, docs: &'a str, cfg: Cfg, i18n: I18n<'a>, options: Option<&'a [&'a Opt<'a>]>, commands: Option<&'a [&'a Cmd<'a>]>)
    -> Self {
        Self {
            name,
            docs,
            cfg,
            i18n,
            options,
            commands,
        }
    }

    /// # Prints this documentation to stdout
    pub fn print(&self) {
        println!("{}", self);
    }

}

impl fmt::Display for Docs<'_> {

    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        let tab = self.cfg.tab_len().saturating_mul(self.cfg.tab_level().into());
        let next_tab = self.cfg.tab_len().saturating_mul(self.cfg.tab_level().saturating_add(1).into());

        // Name
        f.write_str(&format(self.name, tab, self.cfg.columns()))?;
        f.write_str(LINE_BREAK)?;

        // Docs
        f.write_str(&format(self.docs, next_tab, self.cfg.columns()))?;
        f.write_str(LINE_BREAK)?;

        // Options
        f.write_str(&format(self.i18n.options, tab, self.cfg.columns()))?;
        f.write_str(LINE_BREAK)?;
        match self.options {
            Some(options) => {
                let cfg = self.cfg.increment_level();
                for option in options {
                    option.format(&cfg, &self.i18n, f)?;
                }
            },
            None => {
                f.write_str(&format(self.i18n.no_options, next_tab, self.cfg.columns()))?;
                f.write_str(LINE_BREAK)?;
            },
        };

        // Commands
        f.write_str(&format(self.i18n.commands, tab, self.cfg.columns()))?;
        f.write_str(LINE_BREAK)?;
        match self.commands {
            Some(commands) => {
                let cfg = self.cfg.increment_level();
                for command in commands {
                    command.format(&cfg, &self.i18n, f)?;
                }
            },
            None => {
                f.write_str(&format(self.i18n.no_commands, next_tab, self.cfg.columns()))?;
                f.write_str(LINE_BREAK)?;
            },
        };

        Ok(())
    }

}

/// # Formats a string
fn format(s: &str, size_of_indentation: usize, columns: usize) -> String {
    if s.is_empty() || size_of_indentation >= columns {
        return String::new();
    }

    let mut result = String::with_capacity(s.len());
    let tab = ' '.to_string().repeat(size_of_indentation);

    for line in s.lines() {
        let mut col = 0;
        for (idx, word) in line.split_whitespace().enumerate() {
            if idx == 0 {
                result.push_str(&tab);
                col = size_of_indentation;
            }

            let chars: Vec<_> = word.chars().collect();
            match col + match col == size_of_indentation { true => 0, false => 1 } + chars.len() <= columns {
                true => {
                    if col > size_of_indentation {
                        result.push(' ');
                        col += 1;
                    }
                    col += chars.len();
                    result.extend(chars.into_iter());
                },
                false => for (i, c) in chars.into_iter().enumerate() {
                    if i == 0 || col >= columns {
                        result.push_str(LINE_BREAK);
                        result.push_str(&tab);
                        col = size_of_indentation;
                    }
                    result.push(c);
                    col += 1;
                },
            };
        }

        result.push_str(LINE_BREAK);
    }

    result
}