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