nu_protocol/errors/
cli_error.rs

1//! This module manages the step of turning error types into printed error messages
2//!
3//! Relies on the `miette` crate for pretty layout
4use crate::{
5    engine::{EngineState, StateWorkingSet},
6    CompileError, ErrorStyle, ParseError, ParseWarning, ShellError,
7};
8use miette::{
9    LabeledSpan, MietteHandlerOpts, NarratableReportHandler, ReportHandler, RgbColors, Severity,
10    SourceCode,
11};
12use thiserror::Error;
13
14/// This error exists so that we can defer SourceCode handling. It simply
15/// forwards most methods, except for `.source_code()`, which we provide.
16#[derive(Error)]
17#[error("{0}")]
18struct CliError<'src>(
19    pub &'src dyn miette::Diagnostic,
20    pub &'src StateWorkingSet<'src>,
21);
22
23pub fn format_shell_error(working_set: &StateWorkingSet, error: &ShellError) -> String {
24    format!("Error: {:?}", CliError(error, working_set))
25}
26
27pub fn report_shell_error(engine_state: &EngineState, error: &ShellError) {
28    if engine_state.config.display_errors.should_show(error) {
29        report_error(&StateWorkingSet::new(engine_state), error)
30    }
31}
32
33pub fn report_shell_warning(engine_state: &EngineState, error: &ShellError) {
34    if engine_state.config.display_errors.should_show(error) {
35        report_warning(&StateWorkingSet::new(engine_state), error)
36    }
37}
38
39pub fn report_parse_error(working_set: &StateWorkingSet, error: &ParseError) {
40    report_error(working_set, error);
41}
42
43pub fn report_parse_warning(working_set: &StateWorkingSet, error: &ParseWarning) {
44    report_warning(working_set, error);
45}
46
47pub fn report_compile_error(working_set: &StateWorkingSet, error: &CompileError) {
48    report_error(working_set, error);
49}
50
51fn report_error(working_set: &StateWorkingSet, error: &dyn miette::Diagnostic) {
52    eprintln!("Error: {:?}", CliError(error, working_set));
53    // reset vt processing, aka ansi because illbehaved externals can break it
54    #[cfg(windows)]
55    {
56        let _ = nu_utils::enable_vt_processing();
57    }
58}
59
60fn report_warning(working_set: &StateWorkingSet, error: &dyn miette::Diagnostic) {
61    eprintln!("Warning: {:?}", CliError(error, working_set));
62    // reset vt processing, aka ansi because illbehaved externals can break it
63    #[cfg(windows)]
64    {
65        let _ = nu_utils::enable_vt_processing();
66    }
67}
68
69impl std::fmt::Debug for CliError<'_> {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        let config = self.1.get_config();
72
73        let ansi_support = config.use_ansi_coloring.get(self.1.permanent());
74
75        let error_style = &config.error_style;
76
77        let miette_handler: Box<dyn ReportHandler> = match error_style {
78            ErrorStyle::Plain => Box::new(NarratableReportHandler::new()),
79            ErrorStyle::Fancy => Box::new(
80                MietteHandlerOpts::new()
81                    // For better support of terminal themes use the ANSI coloring
82                    .rgb_colors(RgbColors::Never)
83                    // If ansi support is disabled in the config disable the eye-candy
84                    .color(ansi_support)
85                    .unicode(ansi_support)
86                    .terminal_links(ansi_support)
87                    .build(),
88            ),
89        };
90
91        // Ignore error to prevent format! panics. This can happen if span points at some
92        // inaccessible location, for example by calling `report_error()` with wrong working set.
93        let _ = miette_handler.debug(self, f);
94
95        Ok(())
96    }
97}
98
99impl miette::Diagnostic for CliError<'_> {
100    fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
101        self.0.code()
102    }
103
104    fn severity(&self) -> Option<Severity> {
105        self.0.severity()
106    }
107
108    fn help<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
109        self.0.help()
110    }
111
112    fn url<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
113        self.0.url()
114    }
115
116    fn labels<'a>(&'a self) -> Option<Box<dyn Iterator<Item = LabeledSpan> + 'a>> {
117        self.0.labels()
118    }
119
120    // Finally, we redirect the source_code method to our own source.
121    fn source_code(&self) -> Option<&dyn SourceCode> {
122        if let Some(source_code) = self.0.source_code() {
123            Some(source_code)
124        } else {
125            Some(&self.1)
126        }
127    }
128
129    fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn miette::Diagnostic> + 'a>> {
130        self.0.related()
131    }
132
133    fn diagnostic_source(&self) -> Option<&dyn miette::Diagnostic> {
134        self.0.diagnostic_source()
135    }
136}