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
/*
==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--
Dia-Args
Copyright (C) 2018-2019, 2021-2024 Anonymous
There are several releases over multiple years,
they are listed as ranges, such as: "2018-2019".
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--
*/
//! # Kit for documentation
//!
//! ## Examples
//!
//! ```
//! use std::borrow::Cow;
//! use dia_args::docs::{self, Cfg, Cmd, Docs, I18n, Option, 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 OPTION_THIS: &[&str] = &["-t", "--this"];
//! const OPTION_THIS_DEFAULT: bool = true;
//! const OPTION_THIS_DOCS: Cow<str> = Cow::Borrowed("This argument has 2 names.");
//!
//! const OPTION_THAT: &[&str] = &["--that"];
//! const OPTION_THAT_VALUES: &[u8] = &[99, 100];
//! const OPTION_THAT_DEFAULT: u8 = OPTION_THAT_VALUES[0];
//! const OPTION_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_options![
//! Option::new(OPTION_THIS, false, &[], Some(OPTION_THIS_DEFAULT), OPTION_THIS_DOCS),
//! Option::new(OPTION_THAT, true, OPTION_THAT_VALUES, Some(OPTION_THAT_DEFAULT), OPTION_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(Some("https://project-home"), "Nice License", None));
//! docs.print()?;
//!
//! // This does the same as above command:
//! // println!("{}", docs);
//!
//! # Ok::<_, std::io::Error>(())
//! ```
mod cfg;
mod cmd;
mod i18n;
mod option;
use {
core::{
fmt::{self, Display},
option::Option as RustOption,
},
std::borrow::Cow,
};
pub use self::{
cfg::*,
cmd::*,
i18n::*,
option::*,
};
#[cfg(unix)]
const LINE_BREAK: &str = "\n";
#[cfg(not(unix))]
const LINE_BREAK: &str = "\r\n";
/// # Makes a vector of [`Cow<'_, Cmd<'_>>`][struct:Cmd] from a list of either `Cmd` or `&Cmd`
///
/// [struct:Cmd]: docs/struct.Cmd.html
#[macro_export]
macro_rules! make_cmds {
($($e: expr),+ $(,)?) => {{
vec!($(std::borrow::Cow::<dia_args::docs::Cmd>::from($e),)+)
}};
}
/// # Makes a vector of [`Cow<'_, Option<'_>>`][struct:Option] from a list of either `Option` or `&Option`
///
/// [struct:Option]: docs/struct.Option.html
#[macro_export]
macro_rules! make_options {
($($e: expr),+ $(,)?) => {{
vec!($(std::borrow::Cow::<dia_args::docs::Option>::from($e),)+)
}};
}
/// # No values
///
/// This can be used conveniently with [`Option`][struct:Option].
///
/// ## Examples
///
/// ```
/// use std::borrow::Cow;
/// use dia_args::docs::{NO_VALUES, Option};
///
/// const OPTION_PORT: &[&str] = &["-p", "--port"];
/// const OPTION_PORT_DOCS: Cow<str> = Cow::Borrowed("Port for server.");
///
/// let _option = Option::new(OPTION_PORT, false, NO_VALUES, None, OPTION_PORT_DOCS);
/// ```
///
/// [struct:Option]: struct.Option.html
pub const NO_VALUES: &[&str] = &[];
/// # 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: RustOption<Vec<Cow<'a, Option<'a>>>>,
/// # Commands
pub commands: RustOption<Vec<Cow<'a, Cmd<'a>>>>,
/// # Project
pub project: RustOption<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) -> crate::Result<()> {
crate::lock_write_out(self.to_string().trim());
crate::lock_write_out([b'\n']);
Ok(())
}
}
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)?;
if let Some(home) = project.home {
f.write_str(&format(format!("- {}: {}", self.i18n.home, 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: RustOption<&'a str>,
license_name: &'a str,
license: RustOption<Cow<'a, str>>,
}
impl<'a> Project<'a> {
/// # Makes new instance
pub const fn new(home: RustOption<&'a str>, license_name: &'a str, license: RustOption<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();
if col + if col == size_of_indentation { 0 } else { 1 } + chars.len() <= columns {
if col > size_of_indentation {
result.push(' ');
col += 1;
}
col += chars.len();
result.extend(chars.into_iter());
} else {
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
}