liquid_cache_common/
utils.rs

1use url::Url;
2
3/// Sanitize an object store URL for use as a directory name.
4pub fn sanitize_object_store_url_for_dirname(url: &Url) -> String {
5    let mut parts = vec![url.scheme()];
6
7    if let Some(host) = url.host_str() {
8        parts.push(host);
9    }
10
11    let dirname = parts.join("_");
12
13    dirname.replace(['/', ':', '?', '&', '=', '\\'], "_")
14}
15
16/// Sanitize a path for use as a directory name.
17pub fn sanitize_path_for_dirname(path: &str) -> String {
18    path.replace(['/', ':', '?', '&', '=', '\\'], "_")
19}
20
21#[cfg(test)]
22mod tests {
23    use super::*;
24    use std::fs;
25    use tempfile::TempDir;
26    use url::Url;
27
28    #[test]
29    fn test_can_create_directories_with_sanitized_names() {
30        // Create a temporary directory for testing
31        let temp_dir = TempDir::new().expect("Failed to create temp directory");
32
33        // Array of problematic URLs to test
34        let test_urls = [
35            "http://example.com/path/to/resource",
36            "https://example.com?param1=value1&param2=value2",
37            "s3://bucket-name/object/key",
38            "https://user:password@example.com:8080/path?query=value#fragment",
39            "file:///C:/Windows/System32/",
40            "https://example.com/path/with/special?chars=%20%26%3F",
41            "http://192.168.1.1:8080/admin?debug=true",
42            "ftp://files.example.com/pub/file.txt",
43            // Unicode characters in URL
44            "https://例子.测试",
45            // Very long URL
46            &format!("https://example.com/{}", "a".repeat(200)),
47        ];
48
49        // Test each URL
50        for url_str in test_urls {
51            let url = Url::parse(url_str).expect("Failed to parse URL");
52            let dirname = sanitize_object_store_url_for_dirname(&url);
53
54            // Create a directory using the sanitized name
55            let dir_path = temp_dir.path().join(dirname);
56            fs::create_dir(&dir_path).expect("Failed to create directory");
57
58            // Verify the directory exists
59            assert!(dir_path.exists());
60            assert!(dir_path.is_dir());
61
62            // Clean up
63            fs::remove_dir(&dir_path).expect("Failed to remove test directory");
64        }
65    }
66}