1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use crate::{Config, HashedRegex};
use codespan::Files;
use http::header::{HeaderMap, HeaderName, HeaderValue};
use linkcheck::{
    validation::{Cache, Options},
    Link,
};
use reqwest::{Client, Url};
use std::{
    path::Path,
    sync::{Mutex, MutexGuard},
};

/// The [`linkcheck::validation::Context`].
#[derive(Debug)]
pub struct Context<'a> {
    pub(crate) cfg: &'a Config,
    pub(crate) src_dir: &'a Path,
    pub(crate) cache: Mutex<Cache>,
    pub(crate) files: &'a Files<String>,
    pub(crate) client: Client,
    pub(crate) filesystem_options: Options,
    pub(crate) interpolated_headers:
        Vec<(HashedRegex, Vec<(HeaderName, HeaderValue)>)>,
}

impl<'a> linkcheck::validation::Context for Context<'a> {
    fn client(&self) -> &Client { &self.client }

    fn filesystem_options(&self) -> &Options { &self.filesystem_options }

    fn cache(&self) -> Option<MutexGuard<Cache>> {
        Some(self.cache.lock().expect("Lock was poisoned"))
    }

    fn should_ignore(&self, link: &Link) -> bool {
        if !self.cfg.follow_web_links {
            if let Ok(_) = link.href.parse::<Url>() {
                return true;
            }
        }

        self.cfg
            .exclude
            .iter()
            .any(|re| re.find(&link.href).is_some())
    }

    fn url_specific_headers(&self, url: &Url) -> HeaderMap {
        let url = url.to_string();
        let mut headers = HeaderMap::new();

        for (pattern, matching_headers) in &self.interpolated_headers {
            if pattern.find(&url).is_some() {
                for (name, value) in matching_headers {
                    headers.insert(name.clone(), value.clone());
                }
            }
        }

        headers
    }
}