Skip to main content

elemental_shared/
scope.rs

1use crate::error::{Error, 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    /// Uses the supplied directory as the base for scoped files.
16    Directory(PathBuf),
17}
18
19impl Scope {
20    pub fn path(&self) -> Option<PathBuf> {
21        match self {
22            Scope::Document => document_dir(),
23            Scope::Home => home_dir(),
24            Scope::Config => config_dir(),
25            Scope::ConfigLocal => config_local_dir(),
26            Scope::Dot => Some(PathBuf::from(".")),
27            Scope::Directory(directory) => Some(directory.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().ok_or(Error::BasePathUnavailable)?;
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}