mirror of
https://github.com/Noratrieb/badargs.git
synced 2026-01-14 19:55:08 +01:00
completed schema and already added some docs
This commit is contained in:
parent
cdb67f070c
commit
148574ed6e
4 changed files with 187 additions and 73 deletions
|
|
@ -1,5 +1,4 @@
|
||||||
use badargs::arg;
|
use badargs::arg;
|
||||||
use badargs::CliArg;
|
|
||||||
|
|
||||||
arg!(OutFile: "output", "o" -> Option<String>);
|
arg!(OutFile: "output", "o" -> Option<String>);
|
||||||
arg!(Force: "force", "f" -> bool);
|
arg!(Force: "force", "f" -> bool);
|
||||||
|
|
|
||||||
107
src/lib.rs
107
src/lib.rs
|
|
@ -2,13 +2,61 @@ mod macros;
|
||||||
mod schema;
|
mod schema;
|
||||||
|
|
||||||
use crate::parse::CliArgs;
|
use crate::parse::CliArgs;
|
||||||
use crate::schema::{IntoSchema, SchemaKind};
|
use crate::schema::{IntoSchema, Schema, SchemaKind};
|
||||||
|
|
||||||
pub use error::ArgError;
|
pub use error::ArgError;
|
||||||
pub use macros::*;
|
pub use macros::*;
|
||||||
|
|
||||||
pub type Result<T> = std::result::Result<T, ArgError>;
|
pub type Result<T> = std::result::Result<T, ArgError>;
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Parses the command line arguments based on the provided schema S
|
||||||
|
pub fn badargs<S>() -> Result<BadArgs>
|
||||||
|
where
|
||||||
|
S: IntoSchema,
|
||||||
|
{
|
||||||
|
let arg_schema = Schema::create::<S>()?;
|
||||||
|
|
||||||
|
let args = CliArgs::from_args(arg_schema, std::env::args_os())?;
|
||||||
|
|
||||||
|
Ok(BadArgs { args })
|
||||||
|
}
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Implemented by a user provided type that contains all info for a single command line argument
|
||||||
|
///
|
||||||
|
/// This is mostly done using unit structs and the `arg!` macro
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// # use badargs::arg;
|
||||||
|
/// arg!(OutFile: "output", "o" -> Option<String>);
|
||||||
|
/// // OutFile now implements CliArg
|
||||||
|
/// ```
|
||||||
|
pub trait CliArg {
|
||||||
|
type Content: CliReturnValue;
|
||||||
|
|
||||||
|
fn long() -> &'static str;
|
||||||
|
fn short() -> Option<&'static str>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The struct containing parsed argument information
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct BadArgs {
|
||||||
|
args: CliArgs,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BadArgs {
|
||||||
|
/// Get the content of an argument by providing the type of the argument
|
||||||
|
pub fn get<T>(&self) -> &T::Content
|
||||||
|
where
|
||||||
|
T: CliArg,
|
||||||
|
{
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///
|
||||||
|
/// A type that could be parsed from command line arguments
|
||||||
pub trait CliReturnValue: sealed::SealedCliReturnValue {
|
pub trait CliReturnValue: sealed::SealedCliReturnValue {
|
||||||
fn kind() -> schema::SchemaKind;
|
fn kind() -> schema::SchemaKind;
|
||||||
}
|
}
|
||||||
|
|
@ -39,39 +87,9 @@ mod sealed {
|
||||||
impl_!(String, Option<String>, bool, usize, isize);
|
impl_!(String, Option<String>, bool, usize, isize);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait CliArg {
|
|
||||||
type Content: CliReturnValue;
|
|
||||||
fn long() -> &'static str;
|
|
||||||
fn short() -> Option<&'static str>;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default)]
|
|
||||||
pub struct BadArgs {
|
|
||||||
args: CliArgs,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl BadArgs {
|
|
||||||
pub fn get<T>(&self) -> &T::Content
|
|
||||||
where
|
|
||||||
T: CliArg,
|
|
||||||
{
|
|
||||||
todo!()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn badargs<S>() -> Result<BadArgs>
|
|
||||||
where
|
|
||||||
S: IntoSchema,
|
|
||||||
{
|
|
||||||
let arg_schema = schema::parse_schema::<S>()?;
|
|
||||||
|
|
||||||
let args = CliArgs::from_args(arg_schema, std::env::args_os())?;
|
|
||||||
|
|
||||||
Ok(BadArgs { args })
|
|
||||||
}
|
|
||||||
|
|
||||||
mod error {
|
mod error {
|
||||||
#[derive(Debug, Clone)]
|
/// The error type for `badargs`
|
||||||
|
#[derive(Debug, Clone, Eq, PartialEq)]
|
||||||
pub enum ArgError {
|
pub enum ArgError {
|
||||||
InvalidUtf8,
|
InvalidUtf8,
|
||||||
NameAlreadyExists(&'static str),
|
NameAlreadyExists(&'static str),
|
||||||
|
|
@ -97,7 +115,7 @@ mod parse {
|
||||||
|
|
||||||
impl CliArgs {
|
impl CliArgs {
|
||||||
pub fn from_args(_schema: Schema, args: impl Iterator<Item = OsString>) -> Result<Self> {
|
pub fn from_args(_schema: Schema, args: impl Iterator<Item = OsString>) -> Result<Self> {
|
||||||
let mut result = Self::default();
|
let result = Self::default();
|
||||||
let mut args = args;
|
let mut args = args;
|
||||||
while let Some(_arg) = args.next() {}
|
while let Some(_arg) = args.next() {}
|
||||||
|
|
||||||
|
|
@ -105,24 +123,3 @@ mod parse {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod test {
|
|
||||||
use crate::CliArg;
|
|
||||||
|
|
||||||
struct OutFile;
|
|
||||||
impl CliArg for OutFile {
|
|
||||||
type Content = Option<String>;
|
|
||||||
|
|
||||||
fn long() -> &'static str {
|
|
||||||
"output"
|
|
||||||
}
|
|
||||||
|
|
||||||
fn short() -> Option<&'static str> {
|
|
||||||
Some("o")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn get_single_schema() {}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ macro_rules! arg {
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
struct $name;
|
struct $name;
|
||||||
|
|
||||||
impl ::badargs::CliArg for $name {
|
impl $crate::CliArg for $name {
|
||||||
type Content = $result;
|
type Content = $result;
|
||||||
|
|
||||||
fn long() -> &'static str {
|
fn long() -> &'static str {
|
||||||
|
|
|
||||||
150
src/schema.rs
150
src/schema.rs
|
|
@ -1,7 +1,16 @@
|
||||||
|
//!
|
||||||
|
//! Generates CLI argument schemas based on generic types
|
||||||
|
//!
|
||||||
|
//! This makes the interface of this crate fully type-safe! (and kind of cursed)
|
||||||
|
|
||||||
use super::Result;
|
use super::Result;
|
||||||
use crate::{ArgError, CliArg, CliReturnValue};
|
use crate::{ArgError, CliArg, CliReturnValue};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
///
|
||||||
|
/// The type of value the argument returns
|
||||||
|
///
|
||||||
|
/// This could *maybe* also be solved with trait objects but lets keep this for now
|
||||||
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
|
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
|
||||||
pub enum SchemaKind {
|
pub enum SchemaKind {
|
||||||
String,
|
String,
|
||||||
|
|
@ -11,27 +20,60 @@ pub enum SchemaKind {
|
||||||
UNum,
|
UNum,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Eq, PartialEq)]
|
///
|
||||||
|
/// A single command in the schema
|
||||||
|
#[derive(Debug, Clone, Eq, PartialEq, Copy)]
|
||||||
pub struct SchemaCommand {
|
pub struct SchemaCommand {
|
||||||
short: Option<&'static str>,
|
|
||||||
kind: SchemaKind,
|
kind: SchemaKind,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
///
|
||||||
|
/// A runtime representation of the schema type
|
||||||
#[derive(Debug, Clone, Default, Eq, PartialEq)]
|
#[derive(Debug, Clone, Default, Eq, PartialEq)]
|
||||||
pub struct Schema {
|
pub struct Schema {
|
||||||
commands: HashMap<&'static str, SchemaCommand>,
|
longs: HashMap<&'static str, SchemaCommand>,
|
||||||
|
shorts: HashMap<&'static str, SchemaCommand>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Schema {
|
impl Schema {
|
||||||
pub fn add_command(&mut self, name: &'static str, command: SchemaCommand) -> Result<()> {
|
/// Creates the `Schema` from the generic parameter `S`
|
||||||
if let Some(_) = self.commands.insert(name, command) {
|
pub fn create<S>() -> Result<Self>
|
||||||
Err(ArgError::NameAlreadyExists(name))
|
where
|
||||||
|
S: IntoSchema,
|
||||||
|
{
|
||||||
|
let mut schema = Schema::default();
|
||||||
|
S::add_schema(&mut schema)?;
|
||||||
|
Ok(schema)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_command(&mut self, long_name: &'static str, command: SchemaCommand) -> Result<()> {
|
||||||
|
if let Some(_) = self.longs.insert(long_name, command) {
|
||||||
|
Err(ArgError::NameAlreadyExists(long_name))
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_short_command(
|
||||||
|
&mut self,
|
||||||
|
short_name: &'static str,
|
||||||
|
command: SchemaCommand,
|
||||||
|
) -> Result<()> {
|
||||||
|
if let Some(_) = self.shorts.insert(short_name, command) {
|
||||||
|
Err(ArgError::NameAlreadyExists(short_name))
|
||||||
} else {
|
} else {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
///
|
||||||
|
/// This trait allows a type to be added to the schema
|
||||||
|
///
|
||||||
|
/// Any type that implements `CliArg` automatically gets this trait implementation for free
|
||||||
|
///
|
||||||
|
/// This has to be a separate trait because it's also implemented by the tuple, allowing for
|
||||||
|
/// multiple arguments
|
||||||
pub trait IntoSchema {
|
pub trait IntoSchema {
|
||||||
fn add_schema(schema: &mut Schema) -> Result<()>;
|
fn add_schema(schema: &mut Schema) -> Result<()>;
|
||||||
}
|
}
|
||||||
|
|
@ -48,15 +90,6 @@ where
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn parse_schema<S>() -> Result<Schema>
|
|
||||||
where
|
|
||||||
S: IntoSchema,
|
|
||||||
{
|
|
||||||
let mut schema = Schema::default();
|
|
||||||
S::add_schema(&mut schema)?;
|
|
||||||
Ok(schema)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Create the Schema from the CliArg type
|
/// Create the Schema from the CliArg type
|
||||||
impl<T> IntoSchema for T
|
impl<T> IntoSchema for T
|
||||||
where
|
where
|
||||||
|
|
@ -66,6 +99,91 @@ where
|
||||||
let kind = T::Content::kind();
|
let kind = T::Content::kind();
|
||||||
let name = T::long();
|
let name = T::long();
|
||||||
let short = T::short();
|
let short = T::short();
|
||||||
schema.add_command(name, SchemaCommand { short, kind })
|
let command = SchemaCommand { kind };
|
||||||
|
if let Some(short_name) = short {
|
||||||
|
schema.add_short_command(short_name, command)?;
|
||||||
|
}
|
||||||
|
schema.add_command(name, command)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use crate::schema::{Schema, SchemaCommand, SchemaKind};
|
||||||
|
use crate::{arg, ArgError};
|
||||||
|
|
||||||
|
arg!(OutFile: "output", "o" -> Option<String>);
|
||||||
|
arg!(Force: "force", "f" -> bool);
|
||||||
|
arg!(SetUpstream: "set-upstream" -> String);
|
||||||
|
arg!(OutFile2: "output", "o" -> Option<String>);
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn one_command_schema() {
|
||||||
|
let schema = Schema::create::<OutFile>().unwrap();
|
||||||
|
let out_file = SchemaCommand {
|
||||||
|
kind: SchemaKind::OptionString,
|
||||||
|
};
|
||||||
|
assert_eq!(schema.longs.get("output"), Some(&out_file));
|
||||||
|
assert_eq!(schema.shorts.get("o"), Some(&out_file));
|
||||||
|
assert_eq!(schema.longs.get("o"), None);
|
||||||
|
assert_eq!(schema.shorts.get("output"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn two_command_schema() {
|
||||||
|
let schema = Schema::create::<(OutFile, Force)>().unwrap();
|
||||||
|
let out_file = SchemaCommand {
|
||||||
|
kind: SchemaKind::OptionString,
|
||||||
|
};
|
||||||
|
let force = SchemaCommand {
|
||||||
|
kind: SchemaKind::Bool,
|
||||||
|
};
|
||||||
|
|
||||||
|
assert_eq!(schema.longs.get("output"), Some(&out_file));
|
||||||
|
assert_eq!(schema.shorts.get("o"), Some(&out_file));
|
||||||
|
assert_eq!(schema.longs.get("o"), None);
|
||||||
|
assert_eq!(schema.shorts.get("output"), None);
|
||||||
|
|
||||||
|
assert_eq!(schema.longs.get("force"), Some(&force));
|
||||||
|
assert_eq!(schema.shorts.get("f"), Some(&force));
|
||||||
|
assert_eq!(schema.longs.get("f"), None);
|
||||||
|
assert_eq!(schema.shorts.get("force"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn three_command_schema() {
|
||||||
|
let schema = Schema::create::<(OutFile, (Force, SetUpstream))>().unwrap();
|
||||||
|
let out_file = SchemaCommand {
|
||||||
|
kind: SchemaKind::OptionString,
|
||||||
|
};
|
||||||
|
let force = SchemaCommand {
|
||||||
|
kind: SchemaKind::Bool,
|
||||||
|
};
|
||||||
|
let set_upstream = SchemaCommand {
|
||||||
|
kind: SchemaKind::String,
|
||||||
|
};
|
||||||
|
|
||||||
|
assert_eq!(schema.longs.get("output"), Some(&out_file));
|
||||||
|
assert_eq!(schema.shorts.get("o"), Some(&out_file));
|
||||||
|
assert_eq!(schema.longs.get("o"), None);
|
||||||
|
assert_eq!(schema.shorts.get("output"), None);
|
||||||
|
|
||||||
|
assert_eq!(schema.longs.get("force"), Some(&force));
|
||||||
|
assert_eq!(schema.shorts.get("f"), Some(&force));
|
||||||
|
assert_eq!(schema.longs.get("f"), None);
|
||||||
|
assert_eq!(schema.shorts.get("force"), None);
|
||||||
|
|
||||||
|
assert_eq!(schema.longs.get("set-upstream"), Some(&set_upstream));
|
||||||
|
assert_eq!(schema.shorts.get("set-upstream"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn double_error() {
|
||||||
|
let schema = Schema::create::<(OutFile, OutFile2)>();
|
||||||
|
assert!(matches!(
|
||||||
|
schema,
|
||||||
|
// it doesn't matter which one gets reported first
|
||||||
|
Err(ArgError::NameAlreadyExists("output")) | Err(ArgError::NameAlreadyExists("o"))
|
||||||
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue