Skip to main content

tilo_actions/
refusal.rs

1//! Why an action declined to run, as the verb that refused it says.
2
3use crate::ActionError;
4
5/// Why an action declined to run, in the user's words, and, where a caller
6/// acts on the reason rather than reads it, a stable code naming it.
7#[derive(Clone, Debug, PartialEq, Eq)]
8pub struct Refusal {
9    code: Option<String>,
10    reason: String,
11}
12
13impl Refusal {
14    pub fn new(reason: impl Into<String>) -> Self {
15        Self {
16            code: None,
17            reason: reason.into(),
18        }
19    }
20
21    /// A refusal a caller tells apart by `code` (a thing the action would add
22    /// is there already, say), with `reason` in words beside it for whoever
23    /// reads.
24    pub fn coded(code: impl Into<String>, reason: impl Into<String>) -> Self {
25        Self {
26            code: Some(code.into()),
27            reason: reason.into(),
28        }
29    }
30
31    /// The code the app gave, for a caller that decides on it.
32    #[must_use]
33    pub fn code(&self) -> Option<&str> {
34        self.code.as_deref()
35    }
36
37    /// Why, in the user's words.
38    #[must_use]
39    pub fn reason(&self) -> &str {
40        &self.reason
41    }
42
43    /// Why, in the user's words, owned.
44    #[must_use]
45    pub fn into_reason(self) -> String {
46        self.reason
47    }
48}
49
50impl std::fmt::Display for Refusal {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        f.write_str(&self.reason)
53    }
54}
55
56impl From<&str> for Refusal {
57    fn from(reason: &str) -> Self {
58        Self::new(reason)
59    }
60}
61
62impl From<String> for Refusal {
63    fn from(reason: String) -> Self {
64        Self::new(reason)
65    }
66}
67
68/// A verb's refusal as the action's: one a caller decides on keeps its code.
69impl From<Refusal> for ActionError {
70    fn from(refusal: Refusal) -> Self {
71        match refusal.code {
72            Some(code) => Self::Unavailable {
73                code,
74                message: refusal.reason,
75            },
76            None => Self::Refused(refusal.reason),
77        }
78    }
79}
80
81/// An action's refusal as a verb's, for a reader above the action that hands
82/// it on: one a caller decides on keeps its code.
83impl From<ActionError> for Refusal {
84    fn from(error: ActionError) -> Self {
85        match error {
86            ActionError::Unavailable { code, message } => Self::coded(code, message),
87            other => Self::new(other.to_string()),
88        }
89    }
90}