fernctl/error/severity.rs
1//! # Severity Levels for Errors and Notifications
2//!
3//! This module defines [`Severity`], an enumeration of importance levels for
4//! errors and notifications in Fern Shell.
5//!
6//! ## Design Rationale
7//!
8//! Not all problems are equal. A misspelled config key is worth warning about,
9//! but shouldn't prevent the shell from starting. An invalid color format is
10//! an error that needs fixing, but a single module can fail without crashing
11//! the entire shell. Only truly unrecoverable situations are fatal.
12//!
13//! By encoding severity in the type system (rather than as a string or integer),
14//! we get:
15//!
16//! - **Exhaustive matching** — The compiler ensures all severities are handled
17//! - **Type safety** — Can't accidentally pass a string where severity is expected
18//! - **Rich methods** — Severity carries behavior (icons, ordering, etc.)
19//!
20//! ## Ordering
21//!
22//! Severities are ordered from least to most severe:
23//!
24//! ```text
25//! Info < Warning < Error < Fatal
26//! ```
27//!
28//! This enables filtering:
29//!
30//! ```rust
31//! use fernctl::error::Severity;
32//!
33//! let min_severity = Severity::Warning;
34//! let current = Severity::Info;
35//!
36//! if current >= min_severity {
37//! // Won't run - Info is less severe than Warning
38//! }
39//! ```
40
41use serde::{Deserialize, Serialize};
42use std::fmt;
43
44/// Severity level for errors, warnings, and notifications.
45///
46/// `Severity` represents how serious a problem is and how it should be handled.
47/// It is used throughout the error system and integrates with the notification
48/// system for user-facing alerts.
49///
50/// # Variants
51///
52/// | Level | Meaning | Shell Behavior |
53/// |-------|---------|----------------|
54/// | [`Info`](Severity::Info) | Informational, not a problem | Log only |
55/// | [`Warning`](Severity::Warning) | Suboptimal but functional | Log + optional notification |
56/// | [`Error`](Severity::Error) | Operation failed | Log + notification + retry possible |
57/// | [`Fatal`](Severity::Fatal) | Unrecoverable | Log + notification + exit |
58///
59/// # Ordering
60///
61/// `Severity` implements [`Ord`], with [`Info`](Severity::Info) being the least
62/// severe and [`Fatal`](Severity::Fatal) being the most:
63///
64/// ```rust
65/// use fernctl::error::Severity;
66///
67/// assert!(Severity::Info < Severity::Warning);
68/// assert!(Severity::Warning < Severity::Error);
69/// assert!(Severity::Error < Severity::Fatal);
70/// ```
71///
72/// # Display
73///
74/// Each severity has both a human-readable name and an icon for terminal output:
75///
76/// ```rust
77/// use fernctl::error::Severity;
78///
79/// assert_eq!(Severity::Error.as_str(), "error");
80/// assert_eq!(Severity::Error.icon(), "✗");
81/// ```
82///
83/// # Serialization
84///
85/// `Severity` serializes to lowercase strings for JSON/TOML compatibility:
86///
87/// ```rust
88/// use fernctl::error::Severity;
89///
90/// let json = serde_json::to_string(&Severity::Warning).unwrap();
91/// assert_eq!(json, "\"warning\"");
92/// ```
93#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
94#[serde(rename_all = "lowercase")]
95#[non_exhaustive]
96pub enum Severity {
97 /// Informational message, not an error.
98 ///
99 /// Use for status updates, progress information, or optional suggestions
100 /// that don't indicate any problem.
101 ///
102 /// # Example Scenarios
103 ///
104 /// - "Configuration loaded successfully"
105 /// - "Using default theme"
106 /// - "3 modules active"
107 Info,
108
109 /// Something is suboptimal but will work.
110 ///
111 /// Use when the configuration or operation has issues that should be
112 /// addressed, but the shell can continue functioning.
113 ///
114 /// # Example Scenarios
115 ///
116 /// - Unknown configuration key (will be ignored)
117 /// - Deprecated option used
118 /// - Fallback to default value
119 Warning,
120
121 /// Operation failed, but recovery is possible.
122 ///
123 /// Use when a specific operation or module fails, but the shell as a
124 /// whole can continue. The user should be notified and may need to
125 /// take action.
126 ///
127 /// # Example Scenarios
128 ///
129 /// - Invalid color format in config
130 /// - Module failed to load
131 /// - Network request timed out
132 Error,
133
134 /// Unrecoverable failure, shell cannot continue.
135 ///
136 /// Use only for catastrophic failures where the shell cannot possibly
137 /// function. This should be rare — prefer [`Error`](Severity::Error)
138 /// when recovery is possible.
139 ///
140 /// # Example Scenarios
141 ///
142 /// - Core configuration file is invalid TOML
143 /// - Required system service unavailable
144 /// - Out of memory
145 Fatal,
146}
147
148impl Severity {
149 /// Returns the string representation of this severity.
150 ///
151 /// The returned string is lowercase and suitable for logging or
152 /// serialization.
153 ///
154 /// # Examples
155 ///
156 /// ```rust
157 /// use fernctl::error::Severity;
158 ///
159 /// assert_eq!(Severity::Info.as_str(), "info");
160 /// assert_eq!(Severity::Warning.as_str(), "warning");
161 /// assert_eq!(Severity::Error.as_str(), "error");
162 /// assert_eq!(Severity::Fatal.as_str(), "fatal");
163 /// ```
164 #[must_use]
165 pub const fn as_str(&self) -> &'static str {
166 match self {
167 Self::Info => "info",
168 Self::Warning => "warning",
169 Self::Error => "error",
170 Self::Fatal => "fatal",
171 }
172 }
173
174 /// Returns a Unicode icon representing this severity.
175 ///
176 /// These icons are designed for terminal output and provide quick visual
177 /// identification of severity levels.
178 ///
179 /// # Examples
180 ///
181 /// ```rust
182 /// use fernctl::error::Severity;
183 ///
184 /// assert_eq!(Severity::Info.icon(), "ℹ");
185 /// assert_eq!(Severity::Warning.icon(), "⚠");
186 /// assert_eq!(Severity::Error.icon(), "✗");
187 /// assert_eq!(Severity::Fatal.icon(), "💀");
188 /// ```
189 ///
190 /// # Terminal Output
191 ///
192 /// ```text
193 /// ℹ Configuration loaded
194 /// ⚠ Unknown key 'colour' (did you mean 'color'?)
195 /// ✗ Invalid color format: #gg0000
196 /// 💀 Cannot start: config.toml is not valid TOML
197 /// ```
198 #[must_use]
199 pub const fn icon(&self) -> &'static str {
200 match self {
201 Self::Info => "ℹ",
202 Self::Warning => "⚠",
203 Self::Error => "✗",
204 Self::Fatal => "💀",
205 }
206 }
207
208 /// Returns an ANSI color code for terminal styling.
209 ///
210 /// These codes are suitable for colorizing terminal output. Use with
211 /// `\x1b[0m` to reset styling.
212 ///
213 /// # Colors
214 ///
215 /// | Severity | Color |
216 /// |----------|-------|
217 /// | Info | Blue |
218 /// | Warning | Yellow |
219 /// | Error | Red |
220 /// | Fatal | Magenta (bright) |
221 ///
222 /// # Example
223 ///
224 /// ```rust
225 /// use fernctl::error::Severity;
226 ///
227 /// let sev = Severity::Error;
228 /// let reset = "\x1b[0m";
229 /// println!("{}{} Something went wrong{}", sev.ansi_color(), sev.icon(), reset);
230 /// ```
231 #[must_use]
232 pub const fn ansi_color(&self) -> &'static str {
233 match self {
234 Self::Info => "\x1b[34m", // Blue
235 Self::Warning => "\x1b[33m", // Yellow
236 Self::Error => "\x1b[31m", // Red
237 Self::Fatal => "\x1b[95m", // Bright magenta
238 }
239 }
240
241 /// Returns `true` if this severity indicates an error condition.
242 ///
243 /// An error condition is either [`Error`](Severity::Error) or
244 /// [`Fatal`](Severity::Fatal). This is useful for deciding whether
245 /// to fail an operation.
246 ///
247 /// # Examples
248 ///
249 /// ```rust
250 /// use fernctl::error::Severity;
251 ///
252 /// assert!(!Severity::Info.is_error());
253 /// assert!(!Severity::Warning.is_error());
254 /// assert!(Severity::Error.is_error());
255 /// assert!(Severity::Fatal.is_error());
256 /// ```
257 #[must_use]
258 pub const fn is_error(&self) -> bool {
259 matches!(self, Self::Error | Self::Fatal)
260 }
261
262 /// Returns `true` if this severity is fatal.
263 ///
264 /// Fatal severity indicates the shell cannot continue and should exit.
265 ///
266 /// # Examples
267 ///
268 /// ```rust
269 /// use fernctl::error::Severity;
270 ///
271 /// assert!(!Severity::Error.is_fatal());
272 /// assert!(Severity::Fatal.is_fatal());
273 /// ```
274 #[must_use]
275 pub const fn is_fatal(&self) -> bool {
276 matches!(self, Self::Fatal)
277 }
278
279 /// Returns all severity levels in order from least to most severe.
280 ///
281 /// Useful for iteration or building UI elements like filters.
282 ///
283 /// # Example
284 ///
285 /// ```rust
286 /// use fernctl::error::Severity;
287 ///
288 /// for sev in Severity::all() {
289 /// println!("{}: {}", sev.icon(), sev.as_str());
290 /// }
291 /// ```
292 #[must_use]
293 pub const fn all() -> &'static [Severity] {
294 &[Self::Info, Self::Warning, Self::Error, Self::Fatal]
295 }
296}
297
298impl fmt::Display for Severity {
299 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
300 write!(f, "{}", self.as_str())
301 }
302}
303
304impl Default for Severity {
305 /// Returns [`Severity::Info`] as the default severity.
306 fn default() -> Self {
307 Self::Info
308 }
309}
310
311#[cfg(test)]
312mod tests {
313 use super::*;
314
315 #[test]
316 fn ordering_is_correct() {
317 assert!(Severity::Info < Severity::Warning);
318 assert!(Severity::Warning < Severity::Error);
319 assert!(Severity::Error < Severity::Fatal);
320 }
321
322 #[test]
323 fn serialization_roundtrip() {
324 for sev in Severity::all() {
325 let json = serde_json::to_string(sev).expect("serialize");
326 let back: Severity = serde_json::from_str(&json).expect("deserialize");
327 assert_eq!(*sev, back);
328 }
329 }
330
331 #[test]
332 fn display_matches_as_str() {
333 for sev in Severity::all() {
334 assert_eq!(sev.to_string(), sev.as_str());
335 }
336 }
337
338 #[test]
339 fn is_error_correctness() {
340 assert!(!Severity::Info.is_error());
341 assert!(!Severity::Warning.is_error());
342 assert!(Severity::Error.is_error());
343 assert!(Severity::Fatal.is_error());
344 }
345}