aboutsummaryrefslogtreecommitdiffstats
path: root/default-plugins/sequence/src/path_formatting.rs
blob: 01bf50e69cd6ef41c24fd93fa1b0d4a84590137d (plain) (blame)
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use std::path::PathBuf;

/// Expand a path string to an absolute PathBuf
/// Handles ~, ./, .., relative and absolute paths
pub fn expand_path(path_str: &str, current_cwd: Option<&PathBuf>) -> Option<PathBuf> {
    let expanded = if path_str.starts_with("~/") || path_str == "~" {
        let home_dir = std::env::var("HOME").ok()?;
        if path_str == "~" {
            PathBuf::from(home_dir)
        } else {
            PathBuf::from(home_dir).join(&path_str[2..])
        }
    } else if path_str.starts_with('/') {
        PathBuf::from(path_str)
    } else {
        let base = current_cwd?;
        base.join(path_str)
    };

    let mut normalized = PathBuf::new();
    for component in expanded.components() {
        match component {
            std::path::Component::ParentDir => {
                normalized.pop();
            },
            std::path::Component::CurDir => {},
            _ => {
                normalized.push(component);
            },
        }
    }

    Some(normalized)
}

/// Format a path for display in the prompt
/// Example: /home/user/some/long/path -> ~/s/l/path
pub fn format_cwd(cwd: &PathBuf) -> String {
    let path_str = cwd.to_string_lossy().to_string();

    let home_dir = std::env::var("HOME").unwrap_or_default();
    let path_str = if !home_dir.is_empty() && path_str.starts_with(&home_dir) {
        path_str.replacen(&home_dir, "~", 1)
    } else {
        path_str
    };

    let parts: Vec<&str> = path_str.split('/').collect();

    if parts.len() <= 1 {
        return path_str;
    }

    let mut formatted_parts = Vec::new();
    for (i, part) in parts.iter().enumerate() {
        if i == parts.len() - 1 {
            formatted_parts.push(part.to_string());
        } else if part.is_empty() {
            formatted_parts.push(String::new());
        } else {
            formatted_parts.push(part.chars().next().unwrap_or_default().to_string());
        }
    }

    formatted_parts.join("/")
}

/// Alias for expand_path for backwards compatibility
pub fn resolve_path(current_cwd: Option<&PathBuf>, path_str: &str) -> Option<PathBuf> {
    expand_path(path_str, current_cwd)
}