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
264
265
266
267
268
269
270
271
272
273
use std::{
borrow::Cow,
fmt::Display,
path::{Path, PathBuf},
sync::Arc,
};
/// A trait for providing file contents.
pub trait FileProvider {
/// Reads the contents of the file at the given path as bytes.
///
/// # Errors
/// - If an error occurs while reading the file.
/// - If the file does not exist.
fn read_bytes<P: AsRef<Path>>(&self, path: P) -> Result<Cow<[u8]>, Error>;
/// Reads the contents of the file at the given path.
///
/// # Errors
/// - If an error occurs while reading the file.
/// - If the file does not exist.
/// - If the file is not valid UTF-8.
fn read_str<P: AsRef<Path>>(&self, path: P) -> Result<Cow<str>, Error> {
let bytes = self.read_bytes(path)?;
let string = std::str::from_utf8(&bytes)
.map_err(|err| {
let arc: Arc<dyn std::error::Error + Send + Sync> = Arc::new(err);
Error::other(arc)
})?
.to_string();
Ok(Cow::Owned(string))
}
}
/// Provides file contents from the file system.
#[derive(Debug, Clone)]
pub struct FsProvider {
/// The root directory to base paths off of.
root: PathBuf,
}
impl Default for FsProvider {
fn default() -> Self {
Self {
root: PathBuf::from("."),
}
}
}
impl<P> From<P> for FsProvider
where
P: Into<PathBuf>,
{
fn from(root: P) -> Self {
Self { root: root.into() }
}
}
impl FileProvider for FsProvider {
fn read_bytes<P: AsRef<Path>>(&self, path: P) -> Result<Cow<[u8]>, Error> {
let full_path = self.root.join(path);
std::fs::read(full_path)
.map(Cow::Owned)
.map_err(Error::from)
}
fn read_str<P: AsRef<Path>>(&self, path: P) -> Result<Cow<str>, Error> {
let full_path = self.root.join(path);
std::fs::read_to_string(full_path)
.map(Cow::Owned)
.map_err(Error::from)
}
}
/// The error type for [`FileProvider`] operations.
#[allow(clippy::module_name_repetitions)]
#[derive(Debug, Clone, thiserror::Error)]
pub struct Error {
kind: std::io::ErrorKind,
#[source]
error: Option<Arc<dyn std::error::Error + Send + Sync>>,
}
impl Error {
/// Creates a new [`Error`] from a known kind of error as well as an
/// arbitrary error payload.
///
/// The `error` argument is an arbitrary
/// payload which will be contained in this [`Error`].
///
/// Note that this function allocates memory on the heap.
/// If no extra payload is required, use the `From` conversion from
/// `ErrorKind`.
pub fn new<E>(kind: std::io::ErrorKind, error: E) -> Self
where
E: Into<Arc<dyn std::error::Error + Send + Sync>>,
{
Self {
kind,
error: Some(error.into()),
}
}
/// Creates a new [`Error`] from an arbitrary error payload.
///
/// It is a shortcut for [`Error::new`]
/// with [`std::io::ErrorKind::Other`].
pub fn other<E>(error: E) -> Self
where
E: Into<Arc<dyn std::error::Error + Send + Sync>>,
{
Self::new(std::io::ErrorKind::Other, error)
}
/// Returns a reference to the inner error wrapped by this error (if any).
///
/// If this [`Error`] was constructed via [`Self::new`] then this function will
/// return [`Some`], otherwise it will return [`None`].
#[must_use]
pub fn get_ref(&self) -> Option<&(dyn std::error::Error + Send + Sync + 'static)> {
return self.error.as_deref();
}
/// Consumes the [`Error`], returning its inner error (if any).
///
/// If this [`Error`] was constructed via [`Self::new`] then this function will
/// return [`Some`], otherwise it will return [`None`].
#[must_use]
pub fn into_inner(self) -> Option<Arc<dyn std::error::Error + Send + Sync>> {
self.error
}
/// Returns the corresponding [`std::io::ErrorKind`] for this error.
#[must_use]
pub fn kind(&self) -> std::io::ErrorKind {
self.kind
}
}
impl Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.error {
Some(err) => write!(f, "{}: {}", self.kind, err),
None => write!(f, "{}", self.kind),
}
}
}
impl PartialEq for Error {
fn eq(&self, _: &Self) -> bool {
false
}
}
impl From<std::io::ErrorKind> for Error {
fn from(value: std::io::ErrorKind) -> Self {
Self {
kind: value,
error: None,
}
}
}
impl From<std::io::Error> for Error {
fn from(value: std::io::Error) -> Self {
let kind = value.kind();
let error = value.into_inner().map(Arc::from);
Self { kind, error }
}
}
#[cfg(feature = "shulkerbox")]
mod vfs {
use std::{borrow::Cow, sync::Arc};
use super::{Error, FileProvider, Path};
use shulkerbox::virtual_fs::{VFile, VFolder};
impl FileProvider for VFolder {
fn read_bytes<P: AsRef<Path>>(&self, path: P) -> Result<Cow<[u8]>, Error> {
normalize_path_str(path).map_or_else(
|| Err(Error::from(std::io::ErrorKind::InvalidData)),
|path| {
self.get_file(&path)
.ok_or_else(|| Error::from(std::io::ErrorKind::NotFound))
.map(|file| Cow::Borrowed(file.as_bytes()))
},
)
}
fn read_str<P: AsRef<Path>>(&self, path: P) -> Result<Cow<str>, Error> {
normalize_path_str(path).map_or_else(
|| Err(Error::from(std::io::ErrorKind::InvalidData)),
|path| {
self.get_file(&path)
.ok_or_else(|| Error::from(std::io::ErrorKind::NotFound))
.and_then(|file| match file {
VFile::Text(text) => Ok(Cow::Borrowed(text.as_str())),
VFile::Binary(bin) => {
let string = std::str::from_utf8(bin).map_err(|err| {
let arc: Arc<dyn std::error::Error + Send + Sync> =
Arc::new(err);
Error::new(std::io::ErrorKind::InvalidData, arc)
})?;
Ok(Cow::Borrowed(string))
}
})
},
)
}
}
fn normalize_path_str<P: AsRef<Path>>(path: P) -> Option<String> {
let mut err = false;
let res = path
.as_ref()
.to_str()?
.split('/')
.fold(Vec::new(), |mut acc, el| match el {
"." | "" => acc,
".." => {
let popped = acc.pop();
if popped.is_none() {
err = true;
}
acc
}
_ => {
acc.push(el);
acc
}
})
.join("/");
if err {
None
} else {
Some(res)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_normalize_path() {
assert_eq!(normalize_path_str("a/b/c"), Some("a/b/c".to_string()));
assert_eq!(normalize_path_str("a/b/../c"), Some("a/c".to_string()));
assert_eq!(normalize_path_str("./a/b/c"), Some("a/b/c".to_string()));
assert_eq!(normalize_path_str("../a/b/c"), None);
}
#[test]
fn test_vfolder_provider() {
let mut dir = VFolder::new();
dir.add_file("foo.txt", VFile::Text("foo".to_string()));
dir.add_file("bar/baz.txt", VFile::Text("bar, baz".to_string()));
assert_eq!(
dir.read_str("foo.txt").unwrap().into_owned(),
"foo".to_string()
);
assert_eq!(
dir.read_str("bar/baz.txt").unwrap().into_owned(),
"bar, baz".to_string()
);
assert!(dir.read_str("nonexistent.txt").is_err());
}
}
}