evobench_tools/utillib/
path_resolve_home.rs

1use std::path::{Path, PathBuf};
2
3use anyhow::{Result, anyhow};
4
5use super::home::home_dir;
6
7/// Change paths starting with `~/` to replace the `~` with the user's
8/// home directory. Careful: if path is not representable as unicode
9/// string, no expansion is attempted!
10pub fn path_resolve_home(path: &Path) -> Result<PathBuf> {
11    if let Some(path_str) = path.to_str() {
12        if path_str.starts_with("~") {
13            let home = home_dir()?;
14            if path_str == "~" {
15                return Ok(home.to_owned());
16            }
17            if path_str.starts_with("~/") {
18                let home_str = home.to_str().ok_or_else(|| {
19                    anyhow!("home dir {home:?} can't be represented as unicode string")
20                })?;
21                return Ok(format!("{home_str}/{}", &path_str[2..]).into());
22            }
23        }
24    }
25    Ok(path.to_owned())
26}