removed optionality it does not make sense

This commit is contained in:
nora 2021-10-01 22:25:17 +02:00
parent a33b81c58e
commit 2ec1f142a9
5 changed files with 52 additions and 35 deletions

View file

@ -1,6 +1,6 @@
use badargs::arg; use badargs::arg;
arg!(OutFile: "output", 'o' -> String, required); arg!(OutFile: "output", 'o' -> String);
arg!(Force: "force", 'f' -> bool); arg!(Force: "force", 'f' -> bool);
arg!(OLevel: "optimize" -> usize); arg!(OLevel: "optimize" -> usize);

View file

@ -32,8 +32,7 @@ where
/// ``` /// ```
/// # use badargs::arg; /// # use badargs::arg;
/// arg!(Force: "force", 'f' -> bool); /// arg!(Force: "force", 'f' -> bool);
/// /// arg!(OutFile: "output", 'o' -> String);
/// arg!(OutFile: "output", 'o' -> String, required);
/// // OutFile now implements CliArg /// // OutFile now implements CliArg
/// ``` /// ```
// This trait requires any because some dynamic typing is done in the background // This trait requires any because some dynamic typing is done in the background
@ -42,7 +41,6 @@ pub trait CliArg: Any {
fn long() -> &'static str; fn long() -> &'static str;
fn short() -> Option<char>; fn short() -> Option<char>;
fn required() -> bool;
} }
/// The struct containing parsed argument information /// The struct containing parsed argument information
@ -107,8 +105,9 @@ mod error {
#[derive(Debug, Clone, Eq, PartialEq)] #[derive(Debug, Clone, Eq, PartialEq)]
pub enum CallError { pub enum CallError {
SingleMinus, SingleMinus,
UnnamedArgument,
ShortFlagNotFound(char), ShortFlagNotFound(char),
ExpectedValue(String), ExpectedValue(String),
INan(String),
UNan(String),
} }
} }

View file

@ -2,19 +2,12 @@
macro_rules! arg { macro_rules! arg {
// implicit optional // implicit optional
($name:ident: $long:literal, $short:literal -> $result:ty) => { ($name:ident: $long:literal, $short:literal -> $result:ty) => {
arg!(@$name: ($long, ::std::option::Option::Some($short)) -> $result, false); arg!(@$name: ($long, ::std::option::Option::Some($short)) -> $result);
}; };
($name:ident: $long:literal -> $result:ty) => { ($name:ident: $long:literal -> $result:ty) => {
arg!(@$name: ($long, ::std::option::Option::None) -> $result, false); arg!(@$name: ($long, ::std::option::Option::None) -> $result);
}; };
// required (@$name:ident: ($long:literal, $short:expr) -> $result:ty) => {
($name:ident: $long:literal, $short:literal -> $result:ty, required) => {
arg!(@$name: ($long, ::std::option::Option::Some($short)) -> $result, true);
};
($name:ident: $long:literal -> $result:ty, required) => {
arg!(@$name: ($long, ::std::option::Option::None) -> $result, true);
};
(@$name:ident: ($long:literal, $short:expr) -> $result:ty, $required:literal) => {
#[derive(Default)] #[derive(Default)]
struct $name; struct $name;
@ -28,10 +21,6 @@ macro_rules! arg {
fn short() -> Option<char> { fn short() -> Option<char> {
$short $short
} }
fn required() -> bool {
$required
}
} }
}; };
} }

View file

@ -9,6 +9,7 @@ type Result<T> = std::result::Result<T, CallError>;
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct CliArgs { pub struct CliArgs {
args: HashMap<&'static str, Box<dyn Any>>, args: HashMap<&'static str, Box<dyn Any>>,
unnamed: Vec<String>,
} }
impl CliArgs { impl CliArgs {
@ -21,7 +22,7 @@ impl CliArgs {
parse_shorts(schema, &mut result, shorts, &mut args)?; parse_shorts(schema, &mut result, shorts, &mut args)?;
} else if let Some(_longs) = arg.strip_prefix("--") { } else if let Some(_longs) = arg.strip_prefix("--") {
} else { } else {
return Err(CallError::UnnamedArgument); result.unnamed.push(arg);
} }
} }
@ -35,6 +36,10 @@ impl CliArgs {
any.downcast_ref() any.downcast_ref()
} }
pub fn unnamed(&self) -> &[String] {
&self.unnamed
}
fn insert(&mut self, long: &'static str, value: Box<dyn Any>) { fn insert(&mut self, long: &'static str, value: Box<dyn Any>) {
self.args.insert(long, value); self.args.insert(long, value);
} }
@ -62,12 +67,30 @@ fn parse_shorts(
match command.kind { match command.kind {
SchemaKind::String => { SchemaKind::String => {
let next = args let string = args
.next() .next()
.ok_or_else(|| CallError::ExpectedValue(command.long.to_string()))?; .ok_or_else(|| CallError::ExpectedValue(command.long.to_string()))?;
results.insert(command.long, Box::new(next)); results.insert(command.long, Box::new(string));
}
SchemaKind::INum => {
let integer = args
.next()
.ok_or_else(|| CallError::ExpectedValue(command.long.to_string()))?
.parse::<isize>()
.map_err(|_| CallError::INan(command.long.to_string()))?;
results.insert(command.long, Box::new(integer))
}
SchemaKind::UNum => {
let integer = args
.next()
.ok_or_else(|| CallError::ExpectedValue(command.long.to_string()))?
.parse::<usize>()
.map_err(|_| CallError::UNan(command.long.to_string()))?;
results.insert(command.long, Box::new(integer))
}
SchemaKind::Bool => {
results.insert(command.long, Box::new(true));
} }
_ => todo!(),
} }
} else { } else {
return Err(CallError::SingleMinus); return Err(CallError::SingleMinus);
@ -84,7 +107,7 @@ mod test {
use crate::arg; use crate::arg;
use crate::schema::Schema; use crate::schema::Schema;
arg!(OutFile: "output", 'o' -> Option<String>); arg!(OutFile: "output", 'o' -> String);
arg!(Input: "input", 'i' -> String); arg!(Input: "input", 'i' -> String);
arg!(Force: "force", 'f' -> bool); arg!(Force: "force", 'f' -> bool);
arg!(SetUpstream: "set-upstream" -> String); arg!(SetUpstream: "set-upstream" -> String);
@ -109,4 +132,17 @@ mod test {
let args = parse_args("-i stdin").unwrap(); let args = parse_args("-i stdin").unwrap();
assert_eq!(args.get::<String>("input"), Some(&"stdin".to_string())) assert_eq!(args.get::<String>("input"), Some(&"stdin".to_string()))
} }
#[test]
fn two_unnamed() {
let args = parse_args("hallo welt").unwrap();
assert_eq!(args.unnamed(), &["hallo", "welt"]);
}
#[test]
fn arg_param_and_unnamed() {
let args = parse_args("-i stdin uwu").unwrap();
assert_eq!(args.unnamed(), &["uwu"]);
assert_eq!(args.get::<String>("input"), Some(&"stdin".to_string()))
}
} }

