kanidm_proto/messages.rs
1// User-facing output things
2
3use std::{fmt, str::FromStr};
4
5use serde::{Deserialize, Serialize};
6
7/// This is used in user-facing CLIs to set the formatting for output,
8/// and defaults to text.
9#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Default)]
10#[serde(rename_all = "lowercase")]
11pub enum ConsoleOutputMode {
12 #[default]
13 Text,
14 JSON,
15}
16
17impl FromStr for ConsoleOutputMode {
18 type Err = &'static str;
19
20 /// This can be safely unwrap'd because it'll always return a default of text
21 /// ```
22 /// use kanidm_proto::messages::ConsoleOutputMode;
23 ///
24 /// let mode: ConsoleOutputMode = "🦀".into();
25 /// assert_eq!(ConsoleOutputMode::Text, mode);
26 /// let mode: ConsoleOutputMode = "".into();
27 /// assert_eq!(ConsoleOutputMode::Text, mode);
28 ///
29 /// let mode: ConsoleOutputMode = "json".into();
30 /// assert_eq!(ConsoleOutputMode::JSON, mode);
31 /// ```
32 fn from_str(s: &str) -> Result<Self, Self::Err> {
33 match s {
34 "json" => Ok(ConsoleOutputMode::JSON),
35 "text" => Ok(ConsoleOutputMode::Text),
36 _ => {
37 eprintln!("Supplied output mode ({s:?}) was invalid, defaulting to text");
38 Ok(ConsoleOutputMode::Text)
39 }
40 }
41 }
42}
43
44/// This will take any string, if it's 'text' or 'json' then you'll get
45/// what you asked for, else you'll get a text version.
46///
47/// ```
48/// use kanidm_proto::messages::ConsoleOutputMode;
49/// let bork = "text";
50/// let com: ConsoleOutputMode = bork.into();
51/// matches!(ConsoleOutputMode::Text, com);
52/// ```
53impl From<&str> for ConsoleOutputMode {
54 fn from(input: &str) -> Self {
55 match ConsoleOutputMode::from_str(input) {
56 Ok(val) => val,
57 Err(_) => Self::Text,
58 }
59 }
60}
61
62/// This will take any string, if it's 'text' or 'json' then you'll get
63/// what you asked for, else you'll get a text version.
64///
65/// ```
66/// use kanidm_proto::messages::ConsoleOutputMode;
67/// let bork = String::from("cr4bz");
68/// let com: ConsoleOutputMode = bork.into();
69/// matches!(ConsoleOutputMode::Text, com);
70/// ```
71impl From<String> for ConsoleOutputMode {
72 fn from(input: String) -> Self {
73 match ConsoleOutputMode::from_str(input.as_str()) {
74 Ok(val) => val,
75 Err(_) => Self::Text,
76 }
77 }
78}
79
80#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
81#[serde(rename_all = "lowercase")]
82pub enum MessageStatus {
83 Failure,
84 Success,
85}
86
87impl fmt::Display for MessageStatus {
88 fn fmt(&self, f: &mut fmt::Formatter) -> ::std::result::Result<(), ::std::fmt::Error> {
89 match *self {
90 MessageStatus::Failure => f.write_str("failure"),
91 MessageStatus::Success => f.write_str("success"),
92 }
93 }
94}
95
96#[derive(Debug, Serialize, Deserialize)]
97pub struct AccountChangeMessage {
98 #[serde(skip_serializing)]
99 pub output_mode: ConsoleOutputMode,
100 pub action: String,
101 pub result: String,
102 pub status: MessageStatus,
103 pub src_user: String,
104 pub dest_user: String,
105}
106
107impl Default for AccountChangeMessage {
108 fn default() -> Self {
109 AccountChangeMessage {
110 output_mode: ConsoleOutputMode::Text,
111 action: String::from(""),
112 result: String::from(""),
113 status: MessageStatus::Success,
114 src_user: String::from(""),
115 dest_user: String::from(""),
116 }
117 }
118}
119
120/// This outputs in either JSON or Text depending on the output_mode setting
121/// ```
122/// use std::fmt::format;
123/// use kanidm_proto::messages::*;
124/// let mut msg = AccountChangeMessage::default();
125/// msg.action=String::from("cake_eating");
126/// msg.src_user=String::from("Kani");
127/// msg.dest_user=String::from("Krabby");
128/// msg.result=String::from("It was amazing");
129/// assert_eq!(msg.status, MessageStatus::Success);
130///
131/// let expected_result = "success - cake_eating for Krabby: It was amazing";
132/// assert_eq!(format!("{}", msg), expected_result);
133///
134/// msg.output_mode = ConsoleOutputMode::JSON;
135/// let expected_result = "{\"action\":\"cake_eating\",\"result\":\"It was amazing\",\"status\":\"success\",\"src_user\":\"Kani\",\"dest_user\":\"Krabby\"}";
136/// assert_eq!(format!("{}", msg), expected_result);
137/// ```
138impl fmt::Display for AccountChangeMessage {
139 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140 match self.output_mode {
141 ConsoleOutputMode::JSON => write!(
142 f,
143 "{}",
144 serde_json::to_string(self).unwrap_or(format!("{self:?}")) /* if it fails to JSON serialize, just debug-dump it */
145 ),
146 ConsoleOutputMode::Text => write!(
147 f,
148 "{} - {} for {}: {}",
149 self.status, self.action, self.dest_user, self.result,
150 ),
151 }
152 }
153}
154
155#[derive(Debug, Serialize, Deserialize)]
156pub struct BasicMessage {
157 #[serde(skip_serializing)]
158 pub output_mode: ConsoleOutputMode,
159 pub action: String,
160 pub result: String,
161 pub status: MessageStatus,
162}
163
164impl Default for BasicMessage {
165 fn default() -> Self {
166 BasicMessage {
167 output_mode: ConsoleOutputMode::Text,
168 action: String::from(""),
169 result: String::from(""),
170 status: MessageStatus::Success,
171 }
172 }
173}
174
175/// This outputs in either JSON or Text depending on the output_mode setting
176/// ```
177/// use kanidm_proto::messages::*;
178/// use std::fmt::format;
179/// let mut msg = BasicMessage::default();
180/// msg.action = String::from("cake_eating");
181/// msg.result = String::from("It was amazing");
182/// assert_eq!(msg.status, MessageStatus::Success);
183///
184/// let expected_result = "success - cake_eating: It was amazing";
185/// assert_eq!(format!("{}", msg), expected_result);
186///
187/// msg.output_mode = ConsoleOutputMode::JSON;
188/// let expected_result =
189/// "{\"action\":\"cake_eating\",\"result\":\"It was amazing\",\"status\":\"success\"}";
190/// assert_eq!(format!("{}", msg), expected_result);
191/// ```
192impl fmt::Display for BasicMessage {
193 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194 match self.output_mode {
195 ConsoleOutputMode::JSON => write!(
196 f,
197 "{}",
198 serde_json::to_string(self).unwrap_or(format!("{self:?}")) /* if it fails to JSON serialize, just debug-dump it */
199 ),
200 ConsoleOutputMode::Text => {
201 write!(f, "{} - {}: {}", self.status, self.action, self.result,)
202 }
203 }
204 }
205}