mdbook_linkcheck2/
context.rs

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