mdbook_linkcheck/
context.rs

1use crate::{Config, HashedRegex};
2use codespan::Files;
3use http::header::{HeaderMap, HeaderName, HeaderValue};
4use linkcheck::{
5    validation::{Cache, Options},
6    Link,
7};
8use reqwest::{Client, Url};
9use std::{
10    path::Path,
11    sync::{Mutex, MutexGuard},
12};
13
14/// The [`linkcheck::validation::Context`].
15#[derive(Debug)]
16pub struct Context<'a> {
17    pub(crate) cfg: &'a Config,
18    pub(crate) src_dir: &'a Path,
19    pub(crate) cache: Mutex<Cache>,
20    pub(crate) files: &'a Files<String>,
21    pub(crate) client: Client,
22    pub(crate) filesystem_options: Options,
23    pub(crate) interpolated_headers:
24        Vec<(HashedRegex, Vec<(HeaderName, HeaderValue)>)>,
25}
26
27impl<'a> linkcheck::validation::Context for Context<'a> {
28    fn client(&self) -> &Client { &self.client }
29
30    fn filesystem_options(&self) -> &Options { &self.filesystem_options }
31
32    fn cache(&self) -> Option<MutexGuard<Cache>> {
33        Some(self.cache.lock().expect("Lock was poisoned"))
34    }
35
36    fn should_ignore(&self, link: &Link) -> bool {
37        if !self.cfg.follow_web_links {
38            if let Ok(_) = link.href.parse::<Url>() {
39                return true;
40            }
41        }
42
43        self.cfg
44            .exclude
45            .iter()
46            .any(|re| re.find(&link.href).is_some())
47    }
48
49    fn url_specific_headers(&self, url: &Url) -> HeaderMap {
50        let url = url.to_string();
51        let mut headers = HeaderMap::new();
52
53        for (pattern, matching_headers) in &self.interpolated_headers {
54            if pattern.find(&url).is_some() {
55                for (name, value) in matching_headers {
56                    headers.insert(name.clone(), value.clone());
57                }
58            }
59        }
60
61        headers
62    }
63}