read_url/context/
overrides.rs

1use super::{super::errors::*, context::*};
2
3use std::{collections::*, sync::*};
4
5/// Global URL overrides.
6pub static GLOBAL_URL_OVERRIDES: LazyLock<Mutex<HashMap<String, String>>> = LazyLock::new(|| HashMap::default().into());
7
8impl UrlContext {
9    /// Override a URL.
10    pub fn override_url(self: &UrlContextRef, from_url: String, to_url: String) -> Result<Option<String>, UrlError> {
11        let mut url_overrides = self.url_overrides.lock()?;
12        Ok(url_overrides.insert(from_url, to_url))
13    }
14
15    /// Remove a URL override.
16    pub fn remove_url_override(self: &UrlContextRef, from_url: &String) -> Result<Option<String>, UrlError> {
17        let mut url_overrides = self.url_overrides.lock()?;
18        Ok(url_overrides.remove(from_url))
19    }
20
21    /// Override a global URL.
22    pub fn override_global_url(from_url: String, to_url: String) -> Result<Option<String>, UrlError> {
23        let mut url_overrides = GLOBAL_URL_OVERRIDES.lock()?;
24        Ok(url_overrides.insert(from_url, to_url))
25    }
26
27    /// Remove a global URL override.
28    pub fn remove_global_url_override(from_url: &String) -> Result<Option<String>, UrlError> {
29        let mut url_overrides = GLOBAL_URL_OVERRIDES.lock()?;
30        Ok(url_overrides.remove(from_url))
31    }
32
33    /// Get a URL override.
34    ///
35    /// Tries the context's overrides first, the global overrides next.
36    pub fn get_url_override(self: &UrlContextRef, from_url: &String) -> Result<Option<String>, UrlError> {
37        // Try context overrides first
38        let url_overrides = self.url_overrides.lock()?;
39        if let Some(to_url) = url_overrides.get(from_url) {
40            return Ok(Some(to_url.clone()));
41        }
42
43        // Then the global overrides
44        let url_overrides = GLOBAL_URL_OVERRIDES.lock()?;
45        Ok(url_overrides.get(from_url).cloned())
46    }
47
48    /// Get a URL's override or itself.
49    ///
50    /// Tries the context's overrides first, the global overrides next.
51    pub fn get_url_or_override(self: &UrlContextRef, from_url: String) -> Result<String, UrlError> {
52        Ok(self.get_url_override(&from_url)?.clone().unwrap_or(from_url))
53    }
54}