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

//! # Kit for documentation
//!
//! ## Examples
//!
//! ```
//! use std::borrow::Cow;
//! use dia_args::docs::{self, Cfg, Cmd, Docs, I18n, Opt, Project};
//!
//! const CMD_HELP: &str = "help";
//! const CMD_HELP_DOCS: Cow<str> = Cow::Borrowed("Prints help and exits.");
//!
//! const CMD_VERSION: &str = "version";
//! const CMD_VERSION_DOCS: Cow<str> = Cow::Borrowed("Prints version and exits.");
//!
//! const CMD_DO_SOMETHING: &str = "do-something";
//! const CMD_DO_SOMETHING_DOCS: Cow<str> = Cow::Borrowed(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: Cow<str> = Cow::Borrowed("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: Cow<str> = Cow::Borrowed("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 = Cmd::new(
//!     CMD_DO_SOMETHING, CMD_DO_SOMETHING_DOCS,
//!     Some(dia_args::make_opts![
//!         Opt::new(ARG_THIS, false, None, Some(&ARG_THIS_DEFAULT), ARG_THIS_DOCS),
//!         Opt::new(
//!             ARG_THAT, true,
//!             Some(docs::make_cow_strings(ARG_THAT_VALUES)), Some(&ARG_THAT_DEFAULT),
//!             ARG_THAT_DOCS,
//!         ),
//!     ]),
//! );
//!
//! let mut docs = Docs::new(
//!     // Name
//!     "The-Program".into(),
//!     // Docs
//!     "This is the Program".into(),
//! );
//! docs.commands = Some(dia_args::make_cmds![help_cmd, version_cmd, do_something_cmd,]);
//! docs.project = Some(Project::new("https://project-home", "Nice License", None));
//! docs.print();
//!
//! // This does the same as above command:
//! // println!("{}", docs);
//! ```

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

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

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";

/// # Makes a vector of [`Cow<'_, Cmd<'_>>`][::Cmd] from a list of either `Cmd` or `&Cmd`
///
/// [::Cmd]: docs/struct.Cmd.html
#[macro_export]
macro_rules! make_cmds {
    ($($e: expr,)+) => {{
        let mut result = vec![];
        $(
            let cmd: std::borrow::Cow<dia_args::docs::Cmd> = $e.into();
            result.push(cmd);
        )+
        result
    }}
}

/// # Makes a vector of [`Cow<'_, Opt<'_>>`][::Opt] from a list of either `Opt` or `&Opt`
///
/// [::Opt]: docs/struct.Opt.html
#[macro_export]
macro_rules! make_opts {
    ($($e: expr,)+) => {{
        let mut result = vec![];
        $(
            let opt: std::borrow::Cow<dia_args::docs::Opt> = $e.into();
            result.push(opt);
        )+
        result
    }}
}

/// # Makes a vector of [`Cow<'_, str>`][r::Cow] from input slice of [`Display`][r::Display]'s
///
/// ## Examples
///
/// ```
/// use dia_args::docs;
///
/// for s in docs::make_cow_strings(&[0, 1, 2]) {
///     println!("{}", s);
/// }
/// ```
///
/// [r::Cow]: https://doc.rust-lang.org/std/borrow/enum.Cow.html
/// [r::Display]: https://doc.rust-lang.org/std/fmt/trait.Display.html
pub fn make_cow_strings<T>(slice: &[T]) -> Vec<Cow<'_, str>> where T: Display {
    slice.iter().map(|e| Cow::Owned(e.to_string())).collect()
}

/// # Documentation
pub struct Docs<'a> {

    /// # Name
    pub name: Cow<'a, str>,

    /// # Documentation
    pub docs: Cow<'a, str>,

    /// # Configuration
    pub cfg: Cfg,

    /// # Internatinonalization
    pub i18n: I18n<'a>,

    /// # Options
    pub options: Option<Vec<Cow<'a, Opt<'a>>>>,

    /// # Commands
    pub commands: Option<Vec<Cow<'a, Cmd<'a>>>>,

    /// # Project
    pub project: Option<Project<'a>>,

}

impl<'a> Docs<'a> {

    /// # Makes new instance with default configurations
    pub fn new(name: Cow<'a, str>, docs: Cow<'a, str>) -> Self {
        Self {
            name,
            docs,
            cfg: Cfg::default(),
            i18n: I18n::default(),
            options: None,
            commands: None,
            project: None,
        }
    }

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

}

impl 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.to_uppercase(), tab, self.cfg.columns()))?;
        f.write_str(LINE_BREAK)?;
        match self.options.as_ref() {
            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.to_uppercase(), tab, self.cfg.columns()))?;
        f.write_str(LINE_BREAK)?;
        match self.commands.as_ref() {
            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)?;
            },
        };

        // Project
        if let Some(project) = self.project.as_ref() {
            f.write_str(&format(self.i18n.project.to_uppercase(), tab, self.cfg.columns()))?;
            f.write_str(LINE_BREAK)?;
            f.write_str(&format(format!("- {}: {}", self.i18n.home, project.home), next_tab, self.cfg.columns()))?;
            f.write_str(&format(format!("- {}: {}", self.i18n.license, project.license_name), next_tab, self.cfg.columns()))?;
            if let Some(license) = project.license.as_ref() {
                f.write_str(LINE_BREAK)?;
                f.write_str(&format(license, next_tab, self.cfg.columns()))?;
            }
        }

        Ok(())
    }

}

/// # Project information
#[derive(Debug)]
pub struct Project<'a> {
    home: &'a str,
    license_name: &'a str,
    license: Option<Cow<'a, str>>,
}

impl<'a> Project<'a> {

    /// # Makes new instance
    pub const fn new(home: &'a str, license_name: &'a str, license: Option<Cow<'a, str>>) -> Self {
        Self {
            home,
            license_name,
            license,
        }
    }

}

/// # Formats a string
fn format<S>(s: S, size_of_indentation: usize, columns: usize) -> String where S: AsRef<str> {
    let s = s.as_ref();

    if s.is_empty() || size_of_indentation >= columns {
        return String::new();
    }

    let mut result = String::with_capacity(s.len().saturating_add(s.len() / 10));
    let tab = concat!(' ').repeat(size_of_indentation);

    for line in s.lines() {
        let line_indentation = match line.split_whitespace().next() {
            Some(word) => match word.chars().next() {
                Some('-') | Some('+') | Some('*') | Some('~') | Some('$') | Some('#') =>
                    Some(concat!(' ').repeat(word.chars().count().saturating_add(1))),
                _ => None,
            },
            None => None,
        };

        let mut col = 0;
        for (idx, word) in line.split_whitespace().enumerate() {
            if idx == 0 {
                result += &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 += LINE_BREAK;
                        result += &tab;
                        col = size_of_indentation;
                        if let Some(line_indentation) = line_indentation.as_ref() {
                            result += line_indentation;
                            col += line_indentation.len();
                        }
                    }
                    result.push(c);
                    col += 1;
                },
            };
        }

        result += LINE_BREAK;
    }

    result
}