aboutsummaryrefslogtreecommitdiff
path: root/core/src/util/path.rs
blob: 2cd900a3a6db5be5d285d984223ae9f317f3177c (plain)
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
use std::path::PathBuf;

use crate::{error::Error, Result};

/// Returns the user's home directory as a `PathBuf`.
#[allow(dead_code)]
pub fn home_dir() -> Result<PathBuf> {
    dirs::home_dir().ok_or(Error::PathNotFound("Home dir not found"))
}

/// Expands a tilde (~) in a path and returns the expanded `PathBuf`.
#[allow(dead_code)]
pub fn tilde_expand(path: &str) -> Result<PathBuf> {
    match path {
        "~" => home_dir(),
        p if p.starts_with("~/") => Ok(home_dir()?.join(&path[2..])),
        _ => Ok(PathBuf::from(path)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_tilde_expand() {
        let path = "~/src";
        let expanded_path = dirs::home_dir().unwrap().join("src");
        assert_eq!(tilde_expand(path).unwrap(), expanded_path);

        let path = "~";
        let expanded_path = dirs::home_dir().unwrap();
        assert_eq!(tilde_expand(path).unwrap(), expanded_path);

        let path = "";
        let expanded_path = PathBuf::from("");
        assert_eq!(tilde_expand(path).unwrap(), expanded_path);
    }
}