use core::{
convert::Infallible,
fmt::{self, Display, Formatter},
num::NonZeroU8,
};
pub const USAGE_STATUS: NonZeroU8 = NonZeroU8::new(2).unwrap();
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CliOutcome<Value, Error> {
Success(Value),
Failure(Error),
}
pub trait CliFailureAlg {
fn cli_status(&self) -> NonZeroU8;
fn cli_reported(&self) -> bool {
false
}
}
impl CliFailureAlg for Infallible {
fn cli_status(&self) -> NonZeroU8 {
match *self {}
}
}
impl<Value, Error> CliOutcome<Value, Error>
where
Error: CliFailureAlg,
{
pub fn cli_status(&self) -> u8 {
match self {
Self::Success(_) => 0,
Self::Failure(error) => error.cli_status().get(),
}
}
}
#[derive(Debug, Default)]
pub struct Total;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Fallible {
status: NonZeroU8,
}
impl Fallible {
#[must_use]
#[track_caller]
pub const fn new(status: u8) -> Self {
match NonZeroU8::new(status) {
Some(status) => Self { status },
None => panic!("a failure exits with a nonzero status"),
}
}
}
impl Default for Fallible {
fn default() -> Self {
Self { status: NonZeroU8::MIN }
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct FallibleByError;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CliFailure<Error> {
pub error: Error,
status: NonZeroU8,
}
impl<Error> CliFailureAlg for CliFailure<Error> {
fn cli_status(&self) -> NonZeroU8 {
self.status
}
}
impl<Error> Display for CliFailure<Error>
where
Error: Display,
{
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
self.error.fmt(formatter)
}
}
#[diagnostic::on_unimplemented(
message = "`{Self}` cannot read the output `{Output}` as a command outcome",
note = "a `.fallible()`, `.fallible_as(..)`, or `.fallible_by_error()` command applies an operation whose output is a `Result`"
)]
pub trait CliOutcomeOf<Output> {
type Value;
type Error;
fn cli_outcome(&self, output: Output) -> CliOutcome<Self::Value, Self::Error>;
}
impl<Output> CliOutcomeOf<Output> for Total {
type Value = Output;
type Error = Infallible;
fn cli_outcome(&self, output: Output) -> CliOutcome<Output, Infallible> {
CliOutcome::Success(output)
}
}
impl<Value, Error> CliOutcomeOf<Result<Value, Error>> for Fallible {
type Value = Value;
type Error = CliFailure<Error>;
fn cli_outcome(&self, output: Result<Value, Error>) -> CliOutcome<Value, CliFailure<Error>> {
match output {
Ok(value) => CliOutcome::Success(value),
Err(error) => CliOutcome::Failure(CliFailure { error, status: self.status }),
}
}
}
impl<Value, Error> CliOutcomeOf<Result<Value, Error>> for FallibleByError {
type Value = Value;
type Error = Error;
fn cli_outcome(&self, output: Result<Value, Error>) -> CliOutcome<Value, Error> {
match output {
Ok(value) => CliOutcome::Success(value),
Err(error) => CliOutcome::Failure(error),
}
}
}