Skip to main content

elemental_core/storage/
store.rs

1use std::path::{Path, PathBuf};
2
3use tokio::fs::create_dir_all;
4
5use crate::storage::{
6    error::{Error, Result},
7    layout::{Layout, Layoutable},
8};
9
10#[derive(Debug, Clone)]
11pub struct Storage<L: Layout, P = ()> {
12    pub path: PathBuf,
13    pub parent: P,
14    pub layout: L,
15}
16
17impl<L: Layout> Storage<L> {
18    pub fn new<P: AsRef<Path>>(path: P, layout: L) -> Self {
19        Self {
20            path: path.as_ref().to_path_buf(),
21            parent: (),
22            layout,
23        }
24    }
25}
26
27impl<L: Layout, P> Storage<L, P> {
28    pub fn with_parent(path: PathBuf, parent: P, layout: L) -> Self {
29        Self {
30            path,
31            parent,
32            layout,
33        }
34    }
35
36    pub fn name(&self) -> Option<String> {
37        self.path
38            .file_name()
39            .and_then(|n| n.to_str().map(|s| s.to_string()))
40    }
41
42    pub async fn ensure_root(&self) -> Result<()> {
43        create_dir_all(&self.path)
44            .await
45            .map_err(|source| Error::Io {
46                operation: "create storage directory",
47                path: self.path.clone(),
48                source,
49            })?;
50        Ok(())
51    }
52
53    pub fn scope<NL>(&self, relative: impl AsRef<Path>, layout: NL) -> Storage<NL, Self>
54    where
55        NL: Layout,
56        Self: Clone,
57    {
58        Storage::with_parent(self.path.join(relative), self.clone(), layout)
59    }
60}
61
62impl<L: Layout, P> Layoutable<L> for Storage<L, P> {
63    fn layout(&self) -> &L {
64        &self.layout
65    }
66
67    fn root_path(&self) -> &Path {
68        &self.path
69    }
70}