qlty_analysis/utils/
fs.rs

1use std::path::{Path, MAIN_SEPARATOR_STR};
2
3#[macro_export]
4/// Join a path together from a list of string-like arguments.
5///
6/// # Example
7///     let path = join_path_string!("a", "b", "c");
8///     assert_eq!(path, "a/b/c"); // on Unix systems
9macro_rules! join_path_string {
10    ($($x:expr),*) => {
11        {
12            let mut path = std::path::PathBuf::new();
13            $(
14                path.push($x);
15            )*
16            path.to_string_lossy().to_string().replace('\\', "/")
17        }
18    };
19}
20
21pub fn path_to_string<'path>(path: impl AsRef<Path>) -> String {
22    path.as_ref()
23        .to_string_lossy()
24        .to_string()
25        .replace('\\', "/")
26}
27
28pub fn path_to_native_string(path: impl AsRef<Path>) -> String {
29    path_to_string(path)
30        .replace('\\', MAIN_SEPARATOR_STR)
31        .replace('/', MAIN_SEPARATOR_STR)
32}
33
34mod test {
35    #[test]
36    fn test_join_path_string() {
37        let path = join_path_string!(
38            "a",
39            "b".to_string(),
40            std::path::PathBuf::from("c"),
41            std::path::Path::new("d")
42        );
43        assert_eq!(path, "a/b/c/d");
44    }
45
46    #[test]
47    fn test_path_to_string() {
48        let path = std::path::PathBuf::from("a\\b\\c");
49        assert_eq!(crate::utils::fs::path_to_string(path), "a/b/c");
50    }
51
52    #[test]
53    fn test_path_to_native_string() {
54        let path = join_path_string!("a", "b", "c");
55        assert_eq!(
56            crate::utils::fs::path_to_native_string(path),
57            format!(
58                "a{}b{}c",
59                std::path::MAIN_SEPARATOR,
60                std::path::MAIN_SEPARATOR
61            )
62        );
63
64        let path = "a/b/c";
65        assert_eq!(
66            crate::utils::fs::path_to_native_string(path),
67            format!(
68                "a{}b{}c",
69                std::path::MAIN_SEPARATOR,
70                std::path::MAIN_SEPARATOR
71            )
72        );
73    }
74}