spin_common/
url.rs

1//! Operations on URLs
2
3use anyhow::{anyhow, Context};
4
5use std::path::PathBuf;
6
7/// Parse the path from a 'file:' URL
8pub fn parse_file_url(url: &str) -> anyhow::Result<PathBuf> {
9    url::Url::parse(url)
10        .with_context(|| format!("Invalid URL: {url:?}"))?
11        .to_file_path()
12        .map_err(|_| anyhow!("Invalid file URL path: {url:?}"))
13}
14
15/// Remove the credentials from a URL string
16pub fn remove_credentials(url: &str) -> anyhow::Result<String> {
17    let mut url = url::Url::parse(url).with_context(|| format!("Invalid URL: {url:?}"))?;
18    url.set_username("")
19        .map_err(|_| anyhow!("Could not remove username"))?;
20    url.set_password(None)
21        .map_err(|_| anyhow!("Could not remove password"))?;
22    Ok(url.to_string())
23}
24
25#[cfg(test)]
26mod test {
27    use super::*;
28
29    #[test]
30    fn remove_credentials_removes_credentials() {
31        assert_eq!(
32            "redis://example.com:4567",
33            remove_credentials("redis://example.com:4567").unwrap()
34        );
35        assert_eq!(
36            "redis://example.com:4567",
37            remove_credentials("redis://me:secret@example.com:4567").unwrap()
38        );
39        assert_eq!(
40            "http://example.com/users",
41            remove_credentials("http://me:secret@example.com/users").unwrap()
42        );
43    }
44}