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 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
#![doc = include_str!("../README.md")]
#![warn(clippy::pedantic)]
#![allow(clippy::needless_pass_by_value)]
#![allow(clippy::must_use_candidate)]
#![allow(clippy::redundant_closure_for_method_calls)]
pub mod custom;
pub mod prelude;
use std::env;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::num::{ParseFloatError, ParseIntError};
use std::sync::{Arc, Mutex};
pub mod tag;
use tag::Full;
mod error;
pub use error::ArgParseError;
mod types;
use types::{ArgumentType, ArgumentValueType};
#[cfg(test)]
mod test;
/// A value passed to an argument. This will always
/// match the value returned from [`ArgumentType::arg_type`].
///
/// When implementing your own types, you
/// almost always want [`ArgumentValue::String`].
#[derive(Clone, Debug, PartialEq)]
pub enum ArgumentValue {
Bool(bool),
String(String),
I64(i64),
U64(u64),
Float(f64),
}
impl ArgumentValue {
pub fn typ(&self) -> ArgumentValueType {
match self {
Self::Bool(_) => ArgumentValueType::Bool,
Self::String(_) => ArgumentValueType::String,
Self::I64(_) => ArgumentValueType::I64,
Self::U64(_) => ArgumentValueType::U64,
Self::Float(_) => ArgumentValueType::Float,
}
}
}
#[derive(Clone, Debug)]
struct InternalArgument {
tag: Full,
typ: ArgumentValueType,
val: Option<ArgumentValue>,
}
/// A reference to an argument. Use this to
/// retrieve the value of an argument.
pub struct ArgumentRef<'a, T: ArgumentType> {
parser: &'a ArgumentParser,
i: usize,
_marker: PhantomData<T>,
}
impl<'a, T: ArgumentType> ArgumentRef<'a, T> {
/// Retrieve the value of the argument.
/// Consumes the `ArgumentRef`.
///
/// # Errors
///
/// If the argument type fails to parse,
/// this will return that argument types error.
///
/// For `String` and `bool`, this can never fail.
pub fn get(self) -> Result<T, T::Error> {
self.get_keep()
}
/// Retrieve the value of the argument.
/// Does not consume the `ArgumentRef`.
///
/// # Errors
///
/// See [`get`] for possible errors.
#[allow(clippy::missing_panics_doc)]
pub fn get_keep(&self) -> Result<T, T::Error> {
let args = self.parser.args.lock().unwrap();
let Some(val) = args[self.i].clone().val else {
return if let Some(default) = T::default_value() {
Ok(default)
} else {
Err(T::Error::default())
};
};
T::from_value(val)
}
}
/// The structure that actually parses all your
/// arguments. Use [`ArgumentParser::add`] to
/// register arguments and get [`ArgumentRef`]s.
///
/// Internally, the parser is a shambling heap of
/// `Arc<Mutex<HeapAllocatedValue>>`. This is to
/// enable the current API in a thread-safe manner.
/// In the future, there may be a single-threaded
/// feature that disables the extra synchronization
/// primitives, at the risk of possible memory
/// unsafety.
#[derive(Debug, Clone, Default)]
pub struct ArgumentParser {
args: Arc<Mutex<Vec<InternalArgument>>>,
binary: Arc<Mutex<Option<String>>>,
}
impl ArgumentParser {
/// Returns an empty [`ArgumentParser`].
pub fn new() -> Self {
Self::default()
}
/// Adds an argument to the parser.
#[allow(clippy::missing_panics_doc)]
pub fn add<T: ArgumentType>(&self, tag: Full) -> ArgumentRef<T> {
let typ = T::arg_type();
let arg = InternalArgument {
tag,
typ,
val: None,
};
let mut args = self.args.lock().unwrap();
let i = args.len();
args.push(arg);
ArgumentRef {
parser: self,
i,
_marker: PhantomData,
}
}
/// Retrieves the binary, if any.
#[allow(clippy::missing_panics_doc)]
pub fn binary(&self) -> Option<String> {
self.binary.lock().unwrap().clone()
}
/// Parse arguments from `std::env::{args,vars}`.
///
/// # Errors
///
/// If any arguments fail to parse their values, this
/// will forward that error. Otherwise, see
/// [`ArgParseError`] for a list of all possible errors.
pub fn parse(&self) -> Result<Vec<String>, ArgParseError> {
self.parse_provided(env::args().collect::<Vec<_>>().as_slice(), env::vars())
}
/// Parse from the provided environment variables and CLI arguments.
///
/// # Errors
///
/// See [`parse`] for details.
pub fn parse_provided<I: Iterator<Item = (String, String)>>(
&self,
cli: &[String],
env: I,
) -> Result<Vec<String>, ArgParseError> {
self.parse_env(env, true)?;
self.parse_cli(cli, false)
}
/// Parse the provided arguments as if they were environment variables.
///
/// If `reset == true`, clears the values of all arguments beforehand.
/// You probably want to leave this at `false`, unless you're re-using
/// your parser.
///
/// # Errors
///
/// See [`parse`] for details.
#[allow(clippy::missing_panics_doc)]
pub fn parse_env<I: Iterator<Item = (String, String)>>(
&self,
args: I,
reset: bool,
) -> Result<(), ArgParseError> {
let mut env_args = self.args.lock().unwrap();
if reset {
for arg in env_args.iter_mut() {
arg.val = None;
}
}
let mut env_args: Vec<_> = env_args
.iter_mut()
.filter(|arg| arg.tag.has_env())
.collect();
if env_args.is_empty() {
return Ok(());
}
for (key, val) in args {
let key_ref = &key;
if let Some(arg) = env_args
.iter_mut()
.find(|arg| arg.tag.env.as_ref().is_some_and(|env| env == key_ref))
{
Self::parse_arg(arg, Some(val), key)?;
}
}
Ok(())
}
/// Parses the provided arguments as if they were from the CLI.
///
/// If `reset == true`, clears the values of all arguments beforehand.
/// You probably want to leave this at `false`, unless you're re-using
/// your parser.
///
/// # Errors
///
/// See [`parse`] for details.
#[allow(clippy::missing_panics_doc)]
pub fn parse_cli(&self, args: &[String], reset: bool) -> Result<Vec<String>, ArgParseError> {
let mut args = args.iter();
*self.binary.lock().unwrap() = args.next().cloned();
let mut remainder = Vec::new();
if reset {
for arg in self.args.lock().unwrap().iter_mut() {
arg.val = None;
}
}
while let Some(arg) = args.next() {
if let Some(mut long) = arg.strip_prefix("--") {
let val = if let Some((left, right)) = long.split_once('=') {
long = left;
Some(right.to_string())
} else {
args.next().cloned()
};
let mut pre_args = self.args.lock().unwrap();
let arg = pre_args
.iter_mut()
.find(|arg| arg.tag.matches_long(long))
.ok_or(ArgParseError::UnknownFlag(long.to_string()))?;
Self::parse_arg(arg, val, long.to_string())?;
} else if let Some(short) = arg.strip_prefix('-') {
if short.is_empty() {
remainder.push(String::from("-"));
} else {
let mut consumed = false;
let mut pre_args = self.args.lock().unwrap();
for short in short.chars() {
let arg = pre_args
.iter_mut()
.find(|arg| arg.tag.matches_short(short))
.ok_or(ArgParseError::UnknownFlag(short.to_string()))?;
match arg.typ {
ArgumentValueType::Bool => arg.val = Some(ArgumentValue::Bool(true)),
ArgumentValueType::I64 => {
if consumed {
return Err(ArgParseError::ConsumedValue(short.to_string()));
}
consumed = true;
arg.val = Some(ArgumentValue::I64(
args.next()
.ok_or(ArgParseError::MissingValue(short.to_string()))?
.parse()
.map_err(|e: ParseIntError| {
ArgParseError::InvalidInteger(e.to_string())
})?,
));
}
ArgumentValueType::U64 => {
if consumed {
return Err(ArgParseError::ConsumedValue(short.to_string()));
}
consumed = true;
arg.val = Some(ArgumentValue::U64(
args.next()
.ok_or(ArgParseError::MissingValue(short.to_string()))?
.parse()
.map_err(|e: ParseIntError| {
ArgParseError::InvalidUnsignedInteger(e.to_string())
})?,
));
}
ArgumentValueType::Float => {
if consumed {
return Err(ArgParseError::ConsumedValue(short.to_string()));
}
consumed = true;
arg.val = Some(ArgumentValue::Float(
args.next()
.ok_or(ArgParseError::MissingValue(short.to_string()))?
.parse()
.map_err(|e: ParseFloatError| {
ArgParseError::InvalidInteger(e.to_string())
})?,
));
}
ArgumentValueType::String => {
if consumed {
return Err(ArgParseError::ConsumedValue(short.to_string()));
}
consumed = true;
arg.val = Some(ArgumentValue::String(
args.next()
.ok_or(ArgParseError::MissingValue(short.to_string()))?
.clone(),
));
}
}
}
}
} else {
remainder.push(arg.clone());
}
}
Ok(remainder)
}
fn parse_arg<S: AsRef<str>>(
arg: &mut InternalArgument,
val: Option<S>,
name: String,
) -> Result<(), ArgParseError> {
match arg.typ {
ArgumentValueType::Bool => {
if let Some(val) = val {
let val = val.as_ref().trim();
if val == "0" || val == "false" {
arg.val = Some(ArgumentValue::Bool(false));
} else {
arg.val = Some(ArgumentValue::Bool(true));
}
} else {
arg.val = Some(ArgumentValue::Bool(true));
}
}
ArgumentValueType::I64 => {
arg.val = Some(ArgumentValue::I64(
val.ok_or(ArgParseError::MissingValue(name))?
.as_ref()
.parse()
.map_err(|e: ParseIntError| ArgParseError::InvalidInteger(e.to_string()))?,
));
}
ArgumentValueType::U64 => {
arg.val = Some(ArgumentValue::U64(
val.ok_or(ArgParseError::MissingValue(name))?
.as_ref()
.parse()
.map_err(|e: ParseIntError| {
ArgParseError::InvalidUnsignedInteger(e.to_string())
})?,
));
}
ArgumentValueType::Float => {
arg.val = Some(ArgumentValue::Float(
val.ok_or(ArgParseError::MissingValue(name))?
.as_ref()
.parse()
.map_err(|e: ParseFloatError| ArgParseError::InvalidFloat(e.to_string()))?,
));
}
ArgumentValueType::String => {
arg.val = Some(ArgumentValue::String(
val.ok_or(ArgParseError::MissingValue(name))?
.as_ref()
.to_string(),
));
}
}
Ok(())
}
}