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 fn display_name(&self) -> String {
43        self.name().unwrap_or_else(|| {
44            self.path
45                .file_name()
46                .map(|name| name.to_string_lossy().to_string())
47                .unwrap_or_else(|| self.path.display().to_string())
48        })
49    }
50
51    pub async fn ensure_root(&self) -> Result<()> {
52        create_dir_all(&self.path)
53            .await
54            .map_err(|source| Error::Io {
55                operation: "create storage directory",
56                path: self.path.clone(),
57                source,
58            })?;
59        Ok(())
60    }
61
62    pub fn scope<NL>(&self, relative: impl AsRef<Path>, layout: NL) -> Storage<NL, Self>
63    where
64        NL: Layout,
65        Self: Clone,
66    {
67        Storage::with_parent(self.path.join(relative), self.clone(), layout)
68    }
69}
70
71impl<L: Layout, PL: Layout, PP> Storage<L, Storage<PL, PP>> {
72    pub fn parent_root_path(&self) -> &Path {
73        &self.parent.path
74    }
75
76    pub fn get_parent_resource(&self, resource: PL::Resource) -> Option<PathBuf> {
77        self.parent.get_resource(resource)
78    }
79
80    pub fn try_get_parent_resource(&self, resource: PL::Resource) -> Result<PathBuf>
81    where
82        PL::Resource: std::fmt::Debug,
83    {
84        self.parent.try_get_resource(resource)
85    }
86}
87
88impl<L: Layout, P> Layoutable<L> for Storage<L, P> {
89    fn layout(&self) -> &L {
90        &self.layout
91    }
92
93    fn root_path(&self) -> &Path {
94        &self.path
95    }
96}