supa_mdx_lint/utils/
path.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
use std::{
    ops::Deref,
    path::{Component, Path, PathBuf},
};

pub(crate) struct IsGlob(pub bool);

impl Deref for IsGlob {
    type Target = bool;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

fn normalize_glob_path(path: &Path) -> PathBuf {
    let components = path.components();
    let mut result = PathBuf::new();

    for component in components {
        match component {
            Component::ParentDir => {
                result.pop();
            }
            Component::CurDir => {}
            _ => {
                result.push(component);
            }
        }
    }

    result
}

/// Normalize a path for pattern comparison by canonicalizing it, and replacing
/// Windows-specific features:
/// - Replace ackslashes with slashes
/// - Remove extended-length prefix
pub(crate) fn normalize_path(path: &Path, is_glob: IsGlob) -> String {
    let path = if *is_glob {
        normalize_glob_path(path)
    } else {
        path.canonicalize().unwrap_or(path.into())
    };
    let mut path_str = path.to_string_lossy().replace("\\", "/");
    if path_str.starts_with("//?/") {
        path_str = path_str[4..].to_string();
    }
    path_str
}