errcraft 0.1.0

Beautiful, structured, and colorful error handling for 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
//! Display and rendering utilities for error frames.

use crate::{utils, ErrFrame};
use std::fmt::Write;

/// Options for controlling error display.
#[derive(Debug, Clone)]
pub struct DisplayOptions {
    /// Whether to use emoji in output
    pub emoji: bool,
    /// Color mode for output
    pub color: ColorMode,
    /// Maximum depth for nested errors (None = unlimited)
    pub max_depth: Option<usize>,
    /// Backtrace display mode
    pub show_backtrace: BacktraceMode,
}

impl Default for DisplayOptions {
    fn default() -> Self {
        Self {
            emoji: cfg!(feature = "emoji"),
            color: ColorMode::Auto,
            max_depth: None,
            show_backtrace: BacktraceMode::Auto,
        }
    }
}

impl DisplayOptions {
    /// Creates new display options with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets whether to use emoji.
    pub fn with_emoji(mut self, emoji: bool) -> Self {
        self.emoji = emoji;
        self
    }

    /// Sets the color mode.
    pub fn with_color(mut self, color: ColorMode) -> Self {
        self.color = color;
        self
    }

    /// Sets the maximum depth for nested errors.
    pub fn with_max_depth(mut self, depth: Option<usize>) -> Self {
        self.max_depth = depth;
        self
    }

    /// Sets the backtrace display mode.
    pub fn with_backtrace(mut self, mode: BacktraceMode) -> Self {
        self.show_backtrace = mode;
        self
    }

    /// Loads display options from environment variables.
    pub fn from_env() -> Self {
        let mut opts = Self::default();

        // Check NO_COLOR environment variable
        if std::env::var("NO_COLOR").is_ok() {
            opts.color = ColorMode::Never;
        }

        // Check RUST_BACKTRACE
        if let Ok(val) = std::env::var("RUST_BACKTRACE") {
            if val == "1" || val == "full" {
                opts.show_backtrace = BacktraceMode::Shown;
            }
        }

        opts
    }

    /// Determines if colors should be used based on current settings and TTY detection.
    pub fn should_colorize(&self) -> bool {
        match self.color {
            ColorMode::Always => true,
            ColorMode::Never => false,
            ColorMode::Auto => {
                #[cfg(feature = "is-terminal")]
                {
                    use is_terminal::IsTerminal;
                    std::io::stderr().is_terminal()
                }
                #[cfg(not(feature = "is-terminal"))]
                {
                    false
                }
            }
        }
    }
}

/// Color mode for error display.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorMode {
    /// Automatically detect based on TTY
    Auto,
    /// Always use colors
    Always,
    /// Never use colors
    Never,
}

/// Backtrace display mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BacktraceMode {
    /// Automatically decide based on environment
    Auto,
    /// Never show backtraces
    Hidden,
    /// Always show backtraces
    Shown,
}

impl ErrFrame {
    /// Prints the error to stdout with default formatting.
    pub fn print(&self) {
        println!("{}", self.to_string_styled(&DisplayOptions::from_env()));
    }

    /// Prints the error to stderr with default formatting.
    pub fn eprint(&self) {
        eprintln!("{}", self.to_string_styled(&DisplayOptions::from_env()));
    }

