hojicha-core 0.2.2

Core Elm Architecture abstractions for terminal UIs in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//! Error handling for the hojicha framework
//!
//! This module provides a structured approach to error handling throughout the framework.

use std::fmt;
use std::io;
use thiserror::Error;

/// Result type alias for hojicha operations
pub type Result<T> = std::result::Result<T, Error>;

/// Main error type for the hojicha framework
#[derive(Debug, Error)]
pub enum Error {
    /// I/O error (terminal operations, file access, etc.)
    #[error("I/O error: {0}")]
    Io(#[from] io::Error),

    /// Terminal-specific error
    #[error("Terminal error: {0}")]
    Terminal(String),

    /// Event handling error
    #[error("Event error: {0}")]
    Event(String),

    /// Command execution error
    #[error("Command error: {0}")]
    Command(String),

    /// Component error
    #[error("Component error: {0}")]
    Component(String),

    /// Model update error
    #[error("Model error: {0}")]
    Model(String),

    /// Configuration error
    #[error("Configuration error: {0}")]
    Config(String),

    /// Custom error for user-defined errors
    #[error("Custom error: {0}")]
    Custom(#[source] Box<dyn std::error::Error + Send + Sync>),

    /// Async runtime error
    #[error("Async runtime error: {0}")]
    AsyncRuntime(String),

    /// Resource limit exceeded
    #[error("Resource limit exceeded: {0}")]
    ResourceLimit(String),

    /// Validation error
    #[error("Validation error: {0}")]
    Validation(String),

    /// Parsing error
    #[error("Parsing error: {0}")]
    Parse(String),

    /// Timeout error
    #[error("Operation timed out: {0}")]
    Timeout(String),

    /// Channel send error (made generic without the type parameter)
    #[error("Channel send error: {0}")]
    ChannelSend(String),

    /// Channel receive error
    #[error("Channel receive error")]
    ChannelRecv(#[from] std::sync::mpsc::RecvError),
}

// From impls for io::Error and RecvError are handled by thiserror's #[from] attribute

impl<T> From<std::sync::mpsc::SendError<T>> for Error {
    fn from(err: std::sync::mpsc::SendError<T>) -> Self {
        Error::ChannelSend(format!("Failed to send message: {err}"))
    }
}

impl From<tokio::time::error::Elapsed> for Error {
    fn from(err: tokio::time::error::Elapsed) -> Self {
        Error::Timeout(format!("Operation timed out: {err}"))
    }
}

/// Error context trait for adding context to errors
pub trait ErrorContext<T> {
    /// Add context to an error
    fn context(self, msg: &str) -> Result<T>;

    /// Add context with a closure
    fn with_context<F>(self, f: F) -> Result<T>
    where
        F: FnOnce() -> String;
}

impl<T, E> ErrorContext<T> for std::result::Result<T, E>
where
    E: Into<Error>,
{
    fn context(self, msg: &str) -> Result<T> {
        self.map_err(|err| {
            let base_error = err.into();
            Error::Custom(Box::new(ContextError {
                context: msg.to_string(),
                source: base_error,
            }))
        })
    }

    fn with_context<F>(self, f: F) -> Result<T>
    where
        F: FnOnce() -> String,
    {
        self.map_err(|err| {
            let base_error = err.into();
            Error::Custom(Box::new(ContextError {
                context: f(),
                source: base_error,
            }))
        })
    }
}

/// Error with additional context
#[derive(Debug)]
struct ContextError {
    context: String,
    source: Error,
}

impl fmt::Display for ContextError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.context, self.source)
    }
}

impl std::error::Error for ContextError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.source)
    }
}

/// Error handler trait for models
pub trait ErrorHandler {
    /// Handle an error, returning true if the error was handled
    fn handle_error(&mut self, error: Error) -> bool;
}

/// Default error handler that logs errors to stderr
pub struct DefaultErrorHandler;

impl ErrorHandler for DefaultErrorHandler {
    fn handle_error(&mut self, error: Error) -> bool {
        eprintln!("Error: {error}");

        // Print error chain
        let mut current_error: &dyn std::error::Error = &error;
        while let Some(source) = current_error.source() {
            eprintln!("  Caused by: {source}");
            current_error = source;
        }

        false // Error not handled, program should exit
    }
}