View file

@ -4,6 +4,7 @@
//! This makes the interface of this crate fully type-safe! (and kind of cursed) //! This makes the interface of this crate fully type-safe! (and kind of cursed)
use super::Result; use super::Result;
use crate::error::CallError;
use crate::{CliArg, CliReturnValue, SchemaError}; use crate::{CliArg, CliReturnValue, SchemaError};
use std::collections::HashMap; use std::collections::HashMap;
@ -26,7 +27,6 @@ pub struct SchemaCommand {
pub kind: SchemaKind, pub kind: SchemaKind,
pub long: &'static str, pub long: &'static str,
pub short: Option<char>, pub short: Option<char>,
pub required: bool,
} }
/// ///
@ -107,7 +107,6 @@ where
kind: T::Content::kind(), kind: T::Content::kind(),
long: T::long(), long: T::long(),
short, short,
required: T::required(),
}; };
if let Some(short) = short { if let Some(short) = short {
schema.add_short_command(short, command)?; schema.add_short_command(short, command)?;
@ -119,12 +118,12 @@ where
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use crate::arg; use crate::arg;
use crate::schema::{Schema, SchemaCommand, SchemaKind, SchemaKindType}; use crate::schema::{Schema, SchemaCommand, SchemaKind};
arg!(OutFile: "output", 'o' -> Option<String>); arg!(OutFile: "output", 'o' -> String);
arg!(Force: "force", 'f' -> bool); arg!(Force: "force", 'f' -> bool);
arg!(SetUpstream: "set-upstream" -> String); arg!(SetUpstream: "set-upstream" -> String);
arg!(OutFile2: "output", 'o' -> Option<String>); arg!(OutFile2: "output", 'o' -> String);
#[test] #[test]
fn one_command_schema() { fn one_command_schema() {
@ -133,7 +132,6 @@ mod test {
kind: SchemaKind::String, kind: SchemaKind::String,
long: "output", long: "output",
short: Some('o'), short: Some('o'),
required: false,
}; };
assert_eq!(schema.longs.get("output"), Some(&out_file)); assert_eq!(schema.longs.get("output"), Some(&out_file));
assert_eq!(schema.shorts.get(&'o'), Some(&out_file)); assert_eq!(schema.shorts.get(&'o'), Some(&out_file));
@ -147,13 +145,11 @@ mod test {
kind: SchemaKind::String, kind: SchemaKind::String,
long: "output", long: "output",
short: Some('o'), short: Some('o'),
required: false,
}; };
let force = SchemaCommand { let force = SchemaCommand {
kind: SchemaKind::Bool, kind: SchemaKind::Bool,
long: "force", long: "force",
short: Some('f'), short: Some('f'),
required: true,
}; };
assert_eq!(schema.longs.get("output"), Some(&out_file)); assert_eq!(schema.longs.get("output"), Some(&out_file));
@ -172,19 +168,16 @@ mod test {
kind: SchemaKind::String, kind: SchemaKind::String,
long: "output", long: "output",
short: Some('o'), short: Some('o'),
required: false,
}; };
let force = SchemaCommand { let force = SchemaCommand {
kind: SchemaKind::Bool, kind: SchemaKind::Bool,
long: "force", long: "force",
short: Some('f'), short: Some('f'),
required: true,
}; };
let set_upstream = SchemaCommand { let set_upstream = SchemaCommand {
kind: SchemaKind::String, kind: SchemaKind::String,
long: "set-upstream", long: "set-upstream",
short: None, short: None,
required: true,
}; };
assert_eq!(schema.longs.get("output"), Some(&out_file)); assert_eq!(schema.longs.get("output"), Some(&out_file));