arkham/src/opt.rs

131 lines
3.4 KiB
Rust

#[derive(Debug)]
pub enum OptError {
InvalidOpt(String),
}
#[derive(Clone, Debug)]
pub struct Opt {
pub name: String,
pub short: Option<String>,
pub long: Option<String>,
pub desc: Option<String>,
pub(crate) kind: OptKind,
}
impl Opt {
/// Create a boolean opt that is present or not and does not accept additional arguments
///
/// Example:
/// ```rust
/// use arkham::{Opt, App};
/// App::new().opt(Opt::flag("verbose").short("v").long("verbose"));
///```
pub fn flag(name: &str) -> Self {
Self {
name: name.into(),
short: None,
long: None,
kind: OptKind::Flag,
desc: None,
}
}
/// Create a opt that accepts additioanl arguments
///
/// Example:
/// ```rust
/// use arkham::{Opt, App};
/// App::new().opt(Opt::scalar("user").short("u").long("user"));
///```
pub fn scalar(name: &str) -> Self {
Self {
name: name.into(),
short: None,
long: None,
kind: OptKind::String,
desc: None,
}
}
/// Sets the short flag that can be used with -x
///
/// Example:
/// ```rust
/// use arkham::{Opt, App};
/// App::new().opt(Opt::scalar("user").short("u").long("user"));
///```
pub fn short(mut self, short: &str) -> Self {
self.short = Some(short.into());
self
}
/// Sets the long flag that can be used with --xxxxx
///
/// Example:
/// ```rust
/// use arkham::{Opt, App};
/// App::new().opt(Opt::scalar("user").short("u").long("user"));
///```
pub fn long(mut self, long: &str) -> Self {
self.long = Some(long.into());
self
}
/// Sets the description for the option. This is displayed when listing via help commands
///
/// Example:
/// ```rust
/// use arkham::{Opt, App};
/// App::new()
/// .opt(
/// Opt::scalar("user")
/// .short("u")
/// .long("user")
/// .desc("The user to perform the action against")
/// );
///```
pub fn desc(mut self, desc: &str) -> Self {
self.desc = Some(desc.into());
self
}
pub(crate) fn usage(&self) -> String {
match self.kind {
OptKind::Flag => {
let short = self
.short
.as_ref()
.map(|s| format!("-{}", s))
.unwrap_or_else(String::new);
let long = self
.long
.as_ref()
.map(|s| format!("--{}", s))
.unwrap_or_else(String::new);
vec![short, long].join(",").trim_matches(',').to_string()
}
OptKind::String => {
let short = self
.short
.as_ref()
.map(|s| format!("-{} [value]", s))
.unwrap_or_else(String::new);
let long = self
.long
.as_ref()
.map(|s| format!("--{} [value]", s))
.unwrap_or_else(String::new);
vec![short, long].join(",").trim_matches(',').to_string()
}
}
}
}
#[derive(Clone, Debug)]
pub(crate) enum OptKind {
Flag,
String,
}