lychee_lib/types/
error.rs

1use http::StatusCode;
2use serde::{Serialize, Serializer};
3use std::error::Error;
4use std::hash::Hash;
5use std::{convert::Infallible, path::PathBuf};
6use thiserror::Error;
7use tokio::task::JoinError;
8
9use super::InputContent;
10use crate::types::StatusCodeSelectorError;
11use crate::{Uri, basic_auth::BasicAuthExtractorError, utils};
12
13/// Kinds of status errors
14/// Note: The error messages can change over time, so don't match on the output
15#[derive(Error, Debug)]
16#[non_exhaustive]
17pub enum ErrorKind {
18    /// Network error while handling request.
19    /// This does not include erroneous status codes, `RejectedStatusCode` will be used in that case.
20    #[error("Network error: {analysis} ({error})", analysis=utils::reqwest::analyze_error_chain(.0), error=.0)]
21    NetworkRequest(#[source] reqwest::Error),
22    /// Cannot read the body of the received response
23    #[error("Error reading response body: {0}")]
24    ReadResponseBody(#[source] reqwest::Error),
25    /// The network client required for making requests cannot be created
26    #[error("Error creating request client: {0}")]
27    BuildRequestClient(#[source] reqwest::Error),
28
29    /// Network error while using GitHub API
30    #[error("Network error (GitHub client)")]
31    GithubRequest(#[from] Box<octocrab::Error>),
32
33    /// Error while executing a future on the Tokio runtime
34    #[error("Task failed to execute to completion")]
35    RuntimeJoin(#[from] JoinError),
36
37    /// Error while converting a file to an input
38    #[error("Cannot read input content from file `{1}`")]
39    ReadFileInput(#[source] std::io::Error, PathBuf),
40
41    /// Error while reading stdin as input
42    #[error("Cannot read input content from stdin")]
43    ReadStdinInput(#[from] std::io::Error),
44
45    /// Errors which can occur when attempting to interpret a sequence of u8 as a string
46    #[error("Attempted to interpret an invalid sequence of bytes as a string")]
47    Utf8(#[from] std::str::Utf8Error),
48
49    /// The GitHub client required for making requests cannot be created
50    #[error("Error creating GitHub client")]
51    BuildGithubClient(#[source] Box<octocrab::Error>),
52
53    /// Invalid GitHub URL
54    #[error("GitHub URL is invalid: {0}")]
55    InvalidGithubUrl(String),
56
57    /// The input is empty and not accepted as a valid URL
58    #[error("URL cannot be empty")]
59    EmptyUrl,
60
61    /// The given string can not be parsed into a valid URL, e-mail address, or file path
62    #[error("Cannot parse string `{1}` as website url: {0}")]
63    ParseUrl(#[source] url::ParseError, String),
64
65    /// The given URI cannot be converted to a file path
66    #[error("Cannot find file")]
67    InvalidFilePath(Uri),
68
69    /// The given URI's fragment could not be found within the page content
70    #[error("Cannot find fragment")]
71    InvalidFragment(Uri),
72
73    /// Cannot resolve local directory link using the configured index files
74    #[error("Cannot find index file within directory")]
75    InvalidIndexFile(Vec<String>),
76
77    /// The given path cannot be converted to a URI
78    #[error("Invalid path to URL conversion: {0}")]
79    InvalidUrlFromPath(PathBuf),
80
81    /// The given mail address is unreachable
82    #[error("Unreachable mail address: {0}: {1}")]
83    UnreachableEmailAddress(Uri, String),
84
85    /// The given header could not be parsed.
86    /// A possible error when converting a `HeaderValue` from a string or byte
87    /// slice.
88    #[error("Header could not be parsed.")]
89    InvalidHeader(#[from] http::header::InvalidHeaderValue),
90
91    /// The given string can not be parsed into a valid base URL or base directory
92    #[error("Error with base dir `{0}` : {1}")]
93    InvalidBase(String, String),
94
95    /// Cannot join the given text with the base URL
96    #[error("Cannot join '{0}' with the base URL")]
97    InvalidBaseJoin(String),
98
99    /// Cannot convert the given path to a URI
100    #[error("Cannot convert path '{0}' to a URI")]
101    InvalidPathToUri(String),
102
103    /// Invalid root directory given
104    #[error("Invalid root directory '{0}': {1}")]
105    InvalidRootDir(PathBuf, #[source] std::io::Error),
106
107    /// The given URI type is not supported
108    #[error("Unsupported URI type: '{0}'")]
109    UnsupportedUriType(String),
110
111    /// The given input can not be parsed into a valid URI remapping
112    #[error("Error remapping URL: `{0}`")]
113    InvalidUrlRemap(String),
114
115    /// The given path does not resolve to a valid file
116    #[error("Invalid file path: {0}")]
117    InvalidFile(PathBuf),
118
119    /// Error while traversing an input directory
120    #[error("Cannot traverse input directory: {0}")]
121    DirTraversal(#[from] ignore::Error),
122
123    /// The given glob pattern is not valid
124    #[error("UNIX glob pattern is invalid")]
125    InvalidGlobPattern(#[from] glob::PatternError),
126
127    /// The GitHub API could not be called because of a missing GitHub token.
128    #[error(
129        "GitHub token not specified. To check GitHub links reliably, use `--github-token` flag / `GITHUB_TOKEN` env var."
130    )]
131    MissingGitHubToken,
132
133    /// Used an insecure URI where a secure variant was reachable
134    #[error("This URI is available in HTTPS protocol, but HTTP is provided. Use '{0}' instead")]
135    InsecureURL(Uri),
136
137    /// Error while sending/receiving messages from MPSC channel
138    #[error("Cannot send/receive message from channel")]
139    Channel(#[from] tokio::sync::mpsc::error::SendError<InputContent>),
140
141    /// An URL with an invalid host was found
142    #[error("URL is missing a host")]
143    InvalidUrlHost,
144
145    /// Cannot parse the given URI
146    #[error("The given URI is invalid: {0}")]
147    InvalidURI(Uri),
148
149    /// The given status code is invalid (not in the range 100-1000)
150    #[error("Invalid status code: {0}")]
151    InvalidStatusCode(u16),
152
153    /// The given status code was not accepted (this depends on the `accept` configuration)
154    #[error(r#"Rejected status code (this depends on your "accept" configuration)"#)]
155    RejectedStatusCode(StatusCode),
156
157    /// Regex error
158    #[error("Error when using regex engine: {0}")]
159    Regex(#[from] regex::Error),
160
161    /// Basic auth extractor error
162    #[error("Basic auth extractor error")]
163    BasicAuthExtractorError(#[from] BasicAuthExtractorError),
164
165    /// Cannot load cookies
166    #[error("Cannot load cookies")]
167    Cookies(String),
168
169    /// Status code selector parse error
170    #[error("Status code range error")]
171    StatusCodeSelectorError(#[from] StatusCodeSelectorError),
172
173    /// Preprocessor command error
174    #[error("Preprocessor command '{command}' failed: {reason}")]
175    PreprocessorError {
176        /// The command which did not execute successfully
177        command: String,
178        /// The reason the command failed
179        reason: String,
180    },
181}
182
183impl ErrorKind {
184    /// Return more details about the given [`ErrorKind`]
185    ///
186    /// Which additional information we can extract depends on the underlying
187    /// request type. The output is purely meant for humans (e.g. for status
188    /// messages) and future changes are expected.
189    #[must_use]
190    #[allow(clippy::too_many_lines)]
191    pub fn details(&self) -> Option<String> {
192        match self {
193            ErrorKind::NetworkRequest(e) => {
194                        // Get detailed, actionable error analysis
195                        Some(utils::reqwest::analyze_error_chain(e))
196                    }
197            ErrorKind::RejectedStatusCode(status) => Some(
198                        status
199                            .canonical_reason()
200                            .unwrap_or("Unknown status code")
201                            .to_string(),
202                    ),
203            ErrorKind::GithubRequest(e) => {
204                        if let octocrab::Error::GitHub { source, .. } = &**e {
205                            Some(source.message.clone())
206                        } else {
207                            // Fall back to generic error analysis
208                            Some(e.to_string())
209                        }
210                    }
211            ErrorKind::InvalidFilePath(_uri) => Some(
212                "File not found. Check if file exists and path is correct".to_string()
213            ),
214            ErrorKind::ReadFileInput(e, path) => match e.kind() {
215                        std::io::ErrorKind::NotFound => Some(
216                            "Check if file path is correct".to_string()
217                        ),
218                        std::io::ErrorKind::PermissionDenied => Some(format!(
219                            "Permission denied: '{}'. Check file permissions",
220                            path.display()
221                        )),
222                        std::io::ErrorKind::IsADirectory => Some(format!(
223                            "Path is a directory, not a file: '{}'. Check file path",
224                            path.display()
225                        )),
226                        _ => Some(format!("File read error for '{}': {}", path.display(), e)),
227                    },
228            ErrorKind::ReadStdinInput(e) => match e.kind() {
229                        std::io::ErrorKind::UnexpectedEof => {
230                            Some("Stdin input ended unexpectedly. Check input data".to_string())
231                        }
232                        std::io::ErrorKind::InvalidData => {
233                            Some("Invalid data from stdin. Check input format".to_string())
234                        }
235                        _ => Some(format!("Stdin read error: {e}")),
236                    },
237            ErrorKind::ParseUrl(_, url) => {
238                        Some(format!("Invalid URL format: '{url}'. Check URL syntax"))
239                    }
240            ErrorKind::EmptyUrl => {
241                        Some("Empty URL found. Check for missing links or malformed markdown".to_string())
242                    }
243            ErrorKind::InvalidFile(path) => Some(format!(
244                        "Invalid file path: '{}'. Check if file exists and is readable",
245                        path.display()
246                    )),
247            ErrorKind::ReadResponseBody(error) => Some(format!(
248                "Failed to read response body: {error}. Server may have sent invalid data",
249            )),
250            ErrorKind::BuildRequestClient(error) => Some(format!(
251                "Failed to create HTTP client: {error}. Check system configuration",
252            )),
253            ErrorKind::RuntimeJoin(join_error) => Some(format!(
254                "Task execution failed: {join_error}. Internal processing error"
255            )),
256            ErrorKind::Utf8(_utf8_error) => Some(
257                "Invalid UTF-8 sequence found. File contains non-UTF-8 characters".to_string()
258            ),
259            ErrorKind::BuildGithubClient(error) => Some(format!(
260                "Failed to create GitHub client: {error}. Check token and network connectivity",
261            )),
262            ErrorKind::InvalidGithubUrl(url) => Some(format!(
263                "Invalid GitHub URL format: '{url}'. Check URL syntax",
264            )),
265            ErrorKind::InvalidFragment(_uri) => Some(
266                "Fragment not found in document. Check if fragment exists or page structure".to_string()
267            ),
268            ErrorKind::InvalidUrlFromPath(path_buf) => Some(format!(
269                "Cannot convert path to URL: '{}'. Check path format",
270                path_buf.display()
271            )),
272            ErrorKind::UnreachableEmailAddress(uri, reason) => Some(format!(
273                "Email address unreachable: '{uri}'. {reason}",
274            )),
275            ErrorKind::InvalidHeader(invalid_header_value) => Some(format!(
276                "Invalid HTTP header: {invalid_header_value}. Check header format",
277            )),
278            ErrorKind::InvalidBase(base, reason) => Some(format!(
279                "Invalid base URL or directory: '{base}'. {reason}",
280            )),
281            ErrorKind::InvalidBaseJoin(_) => Some("Check relative path format".to_string()),
282            ErrorKind::InvalidPathToUri(path) => match path {
283                path if path.starts_with('/') =>
284                    "To resolve root-relative links in local files, provide a root dir",
285                _ => "Check path format",
286            }.to_string().into(),
287            ErrorKind::InvalidRootDir(_, _) => Some(
288                "Check the root dir exists and is accessible".to_string()
289            ),
290            ErrorKind::UnsupportedUriType(uri_type) => Some(format!(
291                "Unsupported URI type: '{uri_type}'. Only http, https, file, and mailto are supported",
292            )),
293            ErrorKind::InvalidUrlRemap(remap) => Some(format!(
294                "Invalid URL remapping: '{remap}'. Check remapping syntax",
295            )),
296            ErrorKind::DirTraversal(error) => Some(format!(
297                "Directory traversal failed: {error}. Check directory permissions",
298            )),
299            ErrorKind::InvalidGlobPattern(pattern_error) => Some(format!(
300                "Invalid glob pattern: {pattern_error}. Check pattern syntax",
301            )),
302            ErrorKind::MissingGitHubToken => Some(
303                "GitHub token required. Use --github-token flag or GITHUB_TOKEN environment variable".to_string()
304            ),
305            ErrorKind::InsecureURL(uri) => Some(format!(
306                "Insecure HTTP URL detected: use '{}' instead of HTTP",
307                uri.as_str().replace("http://", "https://")
308            )),
309            ErrorKind::Channel(_send_error) => Some(
310                "Internal communication error. Processing thread failed".to_string()
311            ),
312            ErrorKind::InvalidUrlHost => Some(
313                "URL missing hostname. Check URL format".to_string()
314            ),
315            ErrorKind::InvalidURI(uri) => Some(format!(
316                "Invalid URI format: '{uri}'. Check URI syntax",
317            )),
318            ErrorKind::InvalidStatusCode(code) => Some(format!(
319                "Invalid HTTP status code: {code}. Must be between 100-999",
320            )),
321            ErrorKind::Regex(error) => Some(format!(
322                "Regular expression error: {error}. Check regex syntax",
323            )),
324            ErrorKind::BasicAuthExtractorError(basic_auth_extractor_error) => Some(format!(
325                "Basic authentication error: {basic_auth_extractor_error}. Check credentials format",
326            )),
327            ErrorKind::Cookies(reason) => Some(format!(
328                "Cookie handling error: {reason}. Check cookie file format",
329            )),
330            ErrorKind::StatusCodeSelectorError(status_code_selector_error) => Some(format!(
331                "Status code selector error: {status_code_selector_error}. Check accept configuration",
332            )),
333            ErrorKind::InvalidIndexFile(index_files) => match &index_files[..] {
334                [] => "No directory links are allowed because index_files is defined and empty".to_string(),
335                [name] => format!("An index file ({name}) is required"),
336                [init @ .., tail] => format!("An index file ({}, or {}) is required", init.join(", "), tail),
337            }.into(),
338            ErrorKind::PreprocessorError{command, reason} => Some(format!("Command '{command}' failed {reason}. Check value of the preprocessor option"))
339        }
340    }
341
342    /// Return the underlying source of the given [`ErrorKind`]
343    /// if it is a `reqwest::Error`.
344    /// This is useful for extracting the status code of a failed request.
345    /// If the error is not a `reqwest::Error`, `None` is returned.
346    #[must_use]
347    #[allow(clippy::redundant_closure_for_method_calls)]
348    pub(crate) fn reqwest_error(&self) -> Option<&reqwest::Error> {
349        self.source()
350            .and_then(|e| e.downcast_ref::<reqwest::Error>())
351    }
352
353    /// Return the underlying source of the given [`ErrorKind`]
354    /// if it is a `octocrab::Error`.
355    /// This is useful for extracting the status code of a failed request.
356    /// If the error is not a `octocrab::Error`, `None` is returned.
357    #[must_use]
358    #[allow(clippy::redundant_closure_for_method_calls)]
359    pub(crate) fn github_error(&self) -> Option<&octocrab::Error> {
360        self.source()
361            .and_then(|e| e.downcast_ref::<octocrab::Error>())
362    }
363}
364
365#[allow(clippy::match_same_arms)]
366impl PartialEq for ErrorKind {
367    fn eq(&self, other: &Self) -> bool {
368        match (self, other) {
369            (Self::NetworkRequest(e1), Self::NetworkRequest(e2)) => {
370                e1.to_string() == e2.to_string()
371            }
372            (Self::ReadResponseBody(e1), Self::ReadResponseBody(e2)) => {
373                e1.to_string() == e2.to_string()
374            }
375            (Self::BuildRequestClient(e1), Self::BuildRequestClient(e2)) => {
376                e1.to_string() == e2.to_string()
377            }
378            (Self::RuntimeJoin(e1), Self::RuntimeJoin(e2)) => e1.to_string() == e2.to_string(),
379            (Self::ReadFileInput(e1, s1), Self::ReadFileInput(e2, s2)) => {
380                e1.kind() == e2.kind() && s1 == s2
381            }
382            (Self::ReadStdinInput(e1), Self::ReadStdinInput(e2)) => e1.kind() == e2.kind(),
383            (Self::GithubRequest(e1), Self::GithubRequest(e2)) => e1.to_string() == e2.to_string(),
384            (Self::InvalidGithubUrl(s1), Self::InvalidGithubUrl(s2)) => s1 == s2,
385            (Self::ParseUrl(s1, e1), Self::ParseUrl(s2, e2)) => s1 == s2 && e1 == e2,
386            (Self::UnreachableEmailAddress(u1, ..), Self::UnreachableEmailAddress(u2, ..)) => {
387                u1 == u2
388            }
389            (Self::InsecureURL(u1), Self::InsecureURL(u2)) => u1 == u2,
390            (Self::InvalidGlobPattern(e1), Self::InvalidGlobPattern(e2)) => {
391                e1.msg == e2.msg && e1.pos == e2.pos
392            }
393            (Self::InvalidHeader(_), Self::InvalidHeader(_))
394            | (Self::MissingGitHubToken, Self::MissingGitHubToken) => true,
395            (Self::InvalidStatusCode(c1), Self::InvalidStatusCode(c2)) => c1 == c2,
396            (Self::InvalidUrlHost, Self::InvalidUrlHost) => true,
397            (Self::InvalidURI(u1), Self::InvalidURI(u2)) => u1 == u2,
398            (Self::Regex(e1), Self::Regex(e2)) => e1.to_string() == e2.to_string(),
399            (Self::DirTraversal(e1), Self::DirTraversal(e2)) => e1.to_string() == e2.to_string(),
400            (Self::Channel(_), Self::Channel(_)) => true,
401            (Self::BasicAuthExtractorError(e1), Self::BasicAuthExtractorError(e2)) => {
402                e1.to_string() == e2.to_string()
403            }
404            (Self::Cookies(e1), Self::Cookies(e2)) => e1 == e2,
405            (Self::InvalidFile(p1), Self::InvalidFile(p2)) => p1 == p2,
406            (Self::InvalidFilePath(u1), Self::InvalidFilePath(u2)) => u1 == u2,
407            (Self::InvalidFragment(u1), Self::InvalidFragment(u2)) => u1 == u2,
408            (Self::InvalidIndexFile(p1), Self::InvalidIndexFile(p2)) => p1 == p2,
409            (Self::InvalidUrlFromPath(p1), Self::InvalidUrlFromPath(p2)) => p1 == p2,
410            (Self::InvalidBase(b1, e1), Self::InvalidBase(b2, e2)) => b1 == b2 && e1 == e2,
411            (Self::InvalidUrlRemap(r1), Self::InvalidUrlRemap(r2)) => r1 == r2,
412            (Self::EmptyUrl, Self::EmptyUrl) => true,
413            (Self::RejectedStatusCode(c1), Self::RejectedStatusCode(c2)) => c1 == c2,
414
415            _ => false,
416        }
417    }
418}
419
420impl Eq for ErrorKind {}
421
422#[allow(clippy::match_same_arms)]
423impl Hash for ErrorKind {
424    fn hash<H>(&self, state: &mut H)
425    where
426        H: std::hash::Hasher,
427    {
428        match self {
429            Self::RuntimeJoin(e) => e.to_string().hash(state),
430            Self::ReadFileInput(e, s) => (e.kind(), s).hash(state),
431            Self::ReadStdinInput(e) => e.kind().hash(state),
432            Self::NetworkRequest(e) => e.to_string().hash(state),
433            Self::ReadResponseBody(e) => e.to_string().hash(state),
434            Self::BuildRequestClient(e) => e.to_string().hash(state),
435            Self::BuildGithubClient(e) => e.to_string().hash(state),
436            Self::GithubRequest(e) => e.to_string().hash(state),
437            Self::InvalidGithubUrl(s) => s.hash(state),
438            Self::DirTraversal(e) => e.to_string().hash(state),
439            Self::InvalidFile(e) => e.to_string_lossy().hash(state),
440            Self::EmptyUrl => "Empty URL".hash(state),
441            Self::ParseUrl(e, s) => (e.to_string(), s).hash(state),
442            Self::InvalidURI(u) => u.hash(state),
443            Self::InvalidUrlFromPath(p) => p.hash(state),
444            Self::Utf8(e) => e.to_string().hash(state),
445            Self::InvalidFilePath(u) => u.hash(state),
446            Self::InvalidFragment(u) => u.hash(state),
447            Self::InvalidIndexFile(p) => p.hash(state),
448            Self::UnreachableEmailAddress(u, ..) => u.hash(state),
449            Self::InsecureURL(u, ..) => u.hash(state),
450            Self::InvalidBase(base, e) => (base, e).hash(state),
451            Self::InvalidBaseJoin(s) => s.hash(state),
452            Self::InvalidPathToUri(s) => s.hash(state),
453            Self::InvalidRootDir(s, _) => s.hash(state),
454            Self::UnsupportedUriType(s) => s.hash(state),
455            Self::InvalidUrlRemap(remap) => (remap).hash(state),
456            Self::InvalidHeader(e) => e.to_string().hash(state),
457            Self::InvalidGlobPattern(e) => e.to_string().hash(state),
458            Self::InvalidStatusCode(c) => c.hash(state),
459            Self::RejectedStatusCode(c) => c.hash(state),
460            Self::Channel(e) => e.to_string().hash(state),
461            Self::MissingGitHubToken | Self::InvalidUrlHost => {
462                std::mem::discriminant(self).hash(state);
463            }
464            Self::Regex(e) => e.to_string().hash(state),
465            Self::BasicAuthExtractorError(e) => e.to_string().hash(state),
466            Self::Cookies(e) => e.hash(state),
467            Self::StatusCodeSelectorError(e) => e.to_string().hash(state),
468            Self::PreprocessorError { command, reason } => (command, reason).hash(state),
469        }
470    }
471}
472
473impl Serialize for ErrorKind {
474    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
475    where
476        S: Serializer,
477    {
478        serializer.collect_str(self)
479    }
480}
481
482impl From<Infallible> for ErrorKind {
483    fn from(_: Infallible) -> Self {
484        // tautological
485        unreachable!()
486    }
487}