1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
use std::{ffi::OsString, path::PathBuf, string::FromUtf8Error, sync::Arc};
use derive_more::{Display, From};
use futures::{stream, FutureExt, StreamExt, TryStreamExt};
use thiserror::Error;
use tokio::fs::DirEntry;
use crate::{
address::{
primitive::Existence,
traits::{
AddressableList, AddressableRead, AddressableTree, AddressableWrite, BranchOrLeaf,
},
Address, Addressable, PathAddress, SubAddress,
},
store::{Store, StoreResult},
};
#[derive(Error, Display, Debug, From)]
pub enum FileStoreError {
SomeError(String),
StdIoError(std::io::Error),
FromUtf8Error(FromUtf8Error),
#[from(ignore)]
UnsupportedFeature(String),
}
#[derive(PartialEq, Eq, Debug, Clone, From)]
pub struct RelativePath(PathBuf);
#[derive(PartialEq, Eq, Debug, Clone, From, Display)]
pub struct FilePath(RelativePath);
impl std::fmt::Display for RelativePath {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0.display())
}
}
impl From<&str> for RelativePath {
fn from(value: &str) -> Self {
RelativePath(value.into())
}
}
impl From<String> for RelativePath {
fn from(value: String) -> Self {
RelativePath(value.into())
}
}
impl From<OsString> for RelativePath {
fn from(value: OsString) -> Self {
RelativePath(value.into())
}
}
impl From<RelativePath> for String {
fn from(value: RelativePath) -> Self {
value.to_string()
}
}
impl From<FilePath> for String {
fn from(value: FilePath) -> Self {
value.to_string()
}
}
impl From<crate::address::primitive::UniqueRootAddress> for RelativePath {
fn from(_value: crate::address::primitive::UniqueRootAddress) -> Self {
"".into()
}
}
impl PathAddress for RelativePath {
type Error = FileStoreError;
type Output = RelativePath;
fn path(self, str: &str) -> Result<Self::Output, Self::Error> {
Ok(Self(self.0.join(str)))
}
}
impl Address for RelativePath {
fn own_name(&self) -> String {
self.0
.components()
.last()
.map(|p| {
p.as_os_str()
.to_str()
.expect("Non-unicode is not supported")
})
.unwrap_or("")
.to_owned()
}
fn as_parts(&self) -> Vec<String> {
todo!()
}
}
impl SubAddress<RelativePath> for RelativePath {
type Output = RelativePath;
fn sub(self, sub: RelativePath) -> Self::Output {
Self(self.0.join(sub.0))
}
}
#[derive(Debug, Clone)]
pub struct FileSystemStore {
base_directory: Arc<PathBuf>,
}
impl FileSystemStore {
pub fn new(path: PathBuf) -> Self {
FileSystemStore {
base_directory: Arc::new(path),
}
}
pub fn here() -> StoreResult<Self, Self> {
Ok(Self::new(std::env::current_dir()?))
}
pub fn get_complete_path(&self, addr: RelativePath) -> PathBuf {
self.base_directory.join(addr.0)
}
}
impl Store for FileSystemStore {
type Error = FileStoreError;
type RootAddress = RelativePath;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FileOrDir {
File(String),
Dir,
}
impl Addressable<RelativePath> for FileSystemStore {
type DefaultValue = FileOrDir;
}
impl AddressableRead<String, RelativePath> for FileSystemStore {
async fn read(&self, addr: &RelativePath) -> StoreResult<Option<String>, Self> {
match tokio::fs::read(self.get_complete_path(addr.clone())).await {
Ok(fil) => Ok(Some(String::from_utf8(fil)?)),
Err(e) => match e.kind() {
std::io::ErrorKind::NotFound => Ok(None),
_ => Err(e.into()),
},
}
}
}
impl AddressableWrite<String, RelativePath> for FileSystemStore {
async fn write(&self, addr: &RelativePath, value: &Option<String>) -> StoreResult<(), Self> {
let path = self.get_complete_path(addr.clone());
match value {
None => todo!("deletion"),
Some(contents) => Ok(tokio::fs::write(path, contents).await?),
}
}
}
impl AddressableRead<Existence, RelativePath> for FileSystemStore {
async fn read(&self, addr: &RelativePath) -> StoreResult<Option<Existence>, Self> {
let m = tokio::fs::metadata(self.get_complete_path(addr.clone())).await;
match m {
Ok(_) => Ok(Some(Existence)),
Err(e) => match e.kind() {
std::io::ErrorKind::NotFound => Ok(None),
_ => Err(e.into()),
},
}
}
}
impl<'a> AddressableList<'a, RelativePath> for FileSystemStore {
type AddedAddress = RelativePath;
type ItemAddress = RelativePath;
type ListOfAddressesStream = std::pin::Pin<
Box<
dyn 'a
+ futures::Stream<Item = StoreResult<(Self::AddedAddress, Self::ItemAddress), Self>>,
>,
>;
fn list(&self, addr: &RelativePath) -> Self::ListOfAddressesStream {
let this = self.clone();
let addr = addr.clone();
let addr2 = addr.clone();
stream::once(async move {
let stream = tokio_stream::wrappers::ReadDirStream::new(
tokio::fs::read_dir(this.get_complete_path(addr.clone())).await?,
)
.map_err(|e| e.into());
Ok::<_, FileStoreError>(stream)
})
.try_flatten()
.and_then(move |de: DirEntry| {
let addr = addr2.clone();
async move {
let name = de.file_name();
Ok((name.clone().into(), addr.sub(name.into())))
}
})
.boxed_local()
}
}
impl<'a> AddressableTree<'a, RelativePath, FilePath> for FileSystemStore {
async fn branch_or_leaf(
&self,
addr: RelativePath,
) -> StoreResult<BranchOrLeaf<RelativePath, FilePath>, Self> {
let typ = tokio::fs::metadata(self.get_complete_path(addr.clone()))
.await?
.file_type();
if typ.is_dir() {
Ok(BranchOrLeaf::Branch(addr))
} else if typ.is_file() {
Ok(BranchOrLeaf::Leaf(addr.into()))
} else {
Err(FileStoreError::UnsupportedFeature(format!(
"Neither file nor dir: {typ:?}"
)))
}
}
}
impl Address for FilePath {
fn own_name(&self) -> String {
self.0.own_name()
}
fn as_parts(&self) -> Vec<String> {
self.0.as_parts()
}
}