#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Opt<'a> {
Short(char),
Long(&'a str),
}
impl core::fmt::Display for Opt<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Opt::Short(short) => write!(f, "-{short}"),
Opt::Long(long) => write!(f, "--{long}"),
}
}
}
#[must_use]
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Error<'a> {
MissingArgument(&'static str),
UnknownOption {
option: Opt<'a>,
suggestion: Option<&'static str>,
},
UnexpectedArgument(&'a str),
UnexpectedValue(Opt<'a>),
MissingOptionValue(&'static str),
ArgumentConflict {
name: &'static str,
other: &'static str,
},
MissingRequiredArgument {
name: &'static str,
required_by: &'static str,
},
MissingOneOf(&'static [&'static str]),
MissingSubcommand(&'static [&'static str]),
UnknownSubcommand {
name: &'a str,
suggestion: Option<&'static str>,
},
InvalidArguments,
InvalidValue {
name: &'static str,
value: &'a str,
},
InvalidPossibleValue {
name: &'static str,
value: &'a str,
possible_values: &'static [&'static str],
},
ValueOutOfRange {
name: &'static str,
value: &'a str,
range: &'static str,
},
TooManyValues {
name: &'static str,
value: &'a str,
max: usize,
},
TooFewValues {
name: &'static str,
min: usize,
actual: usize,
},
InvalidUtf8 {
name: Option<&'static str>,
value: &'a [u8],
},
Help(&'static str),
Version(&'static str),
}
impl<'a> Error<'a> {
#[must_use]
pub fn is_help(&self) -> bool {
matches!(self, Error::Help(_))
}
#[must_use]
pub fn is_version(&self) -> bool {
matches!(self, Error::Version(_))
}
pub const fn with_usage(self, usage: Usage) -> WithUsage<'a> {
WithUsage { error: self, usage }
}
}
impl core::fmt::Display for Error<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Error::MissingArgument(name) => {
write!(
f,
"the following required argument was not provided: {name}"
)
}
Error::UnknownOption { option, suggestion } => {
write!(f, "unexpected argument '{option}' found")?;
match suggestion {
Some(suggestion) => {
write!(f, "\n\n tip: a similar argument exists: '--{suggestion}'")
}
None => Ok(()),
}
}
Error::UnexpectedArgument(argument) => {
write!(f, "unexpected argument '{argument}' found")
}
Error::UnexpectedValue(option) => {
write!(
f,
"unexpected value for '{option}': it does not take a value"
)
}
Error::ArgumentConflict { name, other } => {
write!(f, "the argument '{name}' cannot be used with '{other}'")
}
Error::MissingRequiredArgument { name, required_by } => {
write!(
f,
"the following required argument was not provided: {name} (required by '{required_by}')"
)
}
Error::MissingOneOf(names) => {
f.write_str("the following required arguments were not provided: <")?;
for (index, name) in names.iter().enumerate() {
if index > 0 {
f.write_str("|")?;
}
f.write_str(name)?;
}
f.write_str(">")
}
Error::MissingSubcommand(names) => {
f.write_str(
"a subcommand is required but one was not provided\n\n [subcommands: ",
)?;
for (index, name) in names.iter().enumerate() {
if index > 0 {
f.write_str(", ")?;
}
f.write_str(name)?;
}
f.write_str("]")
}
Error::UnknownSubcommand { name, suggestion } => {
write!(f, "unrecognized subcommand '{name}'")?;
match suggestion {
Some(suggestion) => {
write!(f, "\n\n tip: a similar subcommand exists: '{suggestion}'")
}
None => Ok(()),
}
}
Error::InvalidArguments => f.write_str("the arguments could not be parsed"),
Error::MissingOptionValue(name) => {
write!(f, "a value is required for '{name}' but none was supplied")
}
Error::InvalidValue { name, value } => {
write!(f, "invalid value '{value}' for '{name}'")
}
Error::InvalidPossibleValue {
name,
value,
possible_values,
} => {
write!(
f,
"invalid value '{value}' for '{name}'\n [possible values: "
)?;
for (index, possible) in possible_values.iter().enumerate() {
if index > 0 {
f.write_str(", ")?;
}
if possible.is_empty() || possible.contains(char::is_whitespace) {
write!(f, "{possible:?}")?;
} else {
f.write_str(possible)?;
}
}
f.write_str("]")
}
Error::ValueOutOfRange { name, value, range } => {
write!(
f,
"invalid value '{value}' for '{name}': {value} is not in {range}"
)
}
Error::TooManyValues { name, value, .. } => {
write!(
f,
"unexpected value '{value}' for '{name}' found; no more were expected"
)
}
Error::TooFewValues { name, min, actual } => {
let verb = if *actual == 1 { "was" } else { "were" };
write!(
f,
"{min} values required by '{name}'; only {actual} {verb} provided"
)
}
Error::InvalidUtf8 {
name: Some(name),
value,
} => {
write!(
f,
"invalid UTF-8 in value '{}' for '{name}'",
crate::Lossy(value)
)
}
Error::InvalidUtf8 { name: None, value } => {
write!(f, "invalid UTF-8 in argument '{}'", crate::Lossy(value))
}
Error::Help(help) => f.write_str(help),
Error::Version(version) => f.write_str(version),
}
}
}
impl core::error::Error for Error<'_> {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Usage {
pub line: &'static str,
pub help_flag: bool,
}
impl Usage {
#[must_use]
pub const fn new(line: &'static str) -> Self {
Usage {
line,
help_flag: true,
}
}
#[must_use]
pub const fn help_flag(mut self, help_flag: bool) -> Self {
self.help_flag = help_flag;
self
}
}
impl core::fmt::Display for Usage {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(self.line)
}
}
#[must_use]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WithUsage<'a> {
error: Error<'a>,
usage: Usage,
}
impl<'a> WithUsage<'a> {
pub const fn error(&self) -> &Error<'a> {
&self.error
}
pub const fn usage(&self) -> &Usage {
&self.usage
}
}
impl core::fmt::Display for WithUsage<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", self.error)?;
if self.error.is_help() || self.error.is_version() {
return Ok(());
}
write!(f, "\n\n{}", self.usage)?;
if self.usage.help_flag {
f.write_str("\n\nFor more information, try '--help'.")?;
}
Ok(())
}
}
impl core::error::Error for WithUsage<'_> {}