Skip to main content

alux_cli/
outcome.rs

1use core::{
2    convert::Infallible,
3    fmt::{self, Display, Formatter},
4    num::NonZeroU8,
5};
6
7/// Names the exit status of a command whose words did not make it: missing, repeated, or
8/// undecodable arguments. It follows the convention of POSIX utilities.
9pub const USAGE_STATUS: NonZeroU8 = NonZeroU8::new(2).unwrap();
10
11/// States what a command answers: its value, or a failure that ends with a nonzero status.
12///
13/// A successful command exits with status zero. How a value or failure is rendered, and on which
14/// stream, is the interpreter's choice.
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub enum CliOutcome<Value, Error> {
17    /// The command succeeded with this value.
18    Success(Value),
19    /// The command failed with this error.
20    Failure(Error),
21}
22
23/// States what a domain failure denotes on the command line: the status the command exits with.
24///
25/// A domain says this once for its own error type. The status is nonzero by its type, because zero
26/// is success.
27pub trait CliFailureAlg {
28    /// The status a command failing with this error exits with.
29    fn cli_status(&self) -> NonZeroU8;
30
31    /// Whether the failure was already reported as it happened, so the exit carries only its
32    /// status: `cat` reports each missing file and still reads the rest, and `false` reports
33    /// nothing.
34    fn cli_reported(&self) -> bool {
35        false
36    }
37}
38
39/// An error that cannot be constructed has no status, so a command carrying one only succeeds.
40impl CliFailureAlg for Infallible {
41    fn cli_status(&self) -> NonZeroU8 {
42        match *self {}
43    }
44}
45
46impl<Value, Error> CliOutcome<Value, Error>
47where
48    Error: CliFailureAlg,
49{
50    /// Returns the status the command exits with: zero on success, the failure's own otherwise.
51    pub fn cli_status(&self) -> u8 {
52        match self {
53            Self::Success(_) => 0,
54            Self::Failure(error) => error.cli_status().get(),
55        }
56    }
57}
58
59/// Reads every output as a success: the command's default.
60#[derive(Debug, Default)]
61pub struct Total;
62
63/// Reads a `Result` output as success or failure, failing at the status the declaration states:
64/// `1` for `.fallible()`, any other for `.fallible_as(status)`. The error can be any error that
65/// displays, `anyhow::Error` among them.
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
67pub struct Fallible {
68    status: NonZeroU8,
69}
70
71impl Fallible {
72    /// Fails at `status`.
73    ///
74    /// # Panics
75    ///
76    /// Panics when `status` is zero, which is success.
77    #[must_use]
78    #[track_caller]
79    pub const fn new(status: u8) -> Self {
80        match NonZeroU8::new(status) {
81            Some(status) => Self { status },
82            None => panic!("a failure exits with a nonzero status"),
83        }
84    }
85}
86
87/// Fails at status `1`, as `.fallible()` declares.
88impl Default for Fallible {
89    fn default() -> Self {
90        Self { status: NonZeroU8::MIN }
91    }
92}
93
94/// Reads a `Result` output as success or failure, failing as its error states: what
95/// `.fallible_by_error()` declares, for an error that implements `CliFailureAlg`.
96#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
97pub struct FallibleByError;
98
99/// An error a command fails with, at the status its declaration states.
100///
101/// It displays as its error does, alternate form included, so an interpreter writing `{:#}`
102/// writes an `anyhow` error with its chain of causes.
103#[derive(Clone, Debug, PartialEq, Eq)]
104pub struct CliFailure<Error> {
105    /// The error the operation answered with.
106    pub error: Error,
107    status: NonZeroU8,
108}
109
110impl<Error> CliFailureAlg for CliFailure<Error> {
111    fn cli_status(&self) -> NonZeroU8 {
112        self.status
113    }
114}
115
116impl<Error> Display for CliFailure<Error>
117where
118    Error: Display,
119{
120    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
121        self.error.fmt(formatter)
122    }
123}
124
125/// Reads an operation's output as a command's outcome under a declared mode.
126#[diagnostic::on_unimplemented(
127    message = "`{Self}` cannot read the output `{Output}` as a command outcome",
128    note = "a `.fallible()`, `.fallible_as(..)`, or `.fallible_by_error()` command applies an operation whose output is a `Result`"
129)]
130pub trait CliOutcomeOf<Output> {
131    /// The value a successful command answers with.
132    type Value;
133    /// The failure a command can end with.
134    type Error;
135
136    /// Reads `output` as the command's outcome.
137    fn cli_outcome(&self, output: Output) -> CliOutcome<Self::Value, Self::Error>;
138}
139
140impl<Output> CliOutcomeOf<Output> for Total {
141    type Value = Output;
142    type Error = Infallible;
143
144    fn cli_outcome(&self, output: Output) -> CliOutcome<Output, Infallible> {
145        CliOutcome::Success(output)
146    }
147}
148
149impl<Value, Error> CliOutcomeOf<Result<Value, Error>> for Fallible {
150    type Value = Value;
151    type Error = CliFailure<Error>;
152
153    fn cli_outcome(&self, output: Result<Value, Error>) -> CliOutcome<Value, CliFailure<Error>> {
154        match output {
155            Ok(value) => CliOutcome::Success(value),
156            Err(error) => CliOutcome::Failure(CliFailure { error, status: self.status }),
157        }
158    }
159}
160
161impl<Value, Error> CliOutcomeOf<Result<Value, Error>> for FallibleByError {
162    type Value = Value;
163    type Error = Error;
164
165    fn cli_outcome(&self, output: Result<Value, Error>) -> CliOutcome<Value, Error> {
166        match output {
167            Ok(value) => CliOutcome::Success(value),
168            Err(error) => CliOutcome::Failure(error),
169        }
170    }
171}