karyon_core/util/
path.rs

1use std::path::PathBuf;
2
3use crate::{error::Error, Result};
4
5/// Returns the user's home directory as a `PathBuf`.
6#[allow(dead_code)]
7pub fn home_dir() -> Result<PathBuf> {
8    dirs::home_dir().ok_or(Error::PathNotFound("Home dir not found".to_string()))
9}
10
11/// Expands a tilde (~) in a path and returns the expanded `PathBuf`.
12#[allow(dead_code)]
13pub fn tilde_expand(path: &str) -> Result<PathBuf> {
14    match path {
15        "~" => home_dir(),
16        p if p.starts_with("~/") => Ok(home_dir()?.join(&path[2..])),
17        _ => Ok(PathBuf::from(path)),
18    }
19}
20
21#[cfg(test)]
22mod tests {
23    use super::*;
24
25    #[test]
26    fn test_tilde_expand() {
27        let path = "~/src";
28        let expanded_path = dirs::home_dir().unwrap().join("src");
29        assert_eq!(tilde_expand(path).unwrap(), expanded_path);
30
31        let path = "~";
32        let expanded_path = dirs::home_dir().unwrap();
33        assert_eq!(tilde_expand(path).unwrap(), expanded_path);
34
35        let path = "";
36        let expanded_path = PathBuf::from("");
37        assert_eq!(tilde_expand(path).unwrap(), expanded_path);
38    }
39}