intelli_shell/
errors.rs

1use std::{
2    env,
3    panic::{self, UnwindSafe},
4    path::PathBuf,
5    process,
6};
7
8use color_eyre::{Report, Section, config::HookBuilder, owo_colors::style};
9use futures_util::FutureExt;
10use tokio::sync::mpsc;
11
12/// A top-level error enum for the entire application
13#[derive(Debug)]
14pub enum AppError {
15    /// A controlled, expected error that can be safely displayed to the end-user
16    UserFacing(UserFacingError),
17    /// An unexpected, internal error
18    Unexpected(Report),
19}
20
21/// A specialized `Result` type for this application
22pub type Result<T, E = AppError> = std::result::Result<T, E>;
23
24/// Initializes error and panics handling
25pub async fn init<F>(log_path: Option<PathBuf>, fut: F) -> Result<(), Report>
26where
27    F: Future<Output = Result<(), Report>> + UnwindSafe,
28{
29    tracing::trace!("Initializing error handlers");
30    // Initialize hooks
31    let panic_section = if let Some(log_path) = log_path {
32        format!(
33            "This is a bug. Consider reporting it at {}\nLogs can be found at {}",
34            env!("CARGO_PKG_REPOSITORY"),
35            log_path.display()
36        )
37    } else {
38        format!(
39            "This is a bug. Consider reporting it at {}\nLogs were not generated, consider enabling them on the \
40             config or running with INTELLI_LOG=debug.",
41            env!("CARGO_PKG_REPOSITORY")
42        )
43    };
44    let (panic_hook, eyre_hook) = HookBuilder::default()
45        .panic_section(panic_section.clone())
46        .display_env_section(false)
47        .display_location_section(true)
48        .capture_span_trace_by_default(true)
49        .into_hooks();
50
51    // Initialize panic notifier
52    let (panic_tx, mut panic_rx) = mpsc::channel(1);
53
54    // Install both hooks
55    eyre_hook.install()?;
56    panic::set_hook(Box::new(move |panic_info| {
57        // At this point the TUI might still be in raw mode, so we can't print to stderr here
58        // Instead, we're sending the report through a channel, to be handled after the main future is dropped
59        let panic_report = panic_hook.panic_report(panic_info).to_string();
60        tracing::error!("Error: {}", strip_ansi_escapes::strip_str(&panic_report));
61        if panic_tx.try_send(panic_report).is_err() {
62            tracing::error!("Error sending panic report",);
63            process::exit(2);
64        }
65    }));
66
67    tokio::select! {
68        biased;
69        // Wait for a panic to be notified
70        panic_report = panic_rx.recv().fuse() => {
71            if let Some(report) = panic_report {
72                eprintln!("{report}");
73            } else {
74                eprintln!(
75                    "{}\n\n{panic_section}",
76                    style().bright_red().style("A panic occurred, but the detailed report could not be captured.")
77                );
78                tracing::error!("A panic occurred, but the detailed report could not be captured.");
79            }
80            // Exit with a non-zero status code
81            process::exit(1);
82        }
83        // Or for the main future to finish, catching unwinding panics
84        res = Box::pin(fut).catch_unwind() => {
85            match res {
86                Ok(r) => r
87                    .with_section(move || panic_section)
88                    .inspect_err(|err| tracing::error!("Error: {}", strip_ansi_escapes::strip_str(format!("{err:?}")))),
89                Err(err) => {
90                    if let Ok(report) = panic_rx.try_recv() {
91                        eprintln!("{report}");
92                    } else if let Some(err) = err.downcast_ref::<&str>() {
93                        print_panic_msg(err, panic_section);
94                    } else if let Some(err) = err.downcast_ref::<String>() {
95                        print_panic_msg(err, panic_section);
96                    } else {
97                        eprintln!(
98                            "{}\n\n{panic_section}",
99                            style().bright_red().style("An unexpected panic happened")
100                        );
101                        tracing::error!("An unexpected panic happened");
102                    }
103                    // Exit with a non-zero status code
104                    process::exit(1);
105                }
106            }
107        }
108    }
109}
110
111fn print_panic_msg(err: impl AsRef<str>, panic_section: String) {
112    let err = err.as_ref();
113    eprintln!(
114        "{}\nMessage: {}\n\n{panic_section}",
115        style().bright_red().style("The application panicked (crashed)."),
116        style().blue().style(err)
117    );
118    tracing::error!("Panic: {err}");
119}
120
121/// Represents all possible errors that are meant to be displayed to the end-user
122#[derive(Debug, strum::Display)]
123pub enum UserFacingError {
124    /// The operation was cancelled by the user
125    #[strum(to_string = "Operation cancelled by user")]
126    Cancelled,
127    /// The regex pattern provided for a search is invalid
128    #[strum(to_string = "Invalid regex pattern")]
129    InvalidRegex,
130    /// A fuzzy search was attempted without providing a valid search term
131    #[strum(to_string = "Invalid fuzzy search")]
132    InvalidFuzzy,
133    /// An attempt was made to save an empty command
134    #[strum(to_string = "Command cannot be empty")]
135    EmptyCommand,
136    /// The user tried to save a command that is already bookmarked
137    #[strum(to_string = "Command is already bookmarked")]
138    CommandAlreadyExists,
139    /// The user tried to save a variable value that already exists
140    #[strum(to_string = "Value already exists")]
141    VariableValueAlreadyExists,
142    /// The user tried to save a completion that already exists
143    #[strum(to_string = "Variable completion already exists")]
144    CompletionAlreadyExists,
145    /// An attempt was made to save a completion with an invalid command
146    #[strum(to_string = "Completion command can contain only alphanumeric characters or hyphen")]
147    CompletionInvalidCommand,
148    /// An attempt was made to save a completion with an empty variable
149    #[strum(to_string = "Completion variable cannot be empty")]
150    CompletionEmptyVariable,
151    /// An attempt was made to save a completion with an invalid variable
152    #[strum(to_string = "Completion variable can't contain pipe, colon or braces")]
153    CompletionInvalidVariable,
154    /// An attempt was made to save a completion with an empty provider
155    #[strum(to_string = "Completion provider cannot be empty")]
156    CompletionEmptySuggestionsProvider,
157    /// A completion was not properly formatted when importing
158    #[strum(to_string = "Invalid completion format: {0}")]
159    ImportCompletionInvalidFormat(String),
160    /// The path for an import operation points to a directory or symlink, not a regular file
161    #[strum(to_string = "Import path must be a file; directories and symlinks are not supported")]
162    ImportLocationNotAFile,
163    /// The file specified for an import operation could not be found
164    #[strum(to_string = "File not found")]
165    ImportFileNotFound,
166    /// The path for an export operation already exists and is not a regular file
167    #[strum(to_string = "The path already exists and it's not a file")]
168    ExportLocationNotAFile,
169    /// The parent directory for a file to be exported does not exist
170    #[strum(to_string = "Destination directory does not exist")]
171    ExportFileParentNotFound,
172    /// An attempt was made to export to a specific Gist revision (SHA), which is not allowed
173    #[strum(to_string = "Cannot export to a gist revision, provide a gist without a revision")]
174    ExportGistLocationHasSha,
175    /// A GitHub personal access token is required for exporting to a Gist but was not found
176    #[strum(to_string = "GitHub token required for Gist export, set GIST_TOKEN env var or update config")]
177    ExportGistMissingToken,
178    /// The application lacks the necessary permissions to read from or write to a file
179    #[strum(to_string = "Cannot access the file, check {0} permissions")]
180    FileNotAccessible(&'static str),
181    /// A "broken pipe" error occurred while writing to a file
182    #[strum(to_string = "broken pipe")]
183    FileBrokenPipe,
184    /// The URL provided for an HTTP operation is malformed
185    #[strum(to_string = "Invalid URL, please provide a valid HTTP/S address")]
186    HttpInvalidUrl,
187    /// An HTTP request to a remote URL has failed
188    #[strum(to_string = "HTTP request failed: {0}")]
189    HttpRequestFailed(String),
190    /// A required GitHub Gist ID was not provided via arguments or configuration
191    #[strum(to_string = "Gist ID is missing, provide it as an argument or in the config file")]
192    GistMissingId,
193    /// The provided Gist identifier (ID or URL) is malformed or invalid
194    #[strum(to_string = "The provided gist is not valid, please provide a valid id or URL")]
195    GistInvalidLocation,
196    /// The specified file within the target GitHub Gist could not be found
197    #[strum(to_string = "File not found within the specified Gist")]
198    GistFileNotFound,
199    /// A request to the GitHub Gist API has failed
200    #[strum(to_string = "Gist request failed: {0}")]
201    GistRequestFailed(String),
202    /// The user's home directory could not be determined, preventing access to shell history
203    #[strum(to_string = "Could not determine home directory")]
204    HistoryHomeDirNotFound,
205    /// The history file for the specified shell could not be found
206    #[strum(to_string = "History file not found at: {0}")]
207    HistoryFileNotFound(String),
208    /// The `nu` command is required for importing history but was not found in the system's PATH
209    #[strum(to_string = "Nushell not found, make sure it is installed and in your PATH")]
210    HistoryNushellNotFound,
211    /// The `nu` command failed to execute
212    #[strum(to_string = "Error running nu, maybe it is an old version")]
213    HistoryNushellFailed,
214    /// The `atuin` command is required for importing history but was not found in the system's PATH
215    #[strum(to_string = "Atuin not found, make sure it is installed and in your PATH")]
216    HistoryAtuinNotFound,
217    /// The `atuin` command failed to execute
218    #[strum(to_string = "Error running atuin, maybe it is an old version")]
219    HistoryAtuinFailed,
220    /// An AI-related feature was used, but AI is not enabled in the configuration
221    #[strum(to_string = "AI feature is disabled, enable it in the config file to use this functionality")]
222    AiRequired,
223    /// The command is missing or empty
224    #[strum(to_string = "A command must be provided")]
225    AiEmptyCommand,
226    /// The API key for the AI service is either missing, invalid, or lacks necessary permissions
227    #[strum(to_string = "API key in '{0}' env variable is missing, invalid, or lacks permissions")]
228    AiMissingOrInvalidApiKey(String),
229    /// The request to the AI provider timed out while waiting for a response
230    #[strum(to_string = "Request to AI provider timed out")]
231    AiRequestTimeout,
232    /// Service unavailable when calling AI provider
233    #[strum(to_string = "AI provider responded with status 503 Service Unavailable")]
234    AiUnavailable,
235    /// A generic error occurred while making a request to the AI provider's API
236    #[strum(to_string = "AI request failed: {0}")]
237    AiRequestFailed(String),
238    /// The request was rejected by the AI provider due to rate limiting
239    #[strum(to_string = "AI request rate-limited, try again later")]
240    AiRateLimit,
241}
242
243impl AppError {
244    /// Converts this error into a [Report]
245    pub fn into_report(self) -> Report {
246        match self {
247            AppError::UserFacing(err) => Report::msg(err),
248            AppError::Unexpected(report) => report,
249        }
250    }
251}
252impl From<UserFacingError> for AppError {
253    fn from(err: UserFacingError) -> Self {
254        Self::UserFacing(err)
255    }
256}
257impl<T: Into<Report>> From<T> for AppError {
258    fn from(err: T) -> Self {
259        Self::Unexpected(err.into())
260    }
261}
262
263/// Similar to the `std::dbg!` macro, but generates `tracing` events rather
264/// than printing to stdout.
265///
266/// By default, the verbosity level for the generated events is `DEBUG`, but
267/// this can be customized.
268#[macro_export]
269macro_rules! trace_dbg {
270    (target: $target:expr, level: $level:expr, $ex:expr) => {
271        {
272            match $ex {
273                value => {
274                    tracing::event!(target: $target, $level, ?value, stringify!($ex));
275                    value
276                }
277            }
278        }
279    };
280    (level: $level:expr, $ex:expr) => {
281        $crate::trace_dbg!(target: module_path!(), level: $level, $ex)
282    };
283    (target: $target:expr, $ex:expr) => {
284        $crate::trace_dbg!(target: $target, level: tracing::Level::DEBUG, $ex)
285    };
286    ($ex:expr) => {
287        $crate::trace_dbg!(level: tracing::Level::DEBUG, $ex)
288    };
289}