    /// Converts the error to a styled string using the given options.
    pub fn to_string_styled(&self, opts: &DisplayOptions) -> String {
        let mut output = String::new();
        let colorize = opts.should_colorize();

        // Error header
        let error_prefix = if opts.emoji { "❌ Error: " } else { "Error: " };

        if colorize {
            write!(
                &mut output,
                "{}{}",
                colorize_text(error_prefix, Color::Red, true),
                colorize_text(&self.message, Color::Red, false)
            )
            .unwrap();
        } else {
            write!(&mut output, "{}{}", error_prefix, self.message).unwrap();
        }
        output.push('\n');

        // Context
        if !self.context.is_empty() {
            output.push('\n');
            let context_prefix = if opts.emoji {
                "📦 Context:"
            } else {
                "Context:"
            };

            if colorize {
                writeln!(
                    &mut output,
                    "{}",
                    colorize_text(context_prefix, Color::Cyan, true)
                )
                .unwrap();
            } else {
                writeln!(&mut output, "{}", context_prefix).unwrap();
            }

            for layer in self.context.iter() {
                if let Some(key) = layer.key() {
                    if colorize {
                        writeln!(
                            &mut output,
                            "   {} = {}",
                            colorize_text(key, Color::Yellow, false),
                            layer.value().as_str()
                        )
                        .unwrap();
                    } else {
                        writeln!(&mut output, "   {} = {}", key, layer.value().as_str()).unwrap();
                    }
                } else {
                    writeln!(&mut output, "   {}", layer.value().as_str()).unwrap();
                }
            }
        }

        // Source chain
        #[cfg(feature = "std")]
        if let Some(source) = self.source.as_ref() {
            output.push('\n');
            let caused_by = if opts.emoji {
                "⚠️  Caused by:"
            } else {
                "Caused by:"
            };

            if colorize {
                writeln!(
                    &mut output,
                    "{}",
                    colorize_text(caused_by, Color::Yellow, true)
                )
                .unwrap();
            } else {
                writeln!(&mut output, "{}", caused_by).unwrap();
            }

            let mut current: &dyn std::error::Error = source.as_ref();
            let mut depth = 0;
            let max_depth = opts.max_depth.unwrap_or(usize::MAX);

            loop {
                if depth >= max_depth {
                    writeln!(
                        &mut output,
                        "   ... ({} more)",
                        count_remaining_sources(current)
                    )
                    .unwrap();
                    break;
                }

                let is_last = current.source().is_none();
                let prefix = if is_last { "  └─ " } else { "  ├─ " };

                if colorize {
                    writeln!(
                        &mut output,
                        "{}{}",
                        prefix,
                        colorize_text(&current.to_string(), Color::White, false)
                    )
                    .unwrap();
                } else {
                    writeln!(&mut output, "{}{}", prefix, current).unwrap();
                }

                if let Some(next) = current.source() {
                    current = next;
                    depth += 1;
                } else {
                    break;
                }
            }
        }

        // Backtrace
        #[cfg(all(feature = "std", feature = "backtrace"))]
        {
            let should_show = match opts.show_backtrace {
                BacktraceMode::Shown => true,
                BacktraceMode::Hidden => false,
                BacktraceMode::Auto => std::env::var("RUST_BACKTRACE").is_ok(),
            };

            if should_show {
                if let Some(bt) = &self.backtrace {
                    if bt.status() == std::backtrace::BacktraceStatus::Captured {
                        output.push('\n');
                        let bt_prefix = if opts.emoji {
                            "📍 Backtrace:"
                        } else {
                            "Backtrace:"
                        };

                        if colorize {
                            writeln!(
                                &mut output,
                                "{}",
                                colorize_text(bt_prefix, Color::Magenta, true)
                            )
                            .unwrap();
                        } else {
                            writeln!(&mut output, "{}", bt_prefix).unwrap();
                        }

                        writeln!(&mut output, "{}", utils::indent(&bt.to_string(), 3)).unwrap();
                    }
                }
            }
        }

        output
    }
}

#[cfg(feature = "std")]
fn count_remaining_sources(mut err: &dyn std::error::Error) -> usize {
    let mut count = 0;
    while let Some(next) = err.source() {
        count += 1;
        err = next;
    }
    count
}

// Color abstraction
#[derive(Debug, Clone, Copy)]
enum Color {
    Red,
    Yellow,
    Cyan,
    Magenta,
    White,
}

fn colorize_text(text: &str, color: Color, bold: bool) -> String {
    #[cfg(feature = "colors-owo")]
    {
        use owo_colors::OwoColorize;
        let result = match color {
            Color::Red => {
                if bold {
                    text.red().bold().to_string()
                } else {
                    text.red().to_string()
                }
            }
            Color::Yellow => {
                if bold {
                    text.yellow().bold().to_string()
                } else {
                    text.yellow().to_string()
                }
            }
            Color::Cyan => {
                if bold {
                    text.cyan().bold().to_string()
                } else {
                    text.cyan().to_string()
                }
            }
            Color::Magenta => {
                if bold {
                    text.magenta().bold().to_string()
                } else {
                    text.magenta().to_string()
                }
            }
            Color::White => {
                if bold {
                    text.white().bold().to_string()
                } else {
                    text.white().to_string()
                }
            }
        };
        result
    }

    #[cfg(all(feature = "colors-yansi", not(feature = "colors-owo")))]
    {
        use yansi::Paint;
        let result = match color {
            Color::Red => {
                if bold {
                    text.red().bold().to_string()
                } else {
                    text.red().to_string()
                }
            }
            Color::Yellow => {
                if bold {
                    text.yellow().bold().to_string()
                } else {
                    text.yellow().to_string()
                }
            }
            Color::Cyan => {
                if bold {
                    text.cyan().bold().to_string()
                } else {
                    text.cyan().to_string()
                }
            }
            Color::Magenta => {
                if bold {
                    text.magenta().bold().to_string()
                } else {
                    text.magenta().to_string()
                }
            }
            Color::White => {
                if bold {
                    text.white().bold().to_string()
                } else {
                    text.white().to_string()
                }
            }
        };
        result
    }

    #[cfg(all(
        feature = "colors-anstyle",
        not(feature = "colors-owo"),
        not(feature = "colors-yansi")
    ))]
    {
        use anstyle::{AnsiColor, Style};
        let style_color = match color {
            Color::Red => AnsiColor::Red,
            Color::Yellow => AnsiColor::Yellow,
            Color::Cyan => AnsiColor::Cyan,
            Color::Magenta => AnsiColor::Magenta,
            Color::White => AnsiColor::White,
        };
        let mut style = Style::new().fg_color(Some(anstyle::Color::Ansi(style_color)));
        if bold {
            style = style.bold();
        }
        format!("{}{}{}", style.render(), text, style.render_reset())
    }

    #[cfg(not(any(
        feature = "colors-owo",
        feature = "colors-yansi",
        feature = "colors-anstyle"
    )))]
    {
        let _ = (color, bold);
        text.to_string()
    }
}