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#[derive(Error, Debug)]
16#[non_exhaustive]
17pub enum ErrorKind {
18 #[error("Network error: {analysis} ({error})", analysis=utils::reqwest::analyze_error_chain(.0), error=.0)]
21 NetworkRequest(#[source] reqwest::Error),
22 #[error("Error reading response body: {0}")]
24 ReadResponseBody(#[source] reqwest::Error),
25 #[error("Error creating request client: {0}")]
27 BuildRequestClient(#[source] reqwest::Error),
28
29 #[error("Network error (GitHub client)")]
31 GithubRequest(#[from] Box<octocrab::Error>),
32
33 #[error("Task failed to execute to completion")]
35 RuntimeJoin(#[from] JoinError),
36
37 #[error("Cannot read input content from file `{1}`")]
39 ReadFileInput(#[source] std::io::Error, PathBuf),
40
41 #[error("Cannot read input content from stdin")]
43 ReadStdinInput(#[from] std::io::Error),
44
45 #[error("Attempted to interpret an invalid sequence of bytes as a string")]
47 Utf8(#[from] std::str::Utf8Error),
48
49 #[error("Error creating GitHub client")]
51 BuildGithubClient(#[source] Box<octocrab::Error>),
52
53 #[error("GitHub URL is invalid: {0}")]
55 InvalidGithubUrl(String),
56
57 #[error("URL cannot be empty")]
59 EmptyUrl,
60
61 #[error("Cannot parse '{1}' into a URL: {0}")]
63 ParseUrl(#[source] url::ParseError, String),
64
65 #[error("Cannot resolve root-relative link '{0}'")]
67 RootRelativeLinkWithoutRoot(String),
68
69 #[error("Cannot find file")]
71 InvalidFilePath(Uri),
72
73 #[error("Cannot find fragment")]
75 InvalidFragment(Uri),
76
77 #[error("Cannot find index file within directory")]
79 InvalidIndexFile(Vec<String>),
80
81 #[error("Invalid path to URL conversion: {0}")]
83 InvalidUrlFromPath(PathBuf),
84
85 #[error("Unreachable mail address: {0}: {1}")]
87 UnreachableEmailAddress(Uri, String),
88
89 #[error("Header could not be parsed.")]
93 InvalidHeader(#[from] http::header::InvalidHeaderValue),
94
95 #[error("Error with base dir '{0}': {1}")]
97 InvalidBase(String, String),
98
99 #[error("Invalid root directory '{0}': {1}")]
101 InvalidRootDir(PathBuf, #[source] std::io::Error),
102
103 #[error("Unsupported URI type: '{0}'")]
105 UnsupportedUriType(String),
106
107 #[error("Error remapping URL: `{0}`")]
109 InvalidUrlRemap(String),
110
111 #[error("Invalid file path: {0}")]
113 InvalidFile(PathBuf),
114
115 #[error("Cannot traverse input directory: {0}")]
117 DirTraversal(#[from] ignore::Error),
118
119 #[error("UNIX glob pattern is invalid")]
121 InvalidGlobPattern(#[from] glob::PatternError),
122
123 #[error(
125 "GitHub token not specified. To check GitHub links reliably, use `--github-token` flag / `GITHUB_TOKEN` env var."
126 )]
127 MissingGitHubToken,
128
129 #[error("This URI is available in HTTPS protocol, but HTTP is provided. Use '{0}' instead")]
131 InsecureURL(Uri),
132
133 #[error("Cannot send/receive message from channel")]
135 Channel(#[from] tokio::sync::mpsc::error::SendError<InputContent>),
136
137 #[error("URL is missing a host")]
139 InvalidUrlHost,
140
141 #[error("The given URI is invalid: {0}")]
143 InvalidURI(Uri),
144
145 #[error("Invalid status code: {0}")]
147 InvalidStatusCode(u16),
148
149 #[error(r#"Rejected status code (this depends on your "accept" configuration)"#)]
151 RejectedStatusCode(StatusCode),
152
153 #[error("Error when using regex engine: {0}")]
155 Regex(#[from] regex::Error),
156
157 #[error("Basic auth extractor error")]
159 BasicAuthExtractorError(#[from] BasicAuthExtractorError),
160
161 #[error("Cannot load cookies")]
163 Cookies(String),
164
165 #[error("Status code range error")]
167 StatusCodeSelectorError(#[from] StatusCodeSelectorError),
168
169 #[error("Preprocessor command '{command}' failed: {reason}")]
171 PreprocessorError {
172 command: String,
174 reason: String,
176 },
177
178 #[error("Wikilink {0} not found at {1}")]
180 WikilinkNotFound(Uri, PathBuf),
181
182 #[error("Failed to initialize wikilink checker: {0}")]
184 WikilinkInvalidBase(String),
185}
186
187impl ErrorKind {
188 #[must_use]
194 #[allow(clippy::too_many_lines)]
195 pub fn details(&self) -> Option<String> {
196 match self {
197 ErrorKind::NetworkRequest(e) => {
198 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 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 #[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 #[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 unreachable!()
508 }
509}