Skip to main content

elemental_shared/
scope.rs

1use anyhow::{Context, Result};
2use dirs::{config_dir, config_local_dir, document_dir, home_dir};
3use std::path::PathBuf;
4use tokio::fs::create_dir_all;
5
6const PRESERVED_DIR: &str = ".elemental";
7
8#[derive(Debug, Clone)]
9pub enum Scope {
10    Document,
11    Home,
12    Config,
13    ConfigLocal,
14    Dot,
15    Custom(PathBuf),
16}
17
18impl Scope {
19    pub fn path(&self) -> Option<PathBuf> {
20        match self {
21            Scope::Document => document_dir(),
22            Scope::Home => home_dir(),
23            Scope::Config => config_dir(),
24            Scope::ConfigLocal => config_local_dir(),
25            Scope::Dot => Some(PathBuf::from(".")),
26            // May need more pathbuf here
27            Scope::Custom(p) => Some(p.clone()),
28        }
29    }
30
31    pub fn get_full_path_blocking(&self, id: &str, suffix: Option<String>) -> Result<PathBuf> {
32        let mut path = self.path().context("There is no valid base path")?;
33        path.push(PRESERVED_DIR);
34        if !path.exists() {
35            std::fs::create_dir_all(&path)?;
36        }
37
38        path.push(id);
39        if let Some(suf) = suffix {
40            path.set_extension(suf);
41        }
42
43        Ok(path)
44    }
45
46    pub async fn get_full_path(&self, id: &str, suffix: Option<String>) -> Result<PathBuf> {
47        let path = self.get_full_path_blocking(id, suffix)?;
48        if let Some(parent) = path.parent()
49            && !parent.exists()
50        {
51            create_dir_all(parent).await?;
52        }
53
54        Ok(path)
55    }
56}