1use url::Url;
2
3pub fn strip_auth_from_url(url: &Url) -> (Url, Option<(String, String)>) {
5 let auth = if !url.username().is_empty() {
6 Some((
7 url.username().to_string(),
8 url.password().unwrap_or("").to_string(),
9 ))
10 } else {
11 None
12 };
13
14 let mut clean_url = url.clone();
15 if auth.is_some() {
16 clean_url.set_username("").ok();
17 clean_url.set_password(None).ok();
18 }
19
20 (clean_url, auth)
21}
22
23pub fn generate_filename_from_url(url: &Url, extension: &str) -> String {
25 let host = url.host_str().unwrap_or("unknown");
26 let path = url.path();
27
28 let path_part = path
30 .trim_start_matches('/')
31 .trim_end_matches('/')
32 .replace('/', "-");
33
34 let base = if path_part.is_empty() {
35 host.to_string()
36 } else {
37 format!("{}-{}", host, path_part)
38 };
39
40 let sanitized = base.replace(':', "-").replace(' ', "-").to_lowercase();
42
43 format!("{}.{}", sanitized, extension)
44}
45
46#[cfg(test)]
47mod tests {
48 use super::*;
49
50 #[test]
51 fn test_strip_auth_from_url() {
52 let url = Url::parse("https://user:pass@example.com/path").unwrap();
53 let (clean_url, auth) = strip_auth_from_url(&url);
54
55 assert_eq!(clean_url.as_str(), "https://example.com/path");
56 assert_eq!(auth, Some(("user".to_string(), "pass".to_string())));
57
58 let url = Url::parse("https://example.com/path").unwrap();
60 let (clean_url, auth) = strip_auth_from_url(&url);
61
62 assert_eq!(clean_url.as_str(), "https://example.com/path");
63 assert_eq!(auth, None);
64 }
65
66 #[test]
67 fn test_generate_filename_from_url() {
68 let url = Url::parse("https://example.com/ubuntu").unwrap();
69 assert_eq!(
70 generate_filename_from_url(&url, "sources"),
71 "example.com-ubuntu.sources"
72 );
73
74 let url = Url::parse("https://ppa.launchpad.net/user/repo/ubuntu").unwrap();
75 assert_eq!(
76 generate_filename_from_url(&url, "list"),
77 "ppa.launchpad.net-user-repo-ubuntu.list"
78 );
79 }
80}