/// Panic handler for converting panics to errors
pub fn set_panic_handler() {
    std::panic::set_hook(Box::new(|panic_info| {
        let msg = if let Some(s) = panic_info.payload().downcast_ref::<&str>() {
            s.to_string()
        } else if let Some(s) = panic_info.payload().downcast_ref::<String>() {
            s.clone()
        } else {
            "Unknown panic".to_string()
        };

        let location = if let Some(location) = panic_info.location() {
            format!(
                " at {}:{}:{}",
                location.file(),
                location.line(),
                location.column()
            )
        } else {
            String::new()
        };

        eprintln!("Panic occurred: {msg}{location}");
    }));
}

/// Helper macro for creating errors with context
#[macro_export]
macro_rules! bail {
    ($msg:literal $(,)?) => {
        return Err($crate::error::Error::Custom(
            format!($msg).into()
        ))
    };
    ($err:expr $(,)?) => {
        return Err($crate::error::Error::Custom(
            format!("{}", $err).into()
        ))
    };
    ($fmt:expr, $($arg:tt)*) => {
        return Err($crate::error::Error::Custom(
            format!($fmt, $($arg)*).into()
        ))
    };
}

/// Helper macro for ensuring conditions
#[macro_export]
macro_rules! ensure {
    ($cond:expr, $msg:literal $(,)?) => {
        if !$cond {
            $crate::bail!($msg);
        }
    };
    ($cond:expr, $err:expr $(,)?) => {
        if !$cond {
            $crate::bail!($err);
        }
    };
    ($cond:expr, $fmt:expr, $($arg:tt)*) => {
        if !$cond {
            $crate::bail!($fmt, $($arg)*);
        }
    };
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::error::Error as StdError;

    #[test]
    fn test_error_display() {
        let err = Error::Terminal("Failed to initialize".to_string());
        assert_eq!(err.to_string(), "Terminal error: Failed to initialize");

        let err = Error::Io(io::Error::new(io::ErrorKind::NotFound, "File not found"));
        assert_eq!(err.to_string(), "I/O error: File not found");
    }

    #[test]
    fn test_error_context() {
        let result: Result<()> = Err(Error::Terminal("Base error".to_string()));
        let with_context = result.context("While initializing terminal");

        assert!(with_context.is_err());
        let err_str = with_context.unwrap_err().to_string();
        assert!(err_str.contains("While initializing terminal"));
        assert!(err_str.contains("Base error"));
    }

    #[test]
    fn test_error_from_io() {
        let io_err = io::Error::new(io::ErrorKind::PermissionDenied, "Access denied");
        let err: Error = io_err.into();

        match err {
            Error::Io(_) => (),
            _ => panic!("Expected Io error variant"),
        }
    }

    #[test]
    fn test_bail_macro() {
        fn test_fn() -> Result<()> {
            bail!("Test error");
        }

        assert!(test_fn().is_err());
        assert_eq!(
            test_fn().unwrap_err().to_string(),
            "Custom error: Test error"
        );
    }

    #[test]
    fn test_ensure_macro() {
        fn test_fn(value: i32) -> Result<i32> {
            ensure!(value > 0, "Value must be positive");
            Ok(value)
        }

        assert!(test_fn(5).is_ok());
        assert!(test_fn(-1).is_err());
    }

    #[test]
    fn test_all_error_variants() {
        let errors = vec![
            Error::Terminal("terminal error".to_string()),
            Error::Event("event error".to_string()),
            Error::Command("command error".to_string()),
            Error::Component("component error".to_string()),
            Error::Model("model error".to_string()),
            Error::Config("config error".to_string()),
        ];

        for error in errors {
            let display_str = error.to_string();
            assert!(!display_str.is_empty());

            // Test that source returns None for string-based errors
            assert!(error.source().is_none());
        }
    }

    #[test]
    fn test_error_source_chain() {
        let io_err = io::Error::new(io::ErrorKind::NotFound, "File not found");
        let err = Error::Io(io_err);

        // Should have a source
        assert!(StdError::source(&err).is_some());

        let source = err.source().unwrap();
        assert_eq!(source.to_string(), "File not found");
    }

    #[test]
    fn test_custom_error() {
        let custom_err = Box::new(io::Error::other("custom"));
        let err = Error::Custom(custom_err);

        assert!(StdError::source(&err).is_some());
        assert!(err.to_string().contains("Custom error"));
    }

    #[test]
    fn test_channel_error_conversions() {
        let recv_err = std::sync::mpsc::RecvError;
        let err: Error = recv_err.into();

        match err {
            Error::ChannelRecv(_) => (),
            _ => panic!("Expected ChannelRecv error variant"),
        }

        let (tx, _rx) = std::sync::mpsc::channel::<i32>();
        drop(_rx); // Close receiver to cause send error

        let send_result = tx.send(42);
        if let Err(send_err) = send_result {
            let err: Error = send_err.into();
            match err {
                Error::ChannelSend(_) => (),
                _ => panic!("Expected ChannelSend error variant"),
            }
        }
    }

    #[test]
    fn test_with_context() {
        let result: Result<()> = Err(Error::Terminal("Base error".to_string()));
        let with_context = result.with_context(|| "Dynamic context".to_string());

        assert!(with_context.is_err());
        let err_str = with_context.unwrap_err().to_string();
        assert!(err_str.contains("Dynamic context"));
    }

    #[test]
    fn test_default_error_handler() {
        let mut handler = DefaultErrorHandler;
        let error = Error::Terminal("test error".to_string());

        // Should return false (error not handled)
        assert!(!handler.handle_error(error));
    }

    #[test]
    fn test_context_error() {
        let base_error = Error::Terminal("base".to_string());
        let context_error = ContextError {
            context: "context".to_string(),
            source: base_error,
        };

        let display_str = context_error.to_string();
        assert!(display_str.contains("context"));
        assert!(display_str.contains("base"));

        assert!(StdError::source(&context_error).is_some());
    }

    #[test]
    fn test_bail_macro_with_format() {
        fn test_fn(value: i32) -> Result<()> {
            bail!("Value {} is invalid", value);
        }

        let err = test_fn(42).unwrap_err();
        assert!(err.to_string().contains("Value 42 is invalid"));
    }

    #[test]
    fn test_ensure_macro_with_format() {
        fn test_fn(value: i32, min: i32) -> Result<i32> {
            ensure!(value >= min, "Value {} must be >= {}", value, min);
            Ok(value)
        }

        assert!(test_fn(10, 5).is_ok());

        let err = test_fn(3, 5).unwrap_err();
        assert!(err.to_string().contains("Value 3 must be >= 5"));
    }

    #[test]
    fn test_panic_handler() {
        // Test that we can set the panic handler without panicking
        set_panic_handler();

        // Reset to default handler
        let _ = std::panic::take_hook();
    }

    #[test]
    fn test_new_error_variants() {
        let errors = vec![
            Error::AsyncRuntime("async error".to_string()),
            Error::ResourceLimit("limit exceeded".to_string()),
            Error::Validation("invalid input".to_string()),
            Error::Parse("parse failed".to_string()),
            Error::Timeout("timed out".to_string()),
            Error::ChannelSend("send failed".to_string()),
        ];

        for error in errors {
            let display_str = error.to_string();
            assert!(!display_str.is_empty());

            // Test that these string-based errors have no source
            assert!(error.source().is_none());
        }
    }

    #[test]
    fn test_timeout_error_conversion() {
        // Just test the timeout error conversion without actually using tokio
        let err = Error::Timeout("Operation timed out".to_string());
        assert!(err.to_string().contains("timed out"));
    }

    #[test]
    fn test_error_display_messages() {
        // Test that all error variants have proper display messages
        assert_eq!(
            Error::Io(io::Error::new(io::ErrorKind::NotFound, "file")).to_string(),
            "I/O error: file"
        );
        assert_eq!(
            Error::Terminal("term".to_string()).to_string(),
            "Terminal error: term"
        );
        assert_eq!(
            Error::Event("evt".to_string()).to_string(),
            "Event error: evt"
        );
        assert_eq!(
            Error::Command("cmd".to_string()).to_string(),
            "Command error: cmd"
        );
        assert_eq!(
            Error::Component("comp".to_string()).to_string(),
            "Component error: comp"
        );
        assert_eq!(
            Error::Model("model".to_string()).to_string(),
            "Model error: model"
        );
        assert_eq!(
            Error::Config("cfg".to_string()).to_string(),
            "Configuration error: cfg"
        );
        assert_eq!(
            Error::AsyncRuntime("async".to_string()).to_string(),
            "Async runtime error: async"
        );
        assert_eq!(
            Error::ResourceLimit("limit".to_string()).to_string(),
            "Resource limit exceeded: limit"
        );
        assert_eq!(
            Error::Validation("valid".to_string()).to_string(),
            "Validation error: valid"
        );
        assert_eq!(
            Error::Parse("parse".to_string()).to_string(),
            "Parsing error: parse"
        );
        assert_eq!(
            Error::Timeout("timeout".to_string()).to_string(),
            "Operation timed out: timeout"
        );
        assert_eq!(
            Error::ChannelSend("send".to_string()).to_string(),
            "Channel send error: send"
        );
    }
}