Skip to main content

pixie_pi/tools/
util.rs

1//! Shared tool helpers: path resolution and display.
2
3use std::path::{Path, PathBuf};
4
5/// Expand a leading `~` to the user's home directory.
6pub fn expand_tilde(path: &str) -> PathBuf {
7    if let Some(rest) = path.strip_prefix("~/") {
8        if let Some(home) = dirs::home_dir() {
9            return home.join(rest);
10        }
11    } else if path == "~" {
12        if let Some(home) = dirs::home_dir() {
13            return home;
14        }
15    }
16    PathBuf::from(path)
17}
18
19/// Resolve a tool-provided path against the working directory. Absolute paths
20/// (and `~`-expanded paths) are used as-is; relative paths are joined to `cwd`.
21pub fn resolve_to_cwd(path: &str, cwd: &Path) -> PathBuf {
22    let expanded = expand_tilde(path);
23    if expanded.is_absolute() {
24        expanded
25    } else {
26        cwd.join(expanded)
27    }
28}
29
30/// Alias mirroring pi's `resolveReadPath` (same semantics as `resolveToCwd`).
31pub fn resolve_read_path(path: &str, cwd: &Path) -> PathBuf {
32    resolve_to_cwd(path, cwd)
33}
34
35/// Render a path compactly: relative to `cwd` when inside it, otherwise `~`-
36/// abbreviated when inside the home dir.
37pub fn shorten_path(path: &Path, cwd: &Path) -> String {
38    if let Ok(rel) = path.strip_prefix(cwd) {
39        let s = rel.to_string_lossy().to_string();
40        return if s.is_empty() { ".".to_string() } else { s };
41    }
42    if let Some(home) = dirs::home_dir() {
43        if let Ok(rel) = path.strip_prefix(&home) {
44            return format!("~/{}", rel.to_string_lossy());
45        }
46    }
47    path.to_string_lossy().to_string()
48}
49
50/// Stringify a path for display given the raw (possibly relative) input.
51pub fn display_path(raw: &str, cwd: &Path) -> String {
52    shorten_path(&resolve_to_cwd(raw, cwd), cwd)
53}