Skip to main content

cargo_plot/core/path_store/
context.rs

1use std::env;
2use std::fs;
3use std::path::Path;
4
5/// [POL]: Kontekst ścieżki roboczej - oblicza relacje między terminalem a celem skanowania.
6/// [ENG]: Working path context - calculates relations between terminal and scan target.
7#[derive(Debug)]
8pub struct PathContext {
9    pub base_absolute: String,
10    pub entry_absolute: String,
11    pub entry_relative: String,
12}
13
14impl PathContext {
15    pub fn resolve<P: AsRef<Path>>(entered_path: P) -> Result<Self, String> {
16        let path_ref = entered_path.as_ref();
17
18        // 1. BASE ABSOLUTE: Gdzie fizycznie odpalono program?
19        let cwd = env::current_dir().map_err(|e| format!("Błąd odczytu CWD: {}", e))?;
20        let base_abs = cwd
21            .to_string_lossy()
22            .trim_start_matches(r"\\?\")
23            .replace('\\', "/");
24
25        // 2. ENTRY ABSOLUTE: Pełna ścieżka do folderu, który skanujemy
26        let abs_path = fs::canonicalize(path_ref)
27            .map_err(|e| format!("Nie można ustalić ścieżki '{:?}': {}", path_ref, e))?;
28        let entry_abs = abs_path
29            .to_string_lossy()
30            .trim_start_matches(r"\\?\")
31            .replace('\\', "/");
32
33        // 3. ENTRY RELATIVE: Ścieżka od terminala do skanowanego folderu
34        let entry_rel = match abs_path.strip_prefix(&cwd) {
35            Ok(rel) => {
36                let rel_str = rel.to_string_lossy().replace('\\', "/");
37                if rel_str.is_empty() {
38                    "./".to_string() // Cel to ten sam folder co terminal
39                } else {
40                    format!("./{}/", rel_str)
41                }
42            }
43            Err(_) => {
44                // Jeśli cel jest na innym dysku (np. C:\ a terminal na D:\)
45                // lub całkiem poza strukturą CWD, relatywna nie istnieje.
46                // Wracamy wtedy do tego, co wpisał użytkownik, lub dajemy absolutną.
47                path_ref.to_string_lossy().replace('\\', "/")
48            }
49        };
50
51        Ok(Self {
52            base_absolute: base_abs,
53            entry_absolute: entry_abs,
54            entry_relative: entry_rel,
55        })
56    }
57}