Skip to main content

project_map_cli_rust/core/
utils.rs

1use std::path::Path;
2
3pub fn path_to_fqn(root: &Path, path: &Path) -> String {
4    let rel = path.strip_prefix(root).unwrap_or(path);
5    let mut parts = Vec::new();
6    
7    for component in rel.components() {
8        let part = component.as_os_str().to_string_lossy();
9        if part == "__init__.py" || part == "mod.rs" || part == "lib.rs" || part == "index.ts" || part == "index.tsx" {
10            continue;
11        }
12        let clean_part = part.trim_end_matches(".py")
13            .trim_end_matches(".rs")
14            .trim_end_matches(".tsx")
15            .trim_end_matches(".ts")
16            .trim_end_matches(".kt")
17            .trim_end_matches(".sql")
18            .trim_end_matches(".vue");
19            
20        if !clean_part.is_empty() {
21            parts.push(clean_part.to_string());
22        }
23    }
24    
25    parts.join(".")
26}
27
28pub fn resolve_import_path(current_file: &str, import_specifier: &str) -> String {
29    if !import_specifier.starts_with('.') {
30        return import_specifier.to_string();
31    }
32
33    let current_path = Path::new(current_file);
34    let current_dir = current_path.parent().unwrap_or_else(|| Path::new(""));
35    let mut resolved = current_dir.to_path_buf();
36    
37    for part in import_specifier.split('/') {
38        if part == "." {
39            continue;
40        } else if part == ".." {
41            resolved.pop();
42        } else {
43            resolved.push(part);
44        }
45    }
46
47    resolved.to_string_lossy().to_string()
48}
49
50#[cfg(test)]
51mod tests {
52    use super::*;
53
54    #[test]
55    fn test_path_to_fqn() {
56        let root = Path::new("/project");
57        let path = Path::new("/project/src/core/utils.py");
58        assert_eq!(path_to_fqn(root, path), "src.core.utils");
59        
60        let path2 = Path::new("/project/src/main.rs");
61        assert_eq!(path_to_fqn(root, path2), "src.main");
62
63        let path3 = Path::new("/project/src/core/__init__.py");
64        assert_eq!(path_to_fqn(root, path3), "src.core");
65
66        let path4 = Path::new("/project/tests/integration/test_main.py");
67        assert_eq!(path_to_fqn(root, path4), "tests.integration.test_main");
68
69        let path5 = Path::new("/project/src/components/Button.tsx");
70        assert_eq!(path_to_fqn(root, path5), "src.components.Button");
71
72        let path6 = Path::new("/project/src/components/index.ts");
73        assert_eq!(path_to_fqn(root, path6), "src.components");
74    }
75
76    #[test]
77    fn test_resolve_import_path() {
78        assert_eq!(resolve_import_path("src/main.ts", "./utils"), "src/utils");
79        assert_eq!(resolve_import_path("src/core/parser.ts", "../utils"), "src/utils");
80        assert_eq!(resolve_import_path("src/index.ts", "lodash"), "lodash");
81    }
82}