libkelp/lib/fsutil/
paths.rs

1use anyhow::Context;
2use kelpdot_macros::red;
3use std::path::Path;
4/// Check if a env var is set or return default
5pub fn get_path_from_env<T: ToString>(var: &str, def: T) -> anyhow::Result<String> {
6    let mut base = std::env::var(var).unwrap_or_else(|_| def.to_string());
7    if !Path::new(&base).exists() {
8        base = def.to_string();
9    }
10    let full = std::fs::canonicalize(base)?;
11    Ok(full.to_str().unwrap().to_string())
12}
13#[cfg(test)]
14mod tests {
15    #[test]
16    fn get_path_fenv_test() {
17        use super::get_path_from_env;
18        println!("{}", std::env::current_dir().unwrap().to_str().unwrap().to_string());
19        assert_eq!(std::env::current_dir().unwrap().to_str().unwrap().to_string(), get_path_from_env("SOME_USELESS_VAR", ".").unwrap())
20    }
21}
22/// Gets the root of dotfiles using DOTFILES_ROOT path or .
23pub fn get_root() -> anyhow::Result<String> {
24    get_path_from_env("DOTFILES_ROOT", ".")
25}
26/// Gets the INSTALL ROOT
27pub fn get_ins_root() -> anyhow::Result<String> {
28    get_path_from_env("KELPDOT_INS_ROOT", "/")
29}
30/// Get name of directory to make
31pub fn get_to_make(path: String) -> anyhow::Result<String> {
32    let home = std::env::var("HOME").with_context(|| red!("Unable to get env var $HOME"))?;
33    // If file is located at /home
34    if Path::new(&format!("{}/{}", home, path)).exists() {
35        Ok(Path::new(&path)
36            .parent()
37            .unwrap()
38            .to_str()
39            .unwrap()
40            .to_owned())
41    } else {
42        Ok(Path::new(&path)
43            .parent()
44            .unwrap()
45            .strip_prefix("/")? // Remove / to get path like etc/config instead of /etc/config
46            .to_str()
47            .unwrap()
48            .to_owned())
49    }
